gotchasqlMajor
Why does COUNT() aggregate return 0 for 'NULL'?
Viewed 0 times
whyreturnnullfordoescountaggregate
Problem
A SELECT statement returns several rows:
I get 47 rows that have 'NULL' for ColA within TableA.
If I add an aggregate to this query:
I get
Why is this happening, and what can I do to avoid this?
SELECT
ColA
FROM
TableA
WHERE
ColA IS NULLI get 47 rows that have 'NULL' for ColA within TableA.
ColA
NULL
NULL
NULL
etc...If I add an aggregate to this query:
SELECT
ColA,
COUNT(ColA) AS theCount
FROM
TableA
WHERE
ColA IS NULL
GROUP BY ColAI get
ColA | theCount
NULL | 0Why is this happening, and what can I do to avoid this?
Solution
Aggregate functions ignore null values.
So
is equivalent to
As all of your values are null,
If you want to count the rows that are null, you need
Or simpler:
If you want to count NULL and NOT NULL values in a single query, use:
So
SELECT COUNT(cola) AS thecount
FROM tableais equivalent to
SELECT count(*) AS thecount
FROM tablea
WHERE cola IS NOT NULL;As all of your values are null,
count(cola) has to return zero.If you want to count the rows that are null, you need
count(*)SELECT cola,
count(*) AS theCount
FROM tablea
WHERE cola is null
GROUP BY cola;Or simpler:
SELECT count(*) AS theCount
FROM tablea
WHERE cola is null;If you want to count NULL and NOT NULL values in a single query, use:
SELECT count(cola) as not_null_count,
count(case when cola is null then 1 end) as null_count
FROM tablea;Code Snippets
SELECT COUNT(cola) AS thecount
FROM tableaSELECT count(*) AS thecount
FROM tablea
WHERE cola IS NOT NULL;SELECT cola,
count(*) AS theCount
FROM tablea
WHERE cola is null
GROUP BY cola;SELECT count(*) AS theCount
FROM tablea
WHERE cola is null;SELECT count(cola) as not_null_count,
count(case when cola is null then 1 end) as null_count
FROM tablea;Context
StackExchange Database Administrators Q#153586, answer score: 35
Revisions (0)
No revisions yet.