I am working in MSSQL and I have stored procedure where I pass multiple parameters and some of them can be null. I did a research and found that if I want to include a WHERE
condition with those nullable parameters, I should do it like this
DECLARE @Firstname AS VARCHAR(50) = 'Tasos'
SELECT *
FROM Names n
WHERE @Firstname is null or n.Firstname LIKE @Firstname + '%'
In my case I have multiple parameters, but for simplicity, I give you an example with just one parameter.
DECLARE @Firstname AS VARCHAR(50) = 'Tasos';
SELECT *
FROM Names AS n
WHERE @Firstname IS NULL OR n.Firstname LIKE @Firstname + '%'
The above query needs about 800k logical reads and 20 secs to run. However,
DECLARE @Firstname AS VARCHAR(50) = 'Tasos';
SELECT *
FROM Names AS n
WHERE n.Firstname LIKE @Firstname + '%'
needs only 5 logical reads with an instant result.
Can someone explain to me why the first part of the WHERE condition has such a huge impact in the performance?
EDIT:
I managed to implemented by constructing the sql query dynamically as a string and then use EXECUTE sp_executesql @SQL_string;
. However, my question was mostly about why the above is happening since the check is happening in the variable and it doesn't add any checks on the actual table.