Sub topic 2
How aggregates and groups treat NULL
This chapter assumes you can write basic SELECT, WHERE and ORDER BY queries, and that you know NULL means "no value recorded". You should also have seen COUNT, SUM, AVG, MIN and MAX on a whole table. Here you learn exactly what each of them does when NULL is present, and what GROUP BY does with NULL in a grouping column.
The sample data
All examples use this small table. It has NULL in three places: a missing amount, a missing shipped_at, and a missing customer_id (a guest checkout).
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER,
amount DECIMAL(10, 2),
shipped_at DATE,
status VARCHAR(20) NOT NULL
);
INSERT INTO orders (order_id, customer_id, amount, shipped_at, status) VALUES
(1, 10, 100.00, '2026-01-05', 'paid'),
(2, 10, NULL, NULL, 'pending'),
(3, 20, 50.00, '2026-01-07', 'paid'),
(4, 20, 150.00, NULL, 'paid'),
(5, NULL, 200.00, '2026-01-09', 'paid'),
(6, NULL, NULL, NULL, 'pending'),
(7, 30, NULL, NULL, 'pending');The core rule: aggregates skip NULL inputs
An aggregate function reads one value per row and collapses them into one result. SUM, AVG, MIN, MAX and COUNT(column) discard every row where that column is NULL before computing. They do not treat NULL as zero, and they do not return NULL because one input was NULL.
SELECT COUNT(*) AS all_rows,
COUNT(amount) AS amounts_present,
SUM(amount) AS total_amount,
AVG(amount) AS avg_amount,
MIN(amount) AS smallest,
MAX(amount) AS largest
FROM orders;| all_rows | amounts_present | total_amount | avg_amount | smallest | largest |
|---|---|---|---|---|---|
| 7 | 4 | 500.00 | 125.00 | 50.00 | 200.00 |
Seven rows exist, but only four have an amount: 100, 50, 150 and 200. SUM adds those four. AVG divides by 4, not by 7. COUNT(*) is the one exception to the skipping rule. It counts rows, so it never looks at any column value. The next chapter covers the COUNT forms in detail.
Why AVG is the aggregate that surprises people
Because AVG skips NULL rows in both the sum and the count, it describes only the rows that have a value. Compare it with an average that treats missing amounts as zero:
SELECT AVG(amount) AS avg_of_known,
AVG(COALESCE(amount, 0)) AS avg_with_zeros,
SUM(amount) / COUNT(*) AS sum_over_all_rows
FROM orders;The first column is 125.00, because 500 / 4. The second and third are about 71.43, because 500 / 7. Neither answer is wrong. They answer different questions: "what is the typical amount when one was recorded?" and "what is the average per order, counting unpriced orders as free?". Decide which question you are asking, then write the query that matches it. Note that COALESCE(amount, 0) goes inside the aggregate, so each row is fixed before the aggregate sees it.
Empty inputs and all-NULL inputs
An aggregate with nothing to aggregate returns NULL, with one exception.
| Function | Over zero rows, or only NULLs |
|---|---|
| COUNT(*) | 0 for zero rows |
| COUNT(column) | 0 |
| SUM, AVG, MIN, MAX | NULL |
This is a common source of NULL showing up in reports. For example, customer 30 has a single order whose amount is NULL, so their SUM is NULL, not 0. If you want zero, wrap the aggregate:
SELECT COALESCE(SUM(amount), 0) AS total_amount
FROM orders
WHERE status = 'cancelled';No order has status cancelled, so no rows reach SUM. Without COALESCE the result would be NULL.
An aggregate query with no GROUP BY always returns exactly one row, even over an empty input. A query with GROUP BY returns one row per group, so an empty input gives zero rows:
-- one row: count 0, total NULL
SELECT COUNT(*) AS n, SUM(amount) AS total
FROM orders
WHERE status = 'cancelled';
-- zero rows
SELECT customer_id, COUNT(*) AS n
FROM orders
WHERE status = 'cancelled'
GROUP BY customer_id;Code that reads the first row of a result should expect both behaviors.
GROUP BY puts all NULLs in one group
In a comparison, NULL = NULL is not true. It is unknown. You might therefore expect each NULL key to form its own group. It does not. For grouping, and also for DISTINCT, SQL treats NULLs as the same value, so all rows with a NULL key land in a single group.
SELECT customer_id,
COUNT(*) AS rows_in_group,
COUNT(amount) AS amounts_present,
SUM(amount) AS total_amount,
AVG(amount) AS avg_amount
FROM orders
GROUP BY customer_id
ORDER BY customer_id;| customer_id | rows_in_group | amounts_present | total_amount | avg_amount |
|---|---|---|---|---|
| 10 | 2 | 1 | 100.00 | 100.00 |
| 20 | 2 | 2 | 200.00 | 100.00 |
| 30 | 1 | 0 | NULL | NULL |
| NULL | 2 | 1 | 200.00 | 200.00 |
The guest orders 5 and 6 form one group with a NULL customer_id. Where the NULL group sorts depends on the database. PostgreSQL and Oracle put NULLs last in ascending order by default, while MySQL, SQL Server and SQLite put them first. Add NULLS FIRST or NULLS LAST where your database supports it, or sort with an expression, if the order matters.
The same rule applies to several grouping columns. Two rows fall in the same group when each grouping column is equal or both are NULL. Grouping by customer_id, status gives these groups: (10, paid), (10, pending), (20, paid), (30, pending), (NULL, paid) and (NULL, pending).
NULL in a grouping column versus NULL in an aggregated column
These two roles behave differently, so keep them separate in your head.
- A NULL in a grouping column decides which group the row joins. All NULLs join the same group, and that group appears in the output.
- A NULL in an aggregated column is ignored by the function. The row still belongs to its group and still counts toward COUNT(*).
Customer 30 shows both effects: the group exists because the row exists, but SUM has nothing to add and returns NULL.
HAVING and NULL results
HAVING keeps a group only when its condition is true. A condition that evaluates to NULL is not true, so the group is dropped, just as WHERE drops such rows.
SELECT customer_id,
SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id
HAVING SUM(amount) > 100;Only customer 20 (200) and the NULL-customer group (200) pass. Customer 10 has exactly 100, which is not greater than 100. Customer 30 has a NULL total, so NULL > 100 is unknown and the group disappears. If you also want groups with no total, test for it explicitly:
SELECT customer_id,
SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id
HAVING SUM(amount) > 100
OR SUM(amount) IS NULL;The same trap exists in WHERE. WHERE shipped_at <> '2026-01-05' removes the rows where shipped_at is NULL, because the comparison is unknown. Write shipped_at IS NULL when you want those rows.
Arithmetic inside an aggregate
NULL spreads through ordinary arithmetic: 10 + NULL is NULL. That matters when you put an expression inside an aggregate. Suppose a table had amount and discount columns, where discount is sometimes NULL.
SUM(amount - discount)skips every row where either column is NULL, because the expression is NULL for that row.SUM(amount) - SUM(discount)skips NULLs in each column separately, so a row with an amount but no discount still contributes its amount.
These can give different totals on the same data. Use COALESCE(discount, 0) inside the expression when a missing discount should mean no discount.
Checking NULL effects in your own queries
Before trusting a summary, run a quick comparison on the column you aggregate:
SELECT COUNT(*) AS all_rows,
COUNT(amount) AS non_null_amounts,
COUNT(*) - COUNT(amount) AS null_amounts,
SUM(CASE WHEN amount IS NULL THEN 1 ELSE 0 END) AS null_amounts_check
FROM orders;Both NULL counts should agree, and here both are 3. If null_amounts is large, the SUM and AVG describe only part of the table, and you should know that before you report them.
Summary of the rules
- SUM, AVG, MIN, MAX and COUNT(column) ignore NULL inputs. COUNT(*) counts all rows.
- Over zero or all-NULL inputs, COUNT returns 0 and the others return NULL.
- AVG divides by the number of non-NULL values, not by the number of rows.
- GROUP BY places all rows with a NULL key into one group.
- A HAVING or WHERE condition that evaluates to NULL removes the row or group.
- Use COALESCE to turn NULL into a chosen default, either inside the aggregate (per row) or around it (per group).
Exercise
Using the sample orders table, what does SELECT AVG(amount) FROM orders WHERE status = 'pending' return, and why? What would SELECT COUNT(*), COUNT(amount) FROM orders WHERE status = 'pending' return?
Show answer
The pending orders are 2, 6 and 7, and all three have a NULL amount. AVG skips NULLs, so it has no values to average and returns NULL, not 0. The second query returns 3 and 0: COUNT(*) counts the three rows, and COUNT(amount) counts none because every amount is NULL.
Exercise
A report shows the query SELECT customer_id, SUM(amount) AS total FROM orders GROUP BY customer_id HAVING SUM(amount) <> 100 and the team is surprised that customer 30 is missing. Explain why, and rewrite the HAVING clause so customer 30 appears.
Show answer
Customer 30's only order has a NULL amount, so SUM(amount) is NULL. The condition NULL <> 100 is unknown, not true, so HAVING drops the group. Rewrite it as HAVING SUM(amount) <> 100 OR SUM(amount) IS NULL. Alternatively, use HAVING COALESCE(SUM(amount), 0) <> 100, which treats the missing total as 0 and also keeps customer 30.
Exercise
Orders 5 and 6 both have a NULL customerid. After `GROUP BY customerid`, how many groups do they form, and what are COUNT(*) and SUM(amount) for that group?
Show answer
They form one group, because GROUP BY treats NULL keys as equal. COUNT(*) is 2 (both rows are counted), and SUM(amount) is 200.00, because order 5 has 200.00 and order 6 has a NULL amount that SUM ignores.