SQL NULL in Aggregates
What you will learn
- That aggregates skip
NULLvalues - Why
AVGover missing values can mislead - What
SUMandAVGreturn when no rows match - How to treat missing values as zero with
COALESCE
This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Edit any query and press Run. Reset data puts the original rows back.
1. Aggregates skip NULL
Lesson 3.4 showed that COUNT(column) skips NULL. The same is true for SUM, AVG, MIN and MAX: a NULL is ignored, not treated as zero. Only COUNT(*) counts every row.
Here is a column that has missing values. Compare the number of rows with the number of values the aggregates really used:
Some customers have no phone, so we use the length of the phone (a number) as a stand-in value:
SELECT COUNT(*) AS rows_in_table,
COUNT(LENGTH(phone)) AS values_used,
MIN(LENGTH(phone)) AS shortest,
MAX(LENGTH(phone)) AS longest,
ROUND(AVG(LENGTH(phone)), 2) AS average_length
FROM customers;
rows_in_table values_used shortest longest average_length
------------- ----------- -------- ------- --------------
420 336 12 12 12.0
(1 row)
The note of an audit entry may be missing, so we use the length of the note:
SELECT COUNT(*) AS rows_in_table,
COUNT(LENGTH(note)) AS values_used,
MIN(LENGTH(note)) AS shortest,
MAX(LENGTH(note)) AS longest,
ROUND(AVG(LENGTH(note)), 2) AS average_length
FROM audit_log;
rows_in_table values_used shortest longest average_length
------------- ----------- -------- ------- --------------
120 91 12 15 13.53
(1 row)
Some enrollments have no grade yet:
SELECT COUNT(*) AS rows_in_table,
COUNT(grade) AS values_used,
MIN(grade) AS lowest,
MAX(grade) AS highest,
ROUND(AVG(grade), 2) AS average_grade
FROM enrollments;
rows_in_table values_used lowest highest average_grade
------------- ----------- ------ ------- -------------
1002 809 28.7 100.0 71.25
(1 row)
The aggregates worked only on the rows that had a value. That is usually what you want, but you must know it.
2. The average of what?
AVG(x) is the sum of the values divided by the number of non-NULL values, not by the number of rows. If missing values really mean zero, the plain average is too high. Compare:
SELECT ROUND(AVG(LENGTH(phone)), 2) AS average_of_existing,
ROUND(AVG(COALESCE(LENGTH(phone), 0)), 2) AS average_with_zero_for_missing,
ROUND(1.0 * SUM(LENGTH(phone)) / COUNT(*), 2) AS same_as_the_line_above
FROM customers;
average_of_existing average_with_zero_for_missing same_as_the_line_above
------------------- ----------------------------- ----------------------
12.0 9.6 9.6
(1 row)
SELECT ROUND(AVG(LENGTH(note)), 2) AS average_of_existing,
ROUND(AVG(COALESCE(LENGTH(note), 0)), 2) AS average_with_zero_for_missing,
ROUND(1.0 * SUM(LENGTH(note)) / COUNT(*), 2) AS same_as_the_line_above
FROM audit_log;
average_of_existing average_with_zero_for_missing same_as_the_line_above
------------------- ----------------------------- ----------------------
13.53 10.26 10.26
(1 row)
SELECT ROUND(AVG(grade), 2) AS average_of_graded,
ROUND(AVG(COALESCE(grade, 0)), 2) AS average_with_zero_for_ungraded,
ROUND(1.0 * SUM(grade) / COUNT(*), 2) AS same_as_the_line_above
FROM enrollments;
average_of_graded average_with_zero_for_ungraded same_as_the_line_above
----------------- ------------------------------ ----------------------
71.25 57.53 57.53
(1 row)
Which one is right depends on the question. "Average grade of the students who have a grade" is the first. "Average if ungraded counted as zero" is the second, and it is usually a wrong question: a missing grade is not a zero grade. Think before you replace NULL with 0.
3. NULL group in GROUP BY
In GROUP BY, all NULLs form one group of their own:
SELECT phone IS NULL AS no_phone, COUNT(*) AS customers FROM customers GROUP BY phone IS NULL ORDER BY no_phone;
no_phone customers
-------- ---------
0 336
1 84
(2 rows)
SELECT note, COUNT(*) AS entries FROM audit_log GROUP BY note ORDER BY note LIMIT 4;
note entries
--------------- -------
NULL 29
address changed 19
card replaced 20
limit raised 21
(4 rows)
SELECT guardian_name IS NULL AS no_guardian, COUNT(*) AS students FROM students GROUP BY guardian_name IS NULL ORDER BY no_guardian;
no_guardian students
----------- --------
0 322
1 38
(2 rows)
(In the Bank example the first row, with a NULL note, is the group of entries without a note.)
4. No rows at all
If a WHERE matches no rows, COUNT(*) returns 0, but SUM, AVG, MIN and MAX return NULL: there is nothing to add or average. Wrap SUM in COALESCE when a report needs a zero:
SELECT COUNT(*) AS rows_found,
SUM(1) AS sum_of_nothing,
COALESCE(SUM(1), 0) AS zero_for_a_report
FROM sqlite_master WHERE name = 'no_such_table';
rows_found sum_of_nothing zero_for_a_report
---------- -------------- -----------------
0 NULL 0
(1 row)
SELECT COUNT(*) AS rows_found,
SUM(1) AS sum_of_nothing,
COALESCE(SUM(1), 0) AS zero_for_a_report
FROM sqlite_master WHERE name = 'no_such_table';
rows_found sum_of_nothing zero_for_a_report
---------- -------------- -----------------
0 NULL 0
(1 row)
SELECT COUNT(*) AS rows_found,
SUM(1) AS sum_of_nothing,
COALESCE(SUM(1), 0) AS zero_for_a_report
FROM sqlite_master WHERE name = 'no_such_table';
rows_found sum_of_nothing zero_for_a_report
---------- -------------- -----------------
0 NULL 0
(1 row)
5. Missing is not zero
A short checklist when a column has missing values:
- Count them:
COUNT(*) - COUNT(column)(lesson 3.4). - Decide what they mean: unknown, not applicable, or really zero.
- Choose: skip them (the default), or
COALESCEthem to a value, and say so in the report.
Worked example: two averages, two meanings
A table of 10 exam results has 8 grades and 2 missing (the students were absent). The 8 grades add up to 560.
| Average | Calculation | Result | Meaning |
|---|---|---|---|
| of the graded | AVG(grade) = 560 / 8 |
70.0 | how well those who sat did |
| missing as zero | AVG(COALESCE(grade, 0)) = 560 / 10 |
56.0 | punishes the absent students |
Reporting 56 as "the class average" would be unfair if the two were absent for a good reason. The numbers are made up.
Common mistakes
- Assuming
AVGdivides by the number of rows. It divides by the number of non-NULLvalues. - Replacing
NULLwith 0 without thinking. - Expecting
SUMof no rows to be 0. It isNULL. - Forgetting that
NULLs form their own group inGROUP BY.
Key takeaways
SUM,AVG,MIN,MAXandCOUNT(column)skipNULL;COUNT(*)counts rows.AVGdivides by the number of values, not the number of rows.- No matching rows:
COUNTis0;SUM,AVG,MIN,MAXareNULL. - Use
COALESCEdeliberately, and say what a missing value means.
Practice
1. A column has 10 rows and 4 are NULL. What does COUNT(column) return?
Show answer
6, the rows with a value.
2. What does AVG divide by?
Show answer
The number of non-NULL values.
3. What does SELECT SUM(price) FROM products WHERE 1 = 0; return?
Show answer
NULL: there are no rows to add.
4. How do you make that result 0 instead?
Show answer
SELECT COALESCE(SUM(price), 0) FROM products WHERE 1 = 0;
5. Why can treating a missing grade as 0 be wrong?
Show answer
A missing grade is unknown, not zero; counting it as zero lowers the average unfairly.
6. How do NULL values appear in a GROUP BY result?
Show answer
As one group of their own, shown with a NULL value in the grouping column.