Sub topic 11
NULL in aggregates: COUNT, AVG, and SUM
This chapter assumes you can write basic SELECT statements with WHERE and aliases, and that you know COUNT, SUM, and AVG at a basic level. It also assumes you have read the earlier chapters on NULL in comparisons and on NVL. You will see how aggregate functions treat NULL, why that can change a result without raising an error, and when NVL or COALESCE belongs inside or outside the aggregate.
The core rule: aggregates skip NULL
Most aggregate functions ignore NULL inputs. They compute their result from the non-NULL values only. The only common exception is COUNT(*), which counts rows and never looks at column values.
| Expression | What it does with NULL | Result when every input is NULL, or there are no rows |
|---|---|---|
| `COUNT(*)` | Counts every row | `0` |
| `COUNT(col)` | Counts rows where `col` is not NULL | `0` |
| `COUNT(DISTINCT col)` | Counts distinct non-NULL values | `0` |
| `SUM(col)` | Adds the non-NULL values | `NULL` |
| `AVG(col)` | Divides the sum of non-NULL values by the count of non-NULL values | `NULL` |
| `MIN(col)`, `MAX(col)` | Ignore NULL | `NULL` |
COUNT is the only aggregate that never returns NULL. The others return NULL when they have nothing to work with.
A small dataset you can run anywhere
The following query builds four rows in a WITH clause, so it runs against dual without any tables. Two of the four amount values are NULL.
WITH sales AS (
SELECT 1 AS id, 100 AS amount FROM dual UNION ALL
SELECT 2, NULL FROM dual UNION ALL
SELECT 3, 300 FROM dual UNION ALL
SELECT 4, NULL FROM dual
)
SELECT COUNT(*) AS rows_total,
COUNT(amount) AS amount_count,
SUM(amount) AS amount_sum,
AVG(amount) AS avg_non_null,
AVG(NVL(amount, 0)) AS avg_with_zero,
MIN(amount) AS min_amount,
MAX(amount) AS max_amount
FROM sales;The result is one row:
| ROWS_TOTAL | AMOUNT_COUNT | AMOUNT_SUM | AVG_NON_NULL | AVG_WITH_ZERO | MIN_AMOUNT | MAX_AMOUNT |
|---|---|---|---|---|---|---|
| 4 | 2 | 400 | 200 | 100 | 100 | 300 |
COUNT(*) sees four rows, but COUNT(amount) sees two. AVG(amount) is 400 / 2 = 200. After NVL(amount, 0), every row has a value, so the divisor becomes 4 and the average is 400 / 4 = 100. Neither number is wrong. They answer different questions.
COUNT: three forms, three meanings
The same word COUNT can answer three different questions:
COUNT(*)answers "how many rows are there?"COUNT(col)answers "how many rows have a value incol?"COUNT(DISTINCT col)answers "how many different values doescolcontain?"NULLis not counted as a value.
A common mistake is wrapping the column in NVL inside COUNT:
SELECT COUNT(commission_pct) AS with_commission,
COUNT(NVL(commission_pct, 0)) AS all_rows,
COUNT(*) AS also_all_rows
FROM employees;COUNT(NVL(commission_pct, 0)) is never NULL, so it counts every row. It is a slower way to write COUNT(*). If you want to count missing values, subtract: COUNT(*) - COUNT(commission_pct) gives the number of NULL rows. A SUM(CASE WHEN commission_pct IS NULL THEN 1 ELSE 0 END) expression does the same and reads more clearly.
In Oracle's sample HR schema, COUNT(*) returns 107 employees and COUNT(commission_pct) returns 35. The other 72 employees have no commission.
AVG: the denominator is the real decision
The AVG example from the spine shows the effect on real data:
SELECT AVG(commission_pct) AS avg_among_earners,
AVG(NVL(commission_pct, 0)) AS avg_across_everyone
FROM employees;In the HR schema, the first column is about 0.22 and the second about 0.07. The first is the average commission rate among the 35 people who earn one. The second spreads the same total over all 107 employees.
Choose by asking what a NULL means in your data:
- If
NULLmeans "this row does not apply" (a salesperson has no commission because the job has none), leave it alone. The default behavior is correct. - If
NULLmeans "zero" (no sales were recorded, so the amount is zero), replace it withNVL(col, 0)before averaging. - If
NULLmeans "unknown" (the value exists but was never captured), neither choice is accurate. Report the count of known values next to the average so readers can judge it.
SUM: NULL inputs vanish, but NULL totals appear
SUM skips NULL inputs, so a column with some missing values still sums correctly. The surprise comes when there is nothing to add:
SELECT SUM(salary) AS total_salary,
COUNT(salary) AS salary_count,
NVL(SUM(salary), 0) AS total_or_zero
FROM employees
WHERE 1 = 0;No rows match, so SUM(salary) returns NULL, COUNT(salary) returns 0, and NVL(SUM(salary), 0) returns 0. The same happens for a group where every value is NULL. Reports and application code often expect a number, so wrapping the aggregate in NVL or COALESCE is the usual fix.
NVL outside or inside SUM?
These two expressions look similar:
SELECT NVL(SUM(commission_pct), 0) AS outside,
SUM(NVL(commission_pct, 0)) AS inside
FROM employees;For a table that has rows, both return the same total. They differ in two ways:
- When no rows match the
WHEREclause,SUM(NVL(x, 0))still returnsNULL, because there is nothing to sum.NVL(SUM(x), 0)returns0. NVLinside the aggregate runs once per row.NVLoutside runs once per group. The outside form is cheaper and usually the better default forSUM.
For AVG the choice is different. Putting NVL outside, as in NVL(AVG(x), 0), only handles the case where no values exist. It does not change the denominator. Put NVL inside only if missing really means zero.
NULL inside the expression you aggregate
NULL propagates through arithmetic before the aggregate sees it. Consider total pay, where the + salary * commission_pct part is NULL for employees without a commission:
SELECT SUM(salary + salary * commission_pct) AS sum_with_gaps,
SUM(salary + salary * NVL(commission_pct, 0)) AS sum_all_pay,
SUM(salary) AS sum_salary_only
FROM employees;The first expression evaluates to NULL for every employee with no commission. SUM then skips those rows and adds only the 35 commission earners, so the total is far too small. No error is raised. The second expression gives every row a value, so it covers all 107 employees.
The same applies to two columns that are summed separately versus added first:
WITH t AS (
SELECT 10 AS a, 5 AS b FROM dual UNION ALL
SELECT 20, NULL FROM dual
)
SELECT SUM(a + b) AS sum_of_sums_per_row,
SUM(a) + SUM(b) AS sum_of_column_sums
FROM t;SUM(a + b) returns 15, because the second row's a + b is NULL and is skipped. SUM(a) + SUM(b) returns 30 + 5 = 35. If you want per-row totals that include rows with a missing column, use SUM(a + NVL(b, 0)), which returns 35.
GROUP BY, HAVING, and NULL
GROUP BY treats all NULL values in a column as one group. This is different from comparison, where NULL = NULL is not true.
SELECT commission_pct,
COUNT(*) AS employee_count
FROM employees
GROUP BY commission_pct
ORDER BY commission_pct;By default, Oracle sorts NULL last in ascending order, so the group of employees without a commission appears at the end. You can add NULLS FIRST to change that. When you report this group, you can label it with NVL(TO_CHAR(commission_pct), 'none'). Convert the number to text first, as described in the data type chapter, or Oracle raises ORA-01722.
HAVING follows the same three-valued logic as WHERE. A group whose AVG(x) is NULL makes the condition AVG(x) > 100 unknown, so that group is dropped. A department where every salary is missing disappears from the result instead of appearing with a blank. If you need it to appear, add a condition such as OR AVG(x) IS NULL, or compare NVL(AVG(x), 0).
Quick decision guide
| Question you are answering | Use |
|---|---|
| How many rows are there? | `COUNT(*)` |
| How many rows have a value? | `COUNT(col)` |
| How many rows have no value? | `COUNT(*) - COUNT(col)` |
| Average among rows that have a value | `AVG(col)` |
| Average where missing means zero | `AVG(NVL(col, 0))` |
| Total that must print as `0`, not blank | `NVL(SUM(col), 0)` |
| Total of an expression that may contain `NULL` | `SUM(NVL(...))` on each nullable operand |
Exercise
A table orders has 10 rows. The column discount is NULL in 4 rows and contains 10 in the other 6 rows. What do COUNT(*), COUNT(discount), SUM(discount), AVG(discount), and AVG(NVL(discount, 0)) return?
Show answer
COUNT(*) returns 10, COUNT(discount) returns 6, and SUM(discount) returns 60. AVG(discount) returns 10, because 60 / 6 = 10. AVG(NVL(discount, 0)) returns 6, because the four NULL rows become 0 and 60 / 10 = 6.
Exercise
A report runs SELECT SUM(amount) FROM payments WHERE customer_id = 999, and no payments exist for that customer. The application crashes because it receives NULL. Rewrite the query so it returns 0, and explain why SUM(NVL(amount, 0)) would not fix it.
Show answer
Use SELECT NVL(SUM(amount), 0) FROM payments WHERE customer_id = 999. With no matching rows, SUM has no input and returns NULL, and NVL outside the aggregate replaces that result with 0. SUM(NVL(amount, 0)) applies NVL to each row, but there are no rows, so SUM still returns NULL.
Exercise
Why does SELECT SUM(a + b) FROM t return a smaller total than SELECT SUM(a) + SUM(b) FROM t when column b has some NULL values? How do you make the first form include every row?
Show answer
In a + b, any row where b is NULL produces NULL, and SUM skips that row, so its a value is lost. SUM(a) + SUM(b) skips NULLs in each column separately, so every a value is counted. To include every row, write SUM(a + NVL(b, 0)).