Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

COUNT CASE and WHEN statement in MySQL

How to use COUNT CASE and WHEN statement in MySQL query, to count when data is NULL and when it is not NULL in one MySQL query?

like image 891
Ivan Tanasijevic Avatar asked Feb 18 '11 18:02

Ivan Tanasijevic


People also ask

How do you use case in count?

CASE can be used in conjunction with SUM to return a count of only those items matching a pre-defined condition. (This is similar to COUNTIF in Excel.) The trick is to return binary results indicating matches, so the "1"s returned for matching entries can be summed for a count of the total number of matches.


1 Answers

Use:

SELECT SUM(CASE               WHEN t.your_column IS NULL THEN 1              ELSE 0            END) AS numNull,        SUM(CASE               WHEN t.your_column IS NOT NULL THEN 1              ELSE 0            END) AS numNotNull   FROM YOUR_TABLE t 

That will sum up the column NULL & not NULL for the entire table. It's likely you need a GROUP BY clause, depending on needs.

like image 119
OMG Ponies Avatar answered Sep 20 '22 08:09

OMG Ponies