How can you use COUNT() in a comparison in a SELECT CASE clause in Sql Server?

Panzercrisis picture Panzercrisis · Oct 30, 2012 · Viewed 43k times · Source

Let's say you want do something along the following lines:

SELECT CASE 
    WHEN (SELECT COUNT(id) FROM table WHERE column2 = 4) > 0
    THEN 1 ELSE 0 END

Basically just return 1 when there's one or more rows in the table, 0 otherwise. There has to be a grammatically correct way to do this. What might it be? Thanks!

Answer

D'Arcy Rittich picture D'Arcy Rittich · Oct 30, 2012

Question: return 1 when there's one or more rows in the table, 0 otherwise:

In this case, there is no need for COUNT. Instead, use EXISTS, which rather than counting all records will return as soon as any is found, which performs much better:

SELECT CASE 
    WHEN EXISTS (SELECT 1 FROM table WHERE column2 = 4)    
        THEN 1  
    ELSE 0 
END