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?
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
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.