sql-servert-sql

CASE or AND/OR in WHERE condition. What is the best practice?


i've often come across situations where i can write the conditions of a t-sql query like this...

DECLARE @FirstName NVARCHAR(500)    
SET @FirstName ='Joe'

SELECT * 
FROM dbo.Customers c
WHERE 
    CASE 
        WHEN  @FirstName <> ''  THEN
            CASE WHEN c.FirstName= @FirstName THEN 1 ELSE 0 END
        ELSE 1
     END = 1 

Or like this...

SELECT * 
FROM dbo.Customers c
WHERE 
    (@FirstName = ''  OR (@FirstName <> '' AND c.FirstName = @FirstName))

They both produce the same results and both query plans appears to be the same.

So i'm curious as to which one is best practice or if there are any pitfalls with one over the other?


Solution

  • I think it's also about readability mostly in this case, but you are doing more in the first query example. You're forcing the database to create a value per row of 0 or 1 and requiring the database to check if the value is 0 or 1. The fewer steps the better when creating queries in my opinion.

    I would opt for the second approach although you can probably get rid of @FirstName<> '' since it is unnecessary, so your query cleans up a bit more:

    SELECT * 
    FROM dbo.Customers c
    WHERE 
        (@FirstName = ''  OR c.FirstName = @FirstName)
    

    EDIT: Martin Smith provided a very good insight that you might want to consider.