What is the best way to include an input param in the WHERE
clause but exclude it if it is null?
There are a number of ways I believe, but I can't seem to remember then.
Also could I use the COALESCE()
? But I think this is only for SELECTing values?
Edit
To clarify, let's say a variable called @code ="1"
then my where would be Where type='B' AND code = @code
but if @code is null
then I only want Where type='B'
- notice the missing code = @code
.
You can use IsNull
EDIT:
What you described in the comment can be done like:
check out this neat article here. It explains why "where (@param is null or Field=@param)" doesn't perform well and what to use instead.
How about
This question really helped me with a similar issue that had a few of us scratching our heads for a bit. I only write it up in case somebody else tries the same approach and cannot figure out why it does not work.
I was trying to only evaluate a part of a multipart WHERE clause if the @Parameter was not null. I tried to do this as below but always had no rows returned if @Parameter was null.
I incorrectly thought that
(@Parameter is not null AND [AlternateID] = @Parameter)
would simply not form part of the full WHERE clause is @Parameter was null. However it was making the entire WHERE clause return false. The remedy was to add an OR 1=1 as below:Of course the approach outlined by Ali (not enough reputation to upvote) solves this more efficiently.
I’d like to suggest a solution which I found on another site:
With this solution if the user selects
null
for your parameter then your query will return all the rows as the result.You can use ISNULL(), or check for nulls explicitly as others have mentioned. This should be OK as long as you have no more than 1 or 2 optional input parameters. But if there are more parameters, this approach would be very inefficient as the indexes you create on those columns won't be used as you would expect. In such a case i would recommend you to use dynamic SQL. Here is an excellent article that explains why http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/