Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL ISNULL in where Condition performance

I am looking for opinions and possibly a concrete answer to the following.
This question applies for SQL Server version 2008 R2+

In a stored procedure, I have an optional query parameter of type DATE, lets call it @MyVar.

The stored procedure executes the following query:

SELECT A, B, C
FROM MyTable
WHERE MyTable.Field1 = ISNULL(@MyVar,MyTable.Field1)

What is the cost of doing the ISNULL(@MyVar,MyTable.Field1) if @MyVar is NULL? I am wondering if it's better to split the cases such as:

IF (@MyVar IS NULL)
    SELECT A, B, C
    FROM MyTable
ELSE
    SELECT A, B, C
    FROM MyTable
    WHERE MyTable.Field1 = @MyVar

Thanks!

like image 262
DOMZE Avatar asked Dec 25 '22 05:12

DOMZE


1 Answers

A more elegant approach would be:

SELECT A, B, C
FROM   MyTable
WHERE  MyTable.Field1 = @MyVar
   OR  @MyVar IS NULL
OPTION(RECOMPILE)

edit

Based on suggestion by @JamesZ, added option(recompile) so that an index on field1 will be used (if it exists).

edit2 (Thanks @Y.B. for pointing it out.)

If field1 can be null as well use something like:

SELECT A, B, C
    FROM   MyTable
    WHERE  MyTable.Field1 = @MyVar
       OR  (@MyVar IS NULL AND MyTable.Field1 IS NULL)
    OPTION(RECOMPILE)

This already shows the problems with 'catch all' queries. You could also, for example, replace the AND in the last query with OR, which would give yet another (theoretical) result set, but could potentially be correct as well.

like image 199
HoneyBadger Avatar answered Jan 06 '23 09:01

HoneyBadger