How do aggregates behave with NULL? What is COALESCE?
Aggregates skip NULL, and on an empty set SUM, AVG, MIN and MAX return NULL, not 0. COUNT always returns a number. COALESCE(a, b, …) returns the first argument that is not NULL, so COALESCE(SUM(x), 0) gives zero instead of NULL. Inside an aggregate COALESCE changes the arithmetic: NULL becomes zero, and, for example, the average is computed over a different number of rows.
SQL · Aggregates
A user with no transactions sees an empty field instead of 0. Where did the NULL come from?
For a new user the API response holds "balance": null and the UI shows an empty field or "NaN" instead of 0. There is no error in the query: the sum over an empty set really is NULL in SQL. This lesson is about how aggregates treat NULL, about COALESCE that fixes it, and about the places where the fix itself creates a new bug.
How it works and why. An aggregate takes the value of the expression from each row and skips those that are NULL. SUM, AVG, MIN and MAX compute only over what is left. If nothing is left (the set is empty or all values are NULL), they return NULL, because SQL does not regard "a sum of zero terms" as zero. The exception: COUNT always returns a number, and COUNT(*) is not touched by NULL at all.
COALESCE(a, b, …) returns the first argument that is not NULL, checking them left to right and not looking further. If all arguments are NULL the result is NULL. All arguments must have compatible types: COALESCE(amount, 'n/a') for a numeric column fails in PostgreSQL.
AVG skips NULL
| id | amount |
|---|---|
| 1 | 100 |
| 2 | NULL ignored |
| 3 | 200 |
| expression | value |
|---|---|
| COUNT(*) | 3 |
| COUNT(amount) | 2 |
| AVG(amount) | 150 |
| AVG(COALESCE(amount, 0)) | 100 |
Example: an empty balance and a "vanished" fee. The first case from the start of the lesson: the account has no transactions.
-- account 999 has no transactions
SELECT SUM(amount) AS balance
FROM transactions
WHERE account_id = 999;
-- balance: NULL
SELECT COALESCE(SUM(amount), 0) AS balance
FROM transactions
WHERE account_id = 999;
-- balance: 0
COALESCE sits outside the aggregate, so it replaces only an empty result. The second case is subtler. Let the table have two rows: an amount of 100 with a fee of 5 and an amount of 200 without a fee (NULL).
-- rows: (amount 100, fee 5) and (amount 200, fee NULL)
SELECT SUM(amount + fee) AS a, -- 105
SUM(amount) + SUM(fee) AS b, -- 305
SUM(amount + COALESCE(fee, 0)) AS c -- 305
FROM transactions;
Arithmetic with NULL gives NULL at the row level: in the second row 200 + NULL is NULL and SUM skips that row entirely. So the first expression gives 105, and the two hundred vanished silently. The right total depends on the rule: if a missing fee means zero, the other two expressions give 305.
Where to put COALESCE
AVG(COALESCE(amount, 0))
NULL counts as zero: the average over three rows is 100. Right if "no amount" means "zero".
COALESCE(AVG(amount), 0)
NULLs are skipped: the average is 150. Zero appears only when there are no values at all.
Limits and alternatives. COALESCE is in the SQL standard and works in all major databases, while dialect shortcuts differ: IFNULL (MySQL, SQLite), ISNULL (SQL Server), NVL (Oracle). To guard against division by zero there is NULLIF(x, 0): it returns NULL if the argument equals zero, and a division by NULL gives NULL instead of an error:
-- the failed percentage; NULLIF prevents division by 0
SELECT ROUND(100.0 * COUNT(*) FILTER (WHERE status = 'failed')
/ NULLIF(COUNT(*), 0), 1) AS failed_pct
FROM transactions
WHERE account_id = 999;
-- failed_pct: NULL (not a division by zero error)
A separate note about checks: COALESCE in a tester's query can hide a defect. If a column must hold a value and holds NULL, turning it into 0 makes the result "tidy" and unnoticeable. To check completeness, count the data as is, with COUNT(*) - COUNT(col), and substitute zeros only where the rule requires it.
Common mistakes.
- Expecting 0 from
SUMover an empty set: it is NULL, and the client shows an empty field or "NaN". - Forgetting that
AVGignores NULL: the average "over all" is really only over the filled ones. - Adding columns with NULL inside an aggregate (
SUM(amount + fee)): the row with NULL drops out entirely. - Putting
COALESCEinside when it is needed outside, and the other way round: it changes the arithmetic. - Comparing with NULL via
= NULL: the result is always UNKNOWN, the right form isIS NULL.
Check yourself
Why does SELECT SUM(amount) FROM transactions WHERE account_id = 999 return NULL and not 0, and where will it do harm?
Answer
In SQL the sum of an empty set is NULL, because there is no value to add. The API will return null and the UI will show an empty field. The fix: COALESCE(SUM(amount), 0) outside the aggregate.
The amount column holds 100, NULL, 200. How do AVG(amount) and AVG(COALESCE(amount, 0)) differ?
Answer
The first ignores NULL and gives (100 + 200) / 2 = 150, the second counts NULL as zero and gives (100 + 0 + 200) / 3 = 100. The choice depends on whether "no value" means zero.
Rows: amount 100, fee 5 and amount 200, fee NULL. What does SUM(amount + fee) return and why is it dangerous?
Answer
105. In the second row 200 + NULL gives NULL and SUM skips the row entirely, so 200 vanished from the total without any error. SUM(amount + COALESCE(fee, 0)) = 305 is more correct.