Full answer
sql
WITH t(x) AS (VALUES (10), (20), (NULL))
SELECT SUM(x) AS s, AVG(x) AS a, MIN(x) AS mn, COUNT(*) AS rows_n, COUNT(x) AS values_n FROM t;| s | a | mn | rows_n | values_n |
|---|---|---|---|---|
| 30 | 15.0 | 10 | 3 | 2 |
The NULL contributes nothing to SUM, AVG or MIN. COUNT(x) counts only the two non-NULL values, while COUNT(*) counts all three rows.
If missing values should count as zero for the average, write AVG(COALESCE(x, 0)), which gives 10. Which one is right depends on whether NULL means "zero" or "unknown".
sql
WITH t(x) AS (VALUES (10), (20), (NULL))
SELECT SUM(x) AS s, AVG(x) AS a, MIN(x) AS mn, COUNT(*) AS rows_n, COUNT(x) AS values_n FROM t;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- Aggregates skip NULL inputs
- COUNT(*) counts rows; COUNT(x) counts non-NULL values
- AVG divides by the number of non-NULL values
- COALESCE changes the meaning of the average
Common mistakes
- Treating NULL as zero without deciding to
- Dividing SUM by COUNT(*) and calling it the average
Follow-ups
- When should a missing value count as zero?
- What does COUNT(DISTINCT x) return here?
Tips
- Ask what NULL means in the data