Skip to content

GROUP BY and aggregates

BasicsConcept

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.

setup.sql
CREATE TABLE orders (
id int PRIMARY KEY,
customer text,
city text,
amount int
);
INSERT INTO orders VALUES
(1, 'Ana', 'Leeds', 30), (2, 'Ben', 'York', 12),
(3, 'Ana', 'Leeds', 8), (4, 'Cho', 'Leeds', 50),
(5, 'Ben', 'York', 25), (6, 'Dee', 'Hull', 5),
(7, 'Ana', 'Leeds', 15), (8, 'Cho', 'Leeds', 9);
per-customer.sql
SELECT customer, count(*) AS orders, sum(amount) AS total
FROM orders
GROUP BY customer
ORDER BY customer;

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.

Text
customer | orders | total
----------+--------+-------
Ana | 3 | 53
Ben | 2 | 37
Cho | 2 | 59
Dee | 1 | 5
(4 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:

SQL
SELECT customer, amount
FROM orders
GROUP BY customer;
Text
ERROR: column "orders.amount" must appear in the GROUP BY clause
or be used in an aggregate function

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.

GROUP BY customer, one row at a time
Step 1 of 10
Buckets 0
orders · 8 rows (customer amount)
Ana 30
Ben 12
Ana 8
Cho 50
Ben 25
Dee 5
Ana 15
Cho 9
Buckets: customer → count, sum
Empty
  • 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.

0 of 8 rows read

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.

Logical order of a grouped query
OrderClauseWorks on
1FROMthe tables, joined
2WHEREsingle rows: keeps or drops each one
3GROUP BYrows into buckets
4HAVINGwhole buckets: keeps or drops each one
5SELECTone output row per bucket
6ORDER BY, LIMITthe 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:

SQL
-- WHERE runs before there are any buckets
SELECT customer, sum(amount) FROM orders
WHERE sum(amount) > 40
GROUP BY customer;
-- ERROR: aggregate functions are not allowed in WHERE
-- HAVING runs before SELECT names its columns
SELECT customer, sum(amount) AS total FROM orders
GROUP BY customer
HAVING total > 40;
-- ERROR: column "total" does not exist

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.

WHERE amount >= 10
SELECT customer, sum(amount) AS total
FROM orders
WHERE amount >= 10
GROUP BY customer;
customer | total
----------+-------
Ana | 45
Ben | 37
Cho | 50
HAVING sum > 40
SELECT customer, sum(amount) AS total
FROM orders
GROUP BY customer
HAVING sum(amount) > 40;
customer | total
----------+-------
Ana | 53
Cho | 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.

The buckets from the trace, with HAVING sum(amount) > 40 applied
Buckets: customer → count, sum
Ana→3 · 53keptBen→2 · 37droppedCho→2 · 59keptDee→1 · 5dropped
  • 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.

WHEREBefore groupingSees one row at a time. Cannot use aggregates.
HAVINGAfter groupingSees one bucket at a time. Usually tests an aggregate.

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.

SQL
SELECT city,
count(*) AS orders,
count(DISTINCT customer) AS customers,
round(avg(amount), 2) AS avg
FROM orders
GROUP BY city
ORDER BY city;
city | orders | customers | avg
-------+--------+-----------+-------
Hull | 1 | 1 | 5.00
Leeds | 5 | 2 | 22.40
York | 2 | 1 | 18.50
The common aggregates and NULL
AggregateGivesNULL values
count(*)the number of rows in the groupcounted: it counts rows, not values
count(col)the number of non-NULL valuesskipped
count(DISTINCT col)the number of different non-NULL valuesskipped
sum, avg, min, maxone value from the group’s valuesskipped; 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.

Hash
HashAggregate
Group Key: customer
-> Seq Scan on orders
Sort, then walk
GroupAggregate
Group Key: customer
-> Sort
Sort 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.

09 Check yourself

Question

You want only customers who spent more than 40 in total. Where does sum(amount) > 40 go?

Question

With the eight orders above, how many rows does SELECT customer, count(*) FROM orders WHERE amount >= 10 GROUP BY customer return?

Question

A city column has 5 rows, 2 of them NULL. What do count(*) and count(city) return?

10 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?