I need to write a SQL query and want to check if this is the optimized approach. If not, what would be a better query for this scenario?
All the joining tables are pretty big(approx 150million records).
Below is the sample code.
DECLARE @inputIds VARCHAR(50) = NULL; -- This can have a comma-separated list of ids as well.
DECLARE @inputIdsVar TABLE (ID INT);
INSERT INTO @inputIdsVar SELECT DISTINCT CAST(value AS INT) FROM fnSplit(@inputIds, ','); -- Some custom function to split the Ids list.
SELECT * FROM TABLE1 tbl1
JOIN TABLE2 tbl2 ON tbl1.JoinIndex1 = tbl2.JoinIndex1 OR @inputVar IS NULL
JOIN TABLE2 tbl3 ON tbl2.JoinIndex2 = tbl3.JoinIndex2 OR @inputVar IS NULL
JOIN @inputIdsVar iiv ON tbl3.ID = iiv.ID OR @inputVar IS NULL
WHERE tbl1.Key = 'blah'
Here, my expected output is as follows:-
- If
@inputVaris NULL, return all records fromTABLE1. - If
@inputVaris NOT NULL, join with 2 other tables and return only the filtered records. Join with 2 other tables is required because the passed-in variable is a comma-separated id list which is present inTABLE3.
Any help would be appreciated.
inputIdsVaris a TABLE variable