← Back to SQL, page 16

sql-0303 · Easy fresher

Given the values 10, 20 and NULL, what do SUM, AVG, MIN and COUNT(*) return?

SUM is 30, AVG is 15.0, MIN is 10 and COUNT(*) is 3. Aggregates other than COUNT(*) skip NULLs, so AVG divides by 2, not 3, while COUNT(*) counts rows regardless of their values.

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;
samnrows_nvalues_n
3015.01032

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