skip to content

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.

count =
query.sql
  1. SELECT count(*)
  2. FROM orders
  3. WHERE customer_id = 42;
each row, and whether count(*) counts it
idstatusshipped_atcounts?
880cancellednull+1
1455refunded2025-08-24 19:27:00+00+1
6580delivered2026-02-24 07:11:00+00+1
7787delivered2026-04-10 17:34:00+00+1
8219delivered2026-04-25 20:09:00+00+1
9615delivered2026-06-14 08:27:00+00+1
9946placednull+1

count(*) doesn't look inside the rows at all. every row is one, NULLs or not. Ada placed 7 orders.

countedNULL: skipped
real output, postgres 18.6 (PGlite 0.5.12) · aggregates
pick a count. it looks only at the hot column (count(*) looks at none: it counts rows). NULLs are skipped, and count(DISTINCT) counts a status only the first time it's seen.

7, 5 and 4 from one table. all three in one query, for real:

sqldb=shop
SELECT count(*) AS orders,
       count(shipped_at) AS shipped,
       count(DISTINCT status) AS statuses
FROM orders
WHERE customer_id = 42;
output, from postgres 18.6
SELECT 1
ordersint8shippedint8statusesint8
754
(1 row)

on the whole customers table the three counts drift even further apart:

sqldb=shop
SELECT count(*), count(city), count(DISTINCT city) FROM customers;
output, from postgres 18.6
SELECT 1
countint8countint8countint8
2000194528
(1 row)

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.

query.sql
  1. SELECT count(*) AS rows,
  2. count(shipped_at) AS shipped,
  3. round(avg(extract(epoch FROM shipped_at - ordered_at) / 3600), 2) AS avg_hours
  4. FROM orders
  5. WHERE customer_id = 42;
the rows avg reads, one at a time
idstatushours
880cancellednull
1455refunded54
6580delivered16
7787delivered60
8219delivered49
9615delivered27
9946placednull
the state
sum0count0
postgres returned
rows…shipped…avg_hours…

avg starts with an empty state: a sum of 0 and a count of 0. nothing has been read yet.

row 1/9
real output, postgres 18.6 (PGlite 0.5.12) · aggregates
step through Ada's orders. avg's state is a sum and a count, and a 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

functiongives youtype of the answer
count(*), count(x)rows, non-NULL valuesalways bigint
sum(x)the totalbigint for int, numeric for numeric
avg(x)the meannumeric for any integer or numeric
min(x), max(x)smallest, largestthe same type as x, text and dates too
string_agg(x, ', ' ORDER BY x)the values glued togethertext
array_agg(x ORDER BY x)the values as an arrayan 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:

sqldb=shop
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;
output, from postgres 18.6
SELECT 1
unitsint8avg_qtynumericsum_typeregtypeavg_typeregtype
475901.9080266217624890bigintnumeric
(1 row)

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:

sqldb=shop
SELECT min(name) AS first, max(name) AS last,
       string_agg(name, ', ' ORDER BY id) AS first_five
FROM customers
WHERE id <= 5;
output, from postgres 18.6
SELECT 1
firsttextlasttextfirst_fivetext
Grace OkaforZoë MartinMaya Chen, Grace Okafor, Sam Lee, Zoë Martin, Zoe Martin
(1 row)

(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

predict the output
sql
SELECT count(*), sum(price), max(price)
FROM products
WHERE price < 0;

and for real:

sqldb=shop
SELECT count(*), sum(price), max(price)
FROM products
WHERE price < 0;
output, from postgres 18.6
SELECT 1
countint8sumnumericmaxnumeric
0nullnull
(1 row)

one row, even though nothing matched. here's the whole pattern, six aggregates fed three different inputs:

aggregatetext1, NULL, 3textNULL, NULLtextno rowstext
count(*)320
count(x)200
sum(x)4nullnull
avg(x)2.0000000000000000nullnull
min(x)1nullnull
max(x)3nullnull
(6 rows)
one captured query. count never returns NULL. everything else returns NULL when it has no values to work with, whether that's because there were no rows or because every value was 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.