Part 04 / Topic 1 of 6
The aggregate functions
An aggregate eats many rows and returns one value. The big five, over the whole products table at once:
SELECT count(*) AS products,
sum(stock) AS units_on_shelf,
avg(price) AS avg_price,
min(price) AS cheapest,
max(price) AS priciest
FROM products;
products | units_on_shelf | avg_price | cheapest | priciest
----------+----------------+----------------------+----------+----------
10 | 490 | 369.8000000000000000 | 15.00 | 1200.00
(1 row)
Ten rows in, one row out. That long avg tail wants the Part 3 rounding habit:
SELECT round(avg(price), 2) AS avg_price FROM products;
avg_price
-----------
369.80
(1 row)
How aggregates treat NULL: they skip it. This is usually what you want — and occasionally a surprise:
SELECT avg(v) AS average, sum(v) AS total, count(v) AS counted
FROM (VALUES (10), (NULL), (20)) AS t(v);
average | total | counted
---------------------+-------+---------
15.0000000000000000 | 30 | 2
(1 row)
The average of 10, NULL and 20 is 15, not 10 — the NULL row simply isn't part of the calculation. (That VALUES ... AS t(v) trick builds a tiny inline table for experiments; steal it.) One more corner: sum over only NULLs returns NULL, not 0 — wrap reports in COALESCE(sum(v), 0) when a zero should print.
🧪 Quick quiz — answer from memory, then check.
avg(v)over the values 10, NULL, 20 returns…?sum(v)over a column containing only NULLs returns…?
Show the answers
- 15 — aggregates skip NULLs: (10 + 20) / 2.
- NULL, not 0.
COALESCE(sum(v), 0)prints the zero.
Done here? The practice set for Part 4 — 7 exercises with solutions — is on the part page.