What's the efficient way to check for a null or value for a column in SQL query. Consider a sql table table
with integer column column
which has an index. @value
can be some integer or null ex: 16 or null.
Query 1: Note sure, but it seems one should not rely on the short-circuit in SQL. However, below query always works correctly when @value
is some integer or null.
select * from
table
where (@value is null or column = @value)
The below query is an expanded version of the above query. It works correctly too.
select * from
table
where ((@value is null)
or (@value is not null and column = @value))
Would the above 2 queries would take the advantage of the index?
Query 2: The below query compares the column with non-null @value
else compares the column column
with itself which will always be true and returns everything. It works correctly too. Would this query take advantage of the index?
select * from
table
where (column = isnull(@value, column)
What's the best way?
Note: If the answer varies with databases, I'm interested in MS-SQL.