This works for Oracle and SQL Server (you might be able to get it to work on another RDBMS):
select sum(case when a is null then 1 else 0 end) count_nulls
, count(a) count_not_nulls
from us;
Or:
select count(*) - count(a), count(a) from us;
Answer from user155789 on Stack OverflowThis works for Oracle and SQL Server (you might be able to get it to work on another RDBMS):
select sum(case when a is null then 1 else 0 end) count_nulls
, count(a) count_not_nulls
from us;
Or:
select count(*) - count(a), count(a) from us;
If I understood correctly you want to count all NULL and all NOT NULL in a column...
If that is correct:
SELECT count(*) FROM us WHERE a IS NULL
UNION ALL
SELECT count(*) FROM us WHERE a IS NOT NULL
Edited to have the full query, after reading the comments :]
SELECT COUNT(*), 'null_tally' AS narrative
FROM us
WHERE a IS NULL
UNION
SELECT COUNT(*), 'not_null_tally' AS narrative
FROM us
WHERE a IS NOT NULL;
Videos
I'm working on a building a simple data quality solution where the requirement is to count all nulls for all columns in all tables. We have over 1000 tables. Tried different methods such as looping thru all tables and query each table but it's too expensive and takes forever. Any suggestions?
Try
SELECT
DATE_FORMAT(registDate, '%m-%Y') AS month,
COUNT(name) AS register,
SUM(!ISNULL(visited)) AS visited,
SUM(ISNULL(visited)) AS not_visited
FROM mytable
GROUP BY DATE_FORMAT(registDate, '%m-%Y');
No need to create another column.
The first thing to do is 'add on' a column for the month:
select *, date_format(registDate, '%Y-%m') as regist_month
from mytable
Then you can get all the counts:
select
regist_month
, count(registDate) as count_registered
, sum(case when visited is not null then 1 else 0 end) as count_visited
, sum(case when visited is null then 1 else 0 end) as count_not_visited
from (
select *, date_format(registDate, '%Y-%m') as regist_month
from mytable
) group by regist_month
COUNT counts values, since null is not a value it does not get counted.
If you want to count all null values you could do something like this:
SELECT COUNT(ID) as NotNull, SUM(CASE WHEN ID IS NULL then 1 else 0 end) as NullCount
Why aren't nulls counted in COUNT(columnname)?
COUNT(*)
will count all rows
COUNT(columnname)
will count all rows, except those rows where columnname IS NULL.
And what's the reason?
It's just that the COUNT() function is designed to work this way: NULL values are treated differently from other values, because NULL can be considered as a placeholder for "unknown" values, so it is very common that you just want to count rows that have a real value and skip rows that don't have.
Counting the rows that don't have a value is less common, and SQL doesn't provide a function for it. But you can calculate it easily:
SELECT
COUNT(*) As rows,
COUNT(columnname) AS non_null_count,
COUNT(*) - COUNT(columnname) AS null_count
FROM
yourtable