Sub topic 8
Aggregates and NULL: COUNT(*) vs COUNT(column), SUM, AVG
This chapter assumes you can write SELECT, WHERE, and GROUP BY queries. It also assumes you know that a comparison with NULL yields UNKNOWN, as covered earlier. Here you will learn how aggregate functions treat NULL, why the same table can give several different "averages", and how to get the result you actually mean.
The core rule
An aggregate function collapses many rows into one value. Most aggregates follow one rule: they discard NULL inputs before computing. The exception is COUNT(*), which counts rows and never looks at column values.
The examples use the sample table from earlier chapters. Ada and Cy have no commission recorded.
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name VARCHAR(50) NOT NULL,
manager_id INTEGER,
commission NUMERIC(8,2)
);
INSERT INTO employees (id, name, manager_id, commission) VALUES
(1, 'Ada', NULL, NULL),
(2, 'Ben', 1, 100.00),
(3, 'Cy', 1, NULL),
(4, 'Di', 2, 300.00);SELECT COUNT(*) AS all_rows, -- 4
COUNT(commission) AS with_commission, -- 2
SUM(commission) AS total, -- 400.00
AVG(commission) AS avg_non_null, -- 200.00
AVG(COALESCE(commission, 0)) AS avg_with_zeros -- 100.00
FROM employees;COUNT(*) versus COUNT(column)
COUNT(*) returns the number of rows in the group. It does not matter which columns are NULL, or whether every column in a row is NULL.
COUNT(column) returns the number of rows where that column is not NULL. It is shorthand for counting the rows that satisfy column IS NOT NULL.
COUNT(1) and COUNT(*) give the same result. The literal 1 is never NULL, so every row counts. Neither is faster in any mainstream database, so prefer COUNT(*) because it states the intent.
COUNT(DISTINCT column) counts distinct non-NULL values. NULL is not counted as a value of its own:
SELECT COUNT(DISTINCT manager_id) AS distinct_managers -- 2 (managers 1 and 2)
FROM employees;Ada's NULL manager_id adds nothing. If you want "number of distinct values, with NULL counted as one", you have to add it yourself, for example with COUNT(DISTINCT manager_id) + MAX(CASE WHEN manager_id IS NULL THEN 1 ELSE 0 END).
The two counts together are a handy way to measure missing data:
SELECT COUNT(*) - COUNT(commission) AS missing_commissions -- 2
FROM employees;SUM, MIN, and MAX
SUM adds the non-NULL values. NULLs behave like absent rows, not like zeros. For SUM the difference is invisible, because adding zero changes nothing. For AVG it changes the answer.
MIN and MAX also skip NULLs. MAX(commission) is 300.00 and MIN(commission) is 100.00. A NULL never wins as the smallest value, even though some databases sort NULLs first in ORDER BY.
AVG and the denominator
AVG(x) is equivalent to SUM(x) / COUNT(x). The denominator is the count of non-NULL values, not the count of rows. In the sample data, the average of Ben's and Di's commissions is 200.00. The average across all four employees, treating a missing commission as zero, is 100.00.
Which number is right depends on what NULL means in your data:
- If NULL means "not applicable" or "unknown", the average of the known values (200) is honest. Replacing NULL with 0 invents data.
- If NULL means "none earned", then zero is the real value and
AVG(COALESCE(commission, 0))is correct.
Some systems also differ in the type of the result. In SQL Server, AVG over an integer column returns an integer and truncates the fraction. PostgreSQL returns numeric. Cast first if you need a fraction everywhere: AVG(CAST(qty AS DECIMAL(10,2))).
Empty groups and all-NULL groups
When no non-NULL values reach an aggregate, SUM, AVG, MIN, and MAX return NULL. COUNT is the exception and returns 0.
SELECT COUNT(commission) AS cnt, -- 0
SUM(commission) AS total, -- NULL
AVG(commission) AS mean -- NULL
FROM employees
WHERE commission IS NULL;The same applies when the WHERE clause matches no rows at all. A query with an aggregate and no GROUP BY still returns exactly one row, and that row holds NULL for SUM and 0 for COUNT.
If a report must show 0 for "nothing", wrap the aggregate, not the column:
SELECT COALESCE(SUM(commission), 0) AS total_commission
FROM employees
WHERE commission IS NULL; -- 0Putting COALESCE inside, as in SUM(COALESCE(commission, 0)), also gives 0 here, but it does extra work per row. It also changes AVG, as shown above.
Aggregates with GROUP BY
Grouping gives each group its own count, sum, and average. Groups can be entirely NULL, and SUM for such a group is NULL:
SELECT manager_id,
COUNT(*) AS employees,
COUNT(commission) AS with_commission,
SUM(commission) AS total_commission,
AVG(commission) AS avg_commission
FROM employees
GROUP BY manager_id
ORDER BY manager_id NULLS LAST;| manager_id | employees | with_commission | total_commission | avg_commission |
|---|---|---|---|---|
| 1 | 2 | 1 | 100.00 | 100.00 |
| 2 | 1 | 1 | 300.00 | 300.00 |
| NULL | 1 | 0 | NULL | NULL |
Two things to notice. Ada's NULL manager_id forms its own group, which a later chapter on GROUP BY covers. Ada's group also shows how COUNT(commission) (0) and SUM(commission) (NULL) disagree about an empty input.
The same rules apply in HAVING. HAVING AVG(commission) > 150 is UNKNOWN for a group whose average is NULL, so that group is removed. A group with no commissions can never pass such a filter.
Aggregating expressions
If the argument is an expression, NULL propagation happens first, row by row. Only then does the aggregate discard NULLs. That makes SUM(a + b) different from SUM(a) + SUM(b):
-- PostgreSQL syntax; most databases support VALUES in FROM with a similar form.
SELECT SUM(a + b) AS sum_of_sums, -- 3 (the row 3 + NULL is dropped)
SUM(a) + SUM(b) AS sums_added -- 6 (4 + 2)
FROM (VALUES (1, 2), (3, NULL)) AS t(a, b);In the first form, the second row produces 3 + NULL = NULL, so the whole row is skipped. In the second form, each column is aggregated alone, so the 3 in column a still counts. If one of the sums could be NULL, SUM(a) + SUM(b) is also NULL, so use COALESCE on each aggregate.
Warnings and silent loss
The SQL standard says a database should raise a completion condition (SQLSTATE 01003, "null value eliminated in set function") when an aggregate drops NULLs. Some systems print it. SQL Server shows "Warning: Null value is eliminated by an aggregate or other SET operation." Many client libraries hide warnings, so you cannot rely on seeing this signal. Check NULL counts yourself when a figure matters.
Common mistakes
- Using
COUNT(column)when you meant to count rows. A row with a NULL in that column silently disappears from the total. - Using
AVGas if it divided by the row count. - Treating a NULL
SUMas an error. It means "no values to add", and it is different from 0. - Comparing an aggregate with
=to a value on a group that may have no values.HAVING SUM(x) = 0does not match a group where the sum is NULL.
Exercise
A table orders has 10 rows. The column discount is NULL in 4 rows and 0 in 2 rows. The other 4 rows hold 10, 10, 20, and 40. What do COUNT(*), COUNT(discount), SUM(discount), and AVG(discount) return?
Show answer
COUNT(*) is 10 because it counts rows. COUNT(discount) is 6 because the 4 NULLs are skipped, while the two zeros count. SUM(discount) is 80 (0 + 0 + 10 + 10 + 20 + 40). AVG(discount) is 80 / 6, about 13.33, because the denominator is the number of non-NULL values. AVG(COALESCE(discount, 0)) would be 80 / 10 = 8.
Exercise
A query SELECT SUM(amount) FROM payments WHERE customer_id = 99 returns NULL, and the report shows a blank cell. Customer 99 has no payments. Rewrite the query so the report shows 0, and explain why COUNT(amount) would not have needed a fix.
Show answer
Use SELECT COALESCE(SUM(amount), 0) FROM payments WHERE customer_id = 99. With no input values, SUM returns NULL, and COALESCE replaces it with 0. COUNT(amount) returns 0 when there are no non-NULL values, so it never produces NULL.