GROUP BY and aggregates
You want one number per customer, not one per order, and GROUP BY gives it to you. Then it rejects a column you thought was harmless, and WHERE refuses a sum. Both rules come from one picture: rows go into buckets, and each bucket becomes one row.
01 Eight orders, one line per customer
A shop keeps one row per order. The question you actually have is about customers: how many orders each one placed, and how much they spent. That is a different shape from the table, with one row per customer instead of one per order.
GROUP BY customer says which rows belong together. count(*) and sum(amount) are aggregates: each takes many rows and gives back one value. These outputs come from Postgres 16, but every SQL database gives the same four rows.
02 Not a sort: the rows are gone
A common first picture is that GROUP BY sorts the table so that each customer’s orders sit together, and you still see every row. If that were true, this would work:
After grouping, Ana is one output row, and she has three amounts: 30, 8 and 15. The database cannot pick one for you. So every column in SELECT must be either a grouping key (one value per group by definition) or inside an aggregate that turns the group’s values into one, such as sum(amount) or max(amount).
There is one exception in Postgres: if you group by a table’s primary key, you may select that table’s other columns, because the key already fixes them. GROUP BY id lets you select customer.
03 What the database does: one bucket per key
The useful picture is a set of buckets. The database reads the rows once. For each row it works out the group key, finds the bucket for that key (making it if needed), and folds the row into the bucket’s running answers. A bucket keeps only what the aggregates need, a count and a sum here, never the rows themselves.
- row being read
- new bucket
- bucket updated
- one output row
- not read yet
The table has eight orders and no buckets yet. The database will read each row once and drop it into the bucket for its customer.
That is why the error above exists: by the time a bucket is turned into an output row, the individual amounts are no longer there. It is also why avg is cheap: a bucket keeps a sum and a count and divides at the end.
04 The order the clauses run in
You write a query top to bottom, starting with SELECT, but the database works through it in a different order. Most GROUP BY puzzles go away once you know it.
| Order | Clause | Works on |
|---|---|---|
| 1 | FROM | the tables, joined |
| 2 | WHERE | single rows: keeps or drops each one |
| 3 | GROUP BY | rows into buckets |
| 4 | HAVING | whole buckets: keeps or drops each one |
| 5 | SELECT | one output row per bucket |
| 6 | ORDER BY, LIMIT | the output rows |
This is the logical order, the meaning of the query. The planner may do the work differently, for example by filtering rows while it reads them, but the result is always as if the steps ran in this order. It explains two errors you will meet:
Postgres wants HAVING sum(amount) > 40, repeating the aggregate. MySQL accepts the alias in HAVING as an extension, which is why code moved between the two sometimes breaks. ORDER BY total works everywhere, because ORDER BY runs last.
05 WHERE filters rows, HAVING filters groups
Both clauses drop things, but at different moments. WHERE looks at one order at a time, before any bucket exists. HAVING looks at a finished bucket, after every row has been added to it. The same number, 40, means something different in each.
SELECT customer, sum(amount) AS totalFROM ordersWHERE amount >= 10GROUP BY customer;customer | total----------+-------Ana | 45Ben | 37Cho | 50
SELECT customer, sum(amount) AS totalFROM ordersGROUP BY customerHAVING sum(amount) > 40;customer | total----------+-------Ana | 53Cho | 59
On the left, the small orders (Ana 8, Dee 5, Cho 9) never reach a bucket. Ana’s total drops to 45, Cho’s to 50, and Dee disappears because none of her rows survived. On the right, every row is counted, and then the buckets with totals of 40 or less are thrown away whole.
- passes HAVING
- dropped by HAVING
You can use both in one query: WHERE amount >= 10 ... HAVING sum(amount) > 40 returns Ana 45 and Cho 50. A rule of thumb: if a condition can be checked on a single row, put it in WHERE. Rows dropped early never need a bucket, so the query does less work.
06 What each aggregate counts
Grouping by city puts Ana and Cho in the same bucket, since both are in Leeds. That makes the difference between counting rows and counting values visible.
| Aggregate | Gives | NULL values |
|---|---|---|
| count(*) | the number of rows in the group | counted: it counts rows, not values |
| count(col) | the number of non-NULL values | skipped |
| count(DISTINCT col) | the number of different non-NULL values | skipped |
| sum, avg, min, max | one value from the group’s values | skipped; NULL if every value is NULL |
GROUP BY also treats NULL keys as equal to each other: every row with a NULL city goes into one bucket, shown with an empty key. That is different from WHERE city = NULL, which matches nothing.
07 Two ways to fill the buckets
The trace drew a hash table of buckets, and that is what Postgres usually does. EXPLAIN shows it as HashAggregate. The other method sorts the rows by the key first and then walks the sorted list, closing one bucket whenever the key changes: GroupAggregate. It needs only one bucket in memory at a time, and it is free when the rows already arrive sorted, for example from an index on the key.
HashAggregateGroup Key: customer-> Seq Scan on orders
GroupAggregateGroup Key: customer-> SortSort Key: customer-> Seq Scan on orders
Both plans are real Postgres 16 output for the per-customer query, with costs removed; the second appeared after SET enable_hashagg = off. Either way the result is the same four rows. Note that neither promises an order: without ORDER BY, a hash aggregate returns groups in whatever order the hash table holds them.
08 When it bites
SELECT customer, amount ... GROUP BY customerA bare column next to an aggregatePostgres rejects it. Old MySQL setups without ONLY_FULL_GROUP_BY accept it and return an amount from some row in the group, with no promise which. Wrap it in an aggregate such as max(amount).SELECT sum(amount) FROM orders WHERE amount > 100No GROUP BY and no rowsWith no GROUP BY, the whole table is one group, so you always get one row: count(*) is 0 and sum is NULL, not 0. Use coalesce(sum(amount), 0). Add GROUP BY customer and the same filter returns zero rows instead.LEFT JOIN orders ... count(*)Counting the NULL row of a left joinA customer with no orders still has one padded row, so count(*) says 1. Count a column from the right table, count(o.id), to get 0.GROUP BY customer, cityMore keys, more bucketsEach different pair is its own bucket. Adding a column to make an error go away can quietly split your groups, so a customer in two cities becomes two rows.GROUP BY customer -- and no ORDER BYExpecting the groups in orderGroup order is not guaranteed without ORDER BY. It can look sorted on a small table and change when the plan changes. Add ORDER BY whenever the order matters.