Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 645
Panzercrisis Avatar asked Oct 30 '12 13:10

Panzercrisis


People also ask

Can I use count in case statement in SQL?

The function counta can be implemented with a case expression as well. For that, SQL makes a distinction between empty strings and the null value. The following expression counts the rows that have neither the null value or the empty string.

How do you use count in select statement?

In SQL, you can make a database query and use the COUNT function to get the number of rows for a particular group in the table. Here is the basic syntax: SELECT COUNT(column_name) FROM table_name; COUNT(column_name) will not include NULL values as part of the count.

Can we use count in select query?

SQL SELECT statement can be used along with COUNT(*) function to count and display the data values. The COUNT(*) function represents the count of all rows present in the table (including the NULL and NON-NULL values).

What is the use of count () and count (*) in SQL?

COUNT() With NULL ValuesSELECT COUNT(*) returns the count of all records in the result set regardless of NULL values. SELECT COUNT(attribute) returns the count of records containing non-NULL values of the specified column.


2 Answers

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
like image 74
D'Arcy Rittich Avatar answered Nov 15 '22 19:11

D'Arcy Rittich


Mahmoud Gammal posted an answer with an interesting approach. Unfortunately the answer was deleted due to the fact that it returned the count of records instead of just 1. This can be fixed using the sign function, leading to this more compact solution:

SELECT sign(count(*)) FROM table WHERE column2 = 4

I posted this because I find it an interesting approach. In production I'd usually end up with something close to RedFilter's answer.

like image 36
Cristian Lupascu Avatar answered Nov 15 '22 21:11

Cristian Lupascu