QA Interview Hub · Knowledge base · Quizzes · Українська

SQL › Aggregation

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

transactions
idamount
1100
2NULL ignored
3200
result
expressionvalue
COUNT(*)3
COUNT(amount)2
AVG(amount)150
AVG(COALESCE(amount, 0))100
Figure 1. The NULL row drops out of both the numerator and the denominator: (100 + 200) / 2 = 150. With COALESCE inside, NULL becomes zero: (100 + 0 + 200) / 3 = 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

inside

AVG(COALESCE(amount, 0))

NULL counts as zero: the average over three rows is 100. Right if "no amount" means "zero".

outside

COALESCE(AVG(amount), 0)

NULLs are skipped: the average is 150. Zero appears only when there are no values at all.

Figure 2. Both variants are right but answer different questions. Which one is needed is decided by the business rule.

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 SUM over an empty set: it is NULL, and the client shows an empty field or "NaN".
  • Forgetting that AVG ignores 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 COALESCE inside 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 is IS 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.

In an interview. Junior: Aggregate functions ignore NULL, so the average is computed only over the filled values. The sum over an empty set returns not zero but NULL, and if the code does not expect it, an empty field or an error appears on screen. To substitute a default value I use COALESCE. Middle/Senior: I watch where COALESCE sits: inside an aggregate NULL becomes zero and changes the average, outside it only closes an empty result. Row-level arithmetic with NULL removes the row from SUM, so I wrap a fee in COALESCE. For division I use NULLIF, and in checks I count NULLs first and replace them afterwards.

More articles in this chapter