HiveBrain v1.2.0
Get Started
← Back to all entries
gotchasqlMajor

Why does COUNT() aggregate return 0 for 'NULL'?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
whyreturnnullfordoescountaggregate

Problem

A SELECT statement returns several rows:

SELECT
  ColA
FROM
  TableA
WHERE
  ColA IS NULL


I 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 ColA


I get

ColA | theCount
NULL | 0


Why is this happening, and what can I do to avoid this?

Solution

Aggregate functions ignore null values.

So

SELECT COUNT(cola) AS thecount
FROM tablea


is 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 tablea
SELECT 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.