Lesson 7 of 29Joining and aggregating
Aggregation, GROUP BY and HAVING
Turn rows into answers with COUNT, SUM and friends, group them correctly, filter groups with HAVING, pivot with FILTER, and avoid double counting.
Most questions people ask about data are about groups, not single rows. "How much revenue did each order status bring in?" "Which customers have ordered more than once?" "How many signups per month?" A product manager asks one of these in Slack, and you answer it with a single query that folds thousands of rows into a handful. Getting it slightly wrong is easy: a count that silently includes cancelled orders, a total that is double what it should be because of a join, a column that SQLite allowed but Postgres rejects in production. This lesson covers how aggregation really works, the rules the database enforces, and the traps that put wrong numbers in front of your boss.
Aggregate functions fold many rows into one
An aggregate function takes a set of values and returns one value. Five of them cover almost everything:
COUNT(*)counts rows.COUNT(col)counts rows wherecolis not NULL.COUNT(DISTINCT col)counts distinct non-NULL values.SUM(col)andAVG(col)add and average the non-NULL values.MIN(col)andMAX(col)work on numbers, text and ISO dates alike.
Every aggregate except COUNT(*) ignores NULLs, as you saw in NULL and Three-Valued Logic, and most aggregate surprises follow from that one rule. AVG divides by the number of non-NULL values, not by the number of rows. If you want missing values to count as zero, say so with AVG(COALESCE(x, 0)).
Press Run (⌘ Enter) to see what happens.Three things in that output catch people out:
- Katherine has no email, so
COUNT(email)is 7, not 8. Margaret has no city, andCOUNT(DISTINCT city)skips the NULL as well. SUM(price_cents) / COUNT(*)is integer division, so the fraction disappears. You saw the same thing in Choosing Column Types. In Postgres,AVGof an integer column returnsnumeric(3966.6666666666666667); SQLite returns a float.SUMover zero rows is NULL, not 0.COUNTover zero rows is 0. A dashboard tile that shows "NULL" or crashes on an empty day is this bug. Wrap sums inCOALESCE(..., 0)when zero is the right answer.
discount is NULL in 4 of them and 5 in the other 6. What does AVG(discount) return?GROUP BY: one output row per group
Without GROUP BY, an aggregate collapses the whole table into one row. With GROUP BY, the database first sorts the rows into buckets that share the same value of the grouping columns, then runs the aggregates once per bucket. You get one output row per bucket.
Ten orders, in no useful order. GROUP BY status asks for one output row per distinct status.
That last step is the key to the whole lesson. After grouping, a row represents many source rows. Anything you select must have one value per group: either a grouping column (the same for every row in the bucket) or an aggregate (which turns the bucket into one value).
Grouping usually goes with a join. Here is revenue per status:
Press Run (⌘ Enter) to see what happens.Notice COUNT(DISTINCT o.id). After the join there is one row per order item, so a plain COUNT(*) would report 9 shipped "orders" instead of 4. Keep that in mind; it comes back later as the fan-out trap.
The GROUP BY rule, and SQLite's bare-column footgun
The SQL standard rule: every column in SELECT (and HAVING, and ORDER BY) must be either in GROUP BY or inside an aggregate. Postgres enforces it:
SELECT category_id, name, price_cents
FROM products
GROUP BY category_id;
-- ERROR: column "products.name" must appear in the GROUP BY clause
-- or be used in an aggregate functionThere is one sensible exception. If you group by a table's primary key, Postgres knows every other column of that table has exactly one value per group (it is functionally dependent on the key), so GROUP BY c.id lets you select c.name too. Many teams still list c.id, c.name explicitly, which works everywhere.
MySQL enforces the same rule through the ONLY_FULL_GROUP_BY SQL mode, on by default since 5.7. Older MySQL code that relied on loose grouping breaks when it is turned on, and you will meet legacy systems that turned it off.
SQLite does not enforce the rule at all. It runs the query and picks a value from some row in each group:
Press Run (⌘ Enter) to see what happens.The first query returns a product per category, and nothing says which one. The second is a documented SQLite feature: with exactly one MIN or MAX, the bare columns come from the row with that extreme. It is handy, and it is not portable. The same query fails in Postgres, which is how a test suite on SQLite passes while production breaks.
WHERE filters rows, HAVING filters groups
This is the most asked aggregation question in interviews, and the answer comes from the order in which a query is logically evaluated. You write SELECT first, but the database thinks about it much later.
FROM and JOIN run first and produce one big set of rows.
So "customers with at least two orders that were not cancelled" needs both: WHERE throws out cancelled orders before grouping, and HAVING keeps groups with two or more rows.
Press Run (⌘ Enter) to see what happens.Two practical consequences:
- Put row conditions in WHERE, even if HAVING would also work.
HAVING c.name LIKE 'A%'gives the same answer as the WHERE version, but the database groups every customer first and throws most of them away afterwards. A filter in WHERE shrinks the input before the expensive step. - Aliases in HAVING are not portable. Postgres rejects
HAVING live_orders >= 2(it allows output aliases inORDER BYandGROUP BY, not inHAVING). SQLite and MySQL accept it. Repeat the expression; the database computes it once anyway.
HAVING without GROUP BY is legal too. The whole table becomes one group, so SELECT COUNT(*) FROM orders HAVING COUNT(*) > 100 returns one row or none.
Put these clauses in the order the database logically evaluates them.
- Tap the steps below in the right order.
Conditional aggregation and pivots
Often you want several counts side by side: per customer, how many orders are shipped, paid and pending. You could run three queries, or one query with conditional aggregation: an aggregate that only looks at the rows matching a condition.
The standard way is the FILTER clause, supported by Postgres and SQLite (3.30+). The portable way, which also works in MySQL, is a CASE inside SUM.
Press Run (⌘ Enter) to see what happens.This is a pivot: values that were rows (status = 'shipped') became columns. It is how most "report with one column per month" or "funnel with one column per step" queries are built. The cost is that you must know the columns in advance. If the set of statuses changes, the query changes too. A truly dynamic pivot needs SQL generated by code, or doing the pivot in your application or BI tool.
Conditional aggregation also replaces a lot of self-joins and subqueries. "What share of orders were cancelled?" is one pass: AVG(CASE WHEN status = 'cancelled' THEN 1.0 ELSE 0 END). The 1.0 matters, for the integer division reason above.
String aggregation
Sometimes the answer is a list: the products in each category, as one comma-separated string. Postgres has string_agg, which takes an ORDER BY inside the call:
SELECT c.name, string_agg(p.name, ', ' ORDER BY p.name) AS products
FROM categories c
JOIN products p ON p.category_id = c.id
GROUP BY c.id, c.name;SQLite 3.39 does not have string_agg and does not allow ORDER BY inside an aggregate (both arrived in 3.44). It has group_concat, also MySQL's name:
Press Run (⌘ Enter) to see what happens.Without an ordered aggregate, the order of names inside each string is whatever the engine happens to produce. Do not write tests that depend on it. MySQL's GROUP_CONCAT has a nastier trap: it silently truncates the result at group_concat_max_len, which defaults to 1024 bytes. In Postgres, array_agg(x ORDER BY ...) returns a real array, which is usually better than a string if code will read the result.
The fan-out trap: join, then aggregate, then wonder
You met fan-out in Joins of Every Kind: joining a one-to-many child copies the parent row once per child, and joining two independent children multiplies them by each other. It matters most at the moment you aggregate, because that is where the copies turn into wrong numbers. Here it is with counts, which look plausible enough to ship:
Press Run (⌘ Enter) to see what happens.Ada has 3 orders and 6 events. The join pairs every order with every event, giving 3 × 6 = 18 rows, and both counts report 18. COUNT(DISTINCT o.id) would rescue the counts, but not a SUM: SUM(DISTINCT ...) would merge two different orders that happen to cost the same.
The reliable fix is the second query: aggregate each child down to one row per parent first, then join. Each subquery returns one row per customer, so the join is one-to-one and nothing multiplies. The next lesson, Subqueries, CTEs and Set Operations, shows how to write those steps as named CTEs so they read top to bottom.
A habit seniors have: before trusting any aggregate over a join, check the row count of the join alone. If it is larger than the number of parents you expected, you have fan-out.
What does this print?
from shopdb import connect
db = connect()
print(db.execute("""
SELECT COUNT(*)
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
WHERE o.customer_id = 1
""").fetchone()[0])Subtotals: GROUPING SETS, ROLLUP and CUBE
Finance wants a payroll report with a line per job title, a subtotal per department and a grand total. You could glue three GROUP BY queries together with UNION ALL. Postgres does it in one pass:
SELECT department, title,
COUNT(*) AS people, SUM(salary) AS payroll,
GROUPING(department, title) AS level
FROM employees
GROUP BY ROLLUP (department, title)
ORDER BY department, title; department | title | people | payroll | level
-------------+---------------------+--------+---------+-------
Engineering | CTO | 1 | 310000 | 0
Engineering | Engineer | 2 | 265000 | 0
Engineering | Engineering Manager | 2 | 415000 | 0
Engineering | Senior Engineer | 2 | 355000 | 0
Engineering | | 7 | 1345000 | 1
Sales | Account Executive | 1 | 95000 | 0
Sales | Head of Sales | 1 | 190000 | 0
Sales | | 2 | 285000 | 1
| | 9 | 1630000 | 3ROLLUP (a, b)produces the groupings(a, b),(a)and(): a hierarchy of subtotals.CUBE (a, b)produces every combination:(a, b),(a),(b)and().GROUPING SETS ((a), (b), ())lists exactly the groupings you want.
The blank cells are NULLs that mean "all titles", which is ambiguous if title can itself be NULL. GROUPING(...) resolves it: it returns a bitmask with a 1 for each column that was rolled up in that row, so 0 is a detail row, 1 a department subtotal and 3 the grand total.
How the database runs a GROUP BY
Knowing the physical side helps you read plans later in Reading EXPLAIN and EXPLAIN ANALYZE. A planner has two main strategies:
- Hash aggregate: read the rows in any order and keep a hash table with one entry per group. Fast when the number of groups fits in memory. In Postgres
EXPLAINit shows asHashAggregate; since Postgres 13 it can spill to disk when it exceeds its memory budget (work_mem) instead of using unbounded memory. - Sort (group) aggregate: sort the rows by the grouping columns, then walk them, closing a group each time the key changes. It shows as
GroupAggregate. If an index already returns rows in group order, the sort is free and results can stream.
Two consequences for real work. First, the number of groups matters as much as the number of rows: grouping a billion rows into 12 months is cheap in memory, grouping them by user id is not. Second, SELECT COUNT(*) FROM big_table is slow in Postgres, because MVCC means there is no stored row count; it has to visit rows (or at least an index plus the visibility map). For a dashboard that only needs "about 40 million", read the planner's estimate from pg_class.reltuples instead.
Two shorthands you will see: GROUP BY 1, 2 groups by output column positions (quick in ad hoc queries, fragile in code), and Postgres 19 adds GROUP BY ALL, which groups by every non-aggregate column in the SELECT list. That is new in 19, so check the release notes before relying on it in a team codebase.
Match each request to the tool that answers it.
- aggregate function
- A function such as COUNT, SUM, AVG, MIN or MAX that turns a set of values into one value. All except COUNT(*) ignore NULLs.
- GROUP BY
- Splits rows into buckets that share the same grouping values and returns one row per bucket.
- HAVING
- Filters groups after GROUP BY, so it can use aggregates. WHERE filters rows before grouping.
- functional dependency
- When one column determines another. Postgres lets you select any column of a table when you group by its primary key.
- conditional aggregation
- An aggregate that only counts matching rows, written with FILTER (WHERE ...) or SUM(CASE ...). Used to pivot rows into columns.
- fan-out
- Row multiplication caused by joining one-to-many relations, which inflates counts and sums. Fixed by aggregating before joining.
- ROLLUP
- A GROUP BY extension that adds subtotal and grand-total rows for a hierarchy of columns. GROUPING() tells subtotal rows apart.