Topic 3 of 5 · 4 min read
Grouping and totals with GROUP BY
Goal: Write a grouped query whose totals match a hand count on a small sample and explain any difference caused by joins or NULLs.
GROUP BY collapses rows into one row per group, and every number it produces counts the rows it was given. If a join or a NULL changed those rows first, the total is wrong even though the query runs.
Check yourself · 1 of 3
A column has 10 rows, 3 of them NULL. What does COUNT(column) return?
Why it matters
Totals are what people act on: revenue, signups, error counts. An inflated total looks the same as a correct one. You catch it by checking a small sample by hand.
How to do it
- Pick the group.
GROUP BY countrygives one row per country. Every selected column must be in the group or inside an aggregate. - Pick the aggregate.
COUNT(*)counts rows.COUNT(column)counts rows where that column is not NULL.SUMandAVGalso ignore NULL, so an average over 3 values and 1 NULL divides by 3. - Filter in the right place.
WHEREfilters rows before grouping.HAVINGfilters groups after, so use it for conditions on aggregates, such asHAVING count(*) > 5. - Watch the join. If you join orders to order lines and then
SUM(orders.total), each order total is counted once per line. - Hand-check. Take one group, count its rows in a plain query, and compare.
Before and after
The request: "revenue per customer." An order has a total, and each order has several rows in order_items.
-- Before
SELECT o.customer_id, SUM(o.total) AS revenue
FROM orders o
JOIN order_items i ON i.order_id = o.id
GROUP BY o.customer_id;
An order with three items contributes its total three times. Sum the order table on its own, or aggregate the items first.
-- After
SELECT customer_id, SUM(total) AS revenue
FROM orders
GROUP BY customer_id;
What goes wrong
- Summing after a one-to-many join. The total is multiplied by the number of child rows.
COUNT(column)when you meantCOUNT(*). Rows with NULL in the column disappear from the count.WHEREon an aggregate.WHERE count(*) > 5is an error. It belongs inHAVING.AVGover a column with NULLs. The mean is of the known values only. If NULL means zero, useAVG(COALESCE(x, 0)).
Examples
COUNT(*) versus COUNT(column)
A table tickets has 10 rows. 4 have a NULL assignee.
| expression | result |
|---|---|
COUNT(*) |
10 |
COUNT(assignee) |
6 |
COUNT(DISTINCT assignee) |
the number of different assignees |
A report titled "tickets per team" that uses COUNT(assignee) quietly leaves out the unassigned ones.
WHERE versus HAVING
SELECT customer_id, count(*) AS orders
FROM orders
WHERE status = 'paid'
GROUP BY customer_id
HAVING count(*) >= 3;
Only paid orders are counted (WHERE, before grouping). Only customers with three or more of them stay (HAVING, after grouping).
Key points
- GROUP BY returns one row per group, and each aggregate counts only the rows it receives.
- COUNT(*) counts rows; COUNT(column) skips rows where the column is NULL.
- WHERE filters rows before grouping; HAVING filters groups after aggregation.
- Summing a parent column after a join to child rows counts it once per child.
- Check one group by hand on a small sample before trusting the totals.
Common mistakes
- Summing an order total after joining to its line items.
- Using COUNT(column) and losing rows where the column is NULL.
- Putting an aggregate condition in WHERE instead of HAVING.
- Not hand-checking a total on three or four rows before sending the report.
Check yourself · 2 of 3
You want only customers with more than five orders, after counting orders per customer. Where does the condition belong?
Check yourself · 3 of 3
Orders (total 100 each) are joined to order_items (3 items per order), then SUM(o.total) is taken for one customer with 2 orders. What is the result?
Practice items, not counted towards your mastery.
Start here
- PostgreSQL tutorial (opens in a new tab)DocsFree
Official walk-through of tables, joins, aggregates and transactions on a small schema.
- SQLBolt: interactive SQL lessons (opens in a new tab)CourseFree
Short browser exercises on filters, joins and aggregates with instant feedback.
- Use The Index, Luke: SQL indexing and tuning (opens in a new tab)BookFree
A free book on how indexes work and how to design them for real queries.