aggregate functions
count(*), count(col) and count(DISTINCT col) count three different things.
- address
- everything.basics.aggregates
- part
- part 2, one table
- chapter
- chapter 10 of 12
- reading time
- 8 min
an aggregate function folds many rows into one value. count(*) counts rows, count(col) counts the values in col that aren't NULL, and count(DISTINCT col) counts how many different ones there are. three numbers, three questions.
every aggregate skips NULLs, and over no rows at all, everything but count returns NULL.
the picture
you know how count(*) and count(email) look like two spellings of the same thing? on the shop's customers they say 2,000 and 1,954, and the difference is the whole chapter.
think of a teacher with a stack of exam papers. "how many papers?" is one question. "how many have a grade written on them?" is another, because some are still blank. "how many different grades?" is a third. same stack, three answers, and none of them is wrong.
here's the stack: customer 42, Ada, and her seven orders.
- SELECT count(*)
- FROM orders
- WHERE customer_id = 42;
| id | status | shipped_at | counts? |
|---|---|---|---|
| 880 | cancelled | null | +1 |
| 1455 | refunded | 2025-08-24 19:27:00+00 | +1 |
| 6580 | delivered | 2026-02-24 07:11:00+00 | +1 |
| 7787 | delivered | 2026-04-10 17:34:00+00 | +1 |
| 8219 | delivered | 2026-04-25 20:09:00+00 | +1 |
| 9615 | delivered | 2026-06-14 08:27:00+00 | +1 |
| 9946 | placed | null | +1 |
count(*) doesn't look inside the rows at all. every row is one, NULLs or not. Ada placed 7 orders.
7, 5 and 4 from one table. all three in one query, for real:
SELECT count(*) AS orders,
count(shipped_at) AS shipped,
count(DISTINCT status) AS statuses
FROM orders
WHERE customer_id = 42;| ordersint8 | shippedint8 | statusesint8 |
|---|---|---|
| 7 | 5 | 4 |
on the whole customers table the three counts drift even further apart:
SELECT count(*), count(city), count(DISTINCT city) FROM customers;| countint8 | countint8 | countint8 |
|---|---|---|
| 2000 | 1945 | 28 |
2,000 rows, 1,945 with a city, 28 different cities. and the empty string Ana Lima lives in is one of the 28: '' is a value, so DISTINCT counts it. only NULL is left out.
an aggregate is a fold
under the hood every aggregate works the same way: start with an empty state, feed it one row at a time, and turn the state into an answer at the end. count keeps a counter. sum keeps a running total. avg keeps two numbers, a total and a count, and divides when the rows run out.
- SELECT count(*) AS rows,
- count(shipped_at) AS shipped,
- round(avg(extract(epoch FROM shipped_at - ordered_at) / 3600), 2) AS avg_hours
- FROM orders
- WHERE customer_id = 42;
| id | status | hours | |
|---|---|---|---|
| 880 | cancelled | null | |
| 1455 | refunded | 54 | |
| 6580 | delivered | 16 | |
| 7787 | delivered | 60 | |
| 8219 | delivered | 49 | |
| 9615 | delivered | 27 | |
| 9946 | placed | null |
avg starts with an empty state: a sum of 0 and a count of 0. nothing has been read yet.
NULL leaves both alone. the last step divides, and the panel shows what postgres actually returned.206 hours over 5 shipped orders: 41.20. if NULLs counted as zero, it would be 206 over 7, about 29, which is a different (and wrong) claim about how fast Ada's orders ship. skipping NULLs is usually what you want. when it isn't, say what a missing value should count as, with avg(coalesce(x, 0)).
this is also why GROUP BY is cheap to explain once you've seen this: it runs one fold per bucket instead of one for the whole table.
the usual suspects
| function | gives you | type of the answer |
|---|---|---|
count(*), count(x) | rows, non-NULL values | always bigint |
sum(x) | the total | bigint for int, numeric for numeric |
avg(x) | the mean | numeric for any integer or numeric |
min(x), max(x) | smallest, largest | the same type as x, text and dates too |
string_agg(x, ', ' ORDER BY x) | the values glued together | text |
array_agg(x ORDER BY x) | the values as an array | an array of x's type |
bool_and(x), bool_or(x) | all true? any true? | boolean |
the types matter more than they look. a sum of int columns comes back as bigint, so it doesn't overflow, and an average of integers comes back as numeric, with all its decimals:
SELECT sum(qty) AS units, avg(qty) AS avg_qty, pg_typeof(sum(qty)) AS sum_type, pg_typeof(avg(qty)) AS avg_type
FROM order_items;| unitsint8 | avg_qtynumeric | sum_typeregtype | avg_typeregtype |
|---|---|---|---|
| 47590 | 1.9080266217624890 | bigint | numeric |
min and max work on anything that can be sorted, so the alphabetically first customer and the newest order are one aggregate away. string_agg and array_agg care about order, so give them their own ORDER BY, inside the parentheses:
SELECT min(name) AS first, max(name) AS last,
string_agg(name, ', ' ORDER BY id) AS first_five
FROM customers
WHERE id <= 5;| firsttext | lasttext | first_fivetext |
|---|---|---|
| Grace Okafor | Zoë Martin | Maya Chen, Grace Okafor, Sam Lee, Zoë Martin, Zoe Martin |
(min and max sort the names, so Grace Okafor comes first. last is Zoë Martin, not Zoe: in the C collation this page runs, ë sorts after every plain letter. LIKE, ILIKE and regular expressions has more on that.) the ordered-set aggregates chapter has the medians and percentiles.
nothing in, something out
SELECT count(*), sum(price), max(price)
FROM products
WHERE price < 0;and for real:
SELECT count(*), sum(price), max(price)
FROM products
WHERE price < 0;| countint8 | sumnumeric | maxnumeric |
|---|---|---|
| 0 | null | null |
one row, even though nothing matched. here's the whole pattern, six aggregates fed three different inputs:
| aggregatetext | 1, NULL, 3text | NULL, NULLtext | no rowstext |
|---|---|---|---|
| count(*) | 3 | 2 | 0 |
| count(x) | 2 | 0 | 0 |
| sum(x) | 4 | null | null |
| avg(x) | 2.0000000000000000 | null | null |
| min(x) | 1 | null | null |
| max(x) | 3 | null | null |
so a report that says "total revenue: null" isn't broken. it's telling you there were no rows. if the report should say 0, ask for it: coalesce(sum(price), 0).
one level deepercount(1), count(*) and count(id)
count(1) counts rows where the expression 1 isn't NULL, which is every row, so it gives the same answer as count(*). a column that's NOT NULL, like a primary key, gives the same answer too. in postgres count(*) is the one to write: it's a special form with no argument at all, so there's nothing to check per row, where count(1) checks its 1 for NULL every time.
the trap is the other way round. count(col) on a column that can be NULL is a different question, and in a LEFT JOIN it's often the right one: counting a customer's orders with count(o.id) gives 0 for a customer with none, where count(*) would count the NULL-padded row and say 1. LEFT, RIGHT and FULL joins shows it.
keylines
- an aggregate folds many rows into one value: a state, fed row by row, finished at the end.
- count(*) counts rows, count(col) counts values, count(DISTINCT col) counts different values.
- every aggregate skips NULLs. avg divides by the values it saw, not by the rows.
- no GROUP BY means one bucket and one row, even over zero rows. count says 0, the rest say NULL.
- aggregates can't go in WHERE and can't nest. HAVING and subqueries are where they go.