I have a number of tables that are joined and have a maximum number of rows about 4 million records. We are searching this table within a Stored Procedure and have an optional parameter with a default value of NULL, below is an redacted example of what we are running, there are more tables involved in the join but only 1 field has a WHERE clause;
DECLARE @OwnerId VARCHAR (50)=NULL
SET @OwnerId = 'A123456'
SELECT DISTINCT
t1.Id,
t2.OwnerId,
FROM
table1 t1
INNER JOIN [table2] t2 m ON t1.Id = t2.id
WHERE
t2.OwnerId = @OwnerId
There is an index on OwnerId. Running the query as above returns the results (600) in less than 1 second. However, as indicated the parameter is optional (along with others) and as soon as I change it slightly to include the value if not NULL (which is what I believe this is doing), the same search goes up to over 10 seconds.
SET @OwnerId = 'A123456'
SELECT DISTINCT
t1.Id,
t2.OwnerId,
FROM
table1 t1
INNER JOIN [table2] t2 ON t1.Id = t2.id
WHERE
(@OwnerId IS null OR (t2.OwnerId = @OwnerId))
I am not able to run an execution plan on the production server but can see a slightly difference when running on a dev server (this does not have 4 million rows), so something is changing, but unsure as to what.