I have a sql proc with some where conditions that look something like this:
AND (@p1 is null OR @p1 like '%' + cast(f1 as varchar(max)) + '%')
Obviously this is to allow the user to filter by a particular parameter if they wish, or not filter they pass in null. The odd thing I noticed today while trying to debug a query is that when I comment this line out the query runs dramatically faster even though @p1 was null.
If @p1 is null, I would have expected SQL to be smart enough to ignore the other OR conditions. Am I doing something wrong here or is there a better way to accomplish this so that SQL doesn't waste time with additional OR conditions when the first one is satisfied? Or is there a fundamental issue I don't understand here about how SQL retrieves the data that prevents it from doing so?