Counting and summing: aggregate functions
An aggregate functionAggregate functionA SQL function that turns many rows into one value: count, sum, avg, min, max.Open in glossary → takes a whole column of values and returns one:
SELECT count(*) AS orders,
sum(total) AS revenue,
avg(total) AS average_order,
min(total) AS smallest,
max(total) AS largest
FROM orders
WHERE created_at >= date '2026-11-01';However many orders match, the result is one row.
count comes in three forms, and the difference matters:
| You write | It counts |
|---|---|
count(*) | rows |
count(country) | rows where country is not NULL |
count(DISTINCT country) | different non-NULL countries |
All the others (sum, avg, min, max) also skip NULLs. And if no rows match at all, count(*) is 0 but sum(total) is NULL, not 0. Write COALESCE(sum(total), 0) when you need a number.
One more surprise: dividing two whole numbers gives a whole number in PostgreSQL, SQLite and SQL Server. 7 / 2 is 3, and 1 / 4 is 0. When you divide counts, turn one side into a decimal first: 7 * 1.0 / 2 or 7::numeric / 2.
count(*)vscount(1): identical in every major database.count(col)skips NULLs,count(DISTINCT col)needs a sort or hash of all values (expensive on big sets; approximate alternatives: HyperLogLog extensions, BigQueryAPPROX_COUNT_DISTINCT).- NULL rules: aggregates ignore NULLs;
avgdivides by the non-NULL count; any aggregate exceptcountreturns NULL over zero rows. - Types: PostgreSQL
avg(integer)returnsnumeric, butint / inttruncates; SQL Server’savg(int)returns anint. MySQL’s/always returns a decimal (DIVtruncates). - Conditional aggregation:
count(*) FILTER (WHERE status = 'PAID')(PostgreSQL, SQLite 3.30+) or the portablesum(CASE WHEN status = 'PAID' THEN 1 ELSE 0 END). One scan computes many metrics, the basis of pivot-style reports. - More aggregates:
string_agg/array_agg(MySQLgroup_concat),bool_and/bool_or,percentile_cont(0.95) WITHIN GROUP (ORDER BY ms)for medians and p95 (an ordered-set aggregate),jsonb_aggfor API payloads. min/maxon an indexed column can read one end of the index instead of the table.
Predict the output
customers has five rows with countries 'RS', 'RS', 'DE', NULL and NULL. What does this return?
SELECT count(*), count(country), count(DISTINCT country)
FROM customers;count(*) counts rows: 5. count(country) counts non-NULL values: 'RS', 'RS', 'DE', so 3. count(DISTINCT country) counts different non-NULL values: 'RS' and 'DE', so 2. NULL is never counted as a value, not even as a distinct one.
SELECT count(*) AS orders,
count(*) FILTER (WHERE status = 'PAID') AS paid,
count(*) FILTER (WHERE status = 'CANCELLED') AS cancelled,
COALESCE(sum(total) FILTER (WHERE status = 'PAID'), 0) AS revenue,
round(avg(total), 2) AS average_order
FROM orders
WHERE created_at >= date '2026-11-01';
-- the same counts without FILTER (works everywhere)
SELECT sum(CASE WHEN status = 'PAID' THEN 1 ELSE 0 END) AS paid
FROM orders;The conversion rate that’s always zero
Tap the line with the bug.
-- carts: id, customer_id, created_at, ordered (boolean)
SELECT count(*) FILTER (WHERE ordered) / count(*) AS conversion
FROM carts
WHERE created_at >= date '2026-11-01';Hint: Both counts are whole numbers. What does PostgreSQL do when it divides two whole numbers?
count(*) returns a whole number (bigint), and dividing two whole numbers throws away everything after the decimal point. 312 orders out of 1,450 carts is 0.215…, which becomes 0. The dashboard shows 0% every day, and someone spends a week debugging the checkout.
Make one side a decimal before dividing, and round the result:
SELECT round(100.0 * count(*) FILTER (WHERE ordered) / count(*), 1) AS conversion_pct
FROM carts
WHERE created_at >= date '2026-11-01';100.0 is a decimal, so the whole calculation is done in decimals: 21.5. If there might be no carts at all, count(*) is 0 and the division fails with “division by zero”: wrap the divisor in NULLIF(count(*), 0) to get NULL instead.
Deep diveWhy count(*) is slow on a big PostgreSQL tableInterview favorite
“SELECT count(*) FROM events takes 40 seconds; MySQL’s MyISAM answered instantly.” Because of MVCCMVCCMulti-version concurrency control: writers create new row versions so readers never wait for them.Open in glossary →, PostgreSQL has no single row count: different transactions see different sets of rows, so every count must check each row’s visibility. The fastest it can do is an index-only scan of the smallest index, which still reads every entry and needs the visibility map to be up to date (recent VACUUM). InnoDB has the same problem; only MyISAM, without transactions, kept an exact counter.
Options, from exact to cheap:
- Count less:
count(*)with a selectiveWHEREon an indexed column. - Maintain a counter: a
countstable updated by triggers or by the app in the same transaction. Exact, but every insert now updates one hot row: use several counter rows (sharded counter) and sum them. - Estimate:
SELECT reltuples FROM pg_class WHERE relname = 'events'(refreshed byANALYZE), or parse the row estimate fromEXPLAIN. Good for “about 12.4 million” in an admin UI. - Don’t show it: paginated UIs rarely need “page 1 of 48,213”. “Load more” with keyset paginationKeyset paginationPaging by continuing after the last row's sort key instead of skipping a number of rows with OFFSET.Open in glossary → avoids the count entirely.
count(*)=count(1);count(col)skips NULLs;count(DISTINCT)is costly. Aggregates skip NULLs;sumof nothing is NULL.- Integer division truncates in PostgreSQL, SQLite, SQL Server:
100.0 * a / NULLIF(b, 0). - Conditional aggregates:
FILTER (WHERE …)orsum(CASE …);percentile_contfor medians and p95. - Exact
count(*)on huge MVCC tables is slow: counters,reltuplesestimates, or no total.
SELECT count(*) FILTER (WHERE status = 'PAID') AS paid,
round(100.0 * count(*) FILTER (WHERE status = 'PAID') / NULLIF(count(*), 0), 1) AS paid_pct,
percentile_cont(0.5) WITHIN GROUP (ORDER BY total) AS median_total
FROM orders;Check this part
What does count(email) count?
No order matches the WHERE. What does sum(total) return?
In PostgreSQL, what is SELECT 3 / 4?
Why is an exact count(*) of a 500-million-row PostgreSQL table slow?