COUNT CASE and WHEN statement in MySQL COUNT CASE and WHEN statement in MySQL mysql mysql

COUNT CASE and WHEN statement in MySQL


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.


You can exploit the fact that COUNT only counts non-null values:

SELECT COUNT(IFNULL(t.your_column, 1)) AS numNull,       COUNT(t.your_column) AS numNotNull  FROM YOUR_TABLE t

Another approach is to use the fact that logical conditions get evaluated to numeric 0 and 1, so this will also work:

SELECT IFNULL(SUM(t.your_column IS NULL), 0) AS numNull,       IFNULL(SUM(t.your_column IS NOT NULL), 0) AS numNotNull  FROM YOUR_TABLE t

Please note that SUM will return NULL if there are no rows selected (i.e. the table is empty or a where condition excludes all rows), this is the reason for the IFNULL statements.