Sub topic 10
Grouping and aggregating joined data
This chapter assumes you can write an INNER JOIN with an ON condition and aliases, and that you know GROUP BY and the basic aggregate functions (COUNT, SUM, AVG, MIN, MAX). It uses the customers and orders tables from earlier chapters, plus order_items and products.
The working model: join first, then group
A query with a join and a GROUP BY runs in a fixed logical order:
FROMandINNER JOINbuild the combined rows.WHEREremoves rows from that combined set.GROUP BYcollects the remaining rows into groups.- Aggregate functions compute one value per group.
HAVINGfilters groups, andSELECTandORDER BYfinish the result.
Aggregates therefore operate on the joined rows, not on the original tables. If the join changes the number of rows, it changes what the aggregates see. Most mistakes in this area come from forgetting that.
A first aggregate over a join
This query counts orders and sums revenue for each customer.
SELECT c.name, COUNT(*) AS order_count, SUM(o.total) AS revenue
FROM customers AS c
INNER JOIN orders AS o ON o.customer_id = c.id
GROUP BY c.id, c.name;With the sample data, the join produces three rows: two for Ada and one for Ben. The result is:
| name | order_count | revenue |
|---|---|---|
| Ada | 2 | 125.00 |
| Ben | 1 | 20.00 |
Chloe has no orders, so no joined row exists for her and no group is created. Order 104 has a NULL customer_id, so it never joins and is not counted. If a report must list every customer, including those with zero orders, an inner join is the wrong tool. The outer joins chapter covers that case.
Group by the key, not only the name
The query groups by c.id as well as c.name. Two customers can share a name. Grouping by name alone would merge them into one row and add their orders together. Grouping by the primary key keeps each customer separate. Including c.name in the GROUP BY also keeps the query valid in databases that require every non-aggregated column in SELECT to appear in GROUP BY. Some databases, such as PostgreSQL, accept GROUP BY c.id alone when id is the primary key. Others, such as SQL Server and Oracle, do not.
Choosing the right COUNT
COUNT has several forms, and the difference matters once joins are involved.
| Expression | What it counts |
|---|---|
| `COUNT(*)` | Every joined row in the group |
| `COUNT(o.id)` | Rows where `o.id` is not `NULL` |
| `COUNT(DISTINCT o.id)` | Distinct non-`NULL` values of `o.id` |
With a plain inner join, COUNT(*) and COUNT(o.id) give the same answer, because every joined row has an order. They differ with outer joins, where unmatched rows carry NULL. They also differ when you join further tables and the order repeats.
How row multiplication distorts aggregates
A one-to-many join repeats the parent row once for each matching child. Each repeat carries the parent's column values. Summing a parent column after such a join counts each value more than once.
Suppose order 101 has two items and order 102 has one. Add this data to the earlier schema:
INSERT INTO products (id, name) VALUES (1, 'Pen'), (2, 'Notebook');
INSERT INTO order_items (order_id, product_id, quantity) VALUES
(101, 1, 10),
(101, 2, 2),
(102, 2, 5);Now consider the wrong query:
-- Wrong: each order's total is repeated once per matching order item.
SELECT SUM(o.total) AS inflated_revenue
FROM orders AS o
INNER JOIN order_items AS i ON i.order_id = o.id;The join returns three rows: order 101 twice and order 102 once. The sum is 50 + 50 + 75 = 175, but the real total for those two orders is 125. The query ran without error and returned a plausible number, which is why this mistake is easy to miss.
Fix 1: aggregate at the right level first
Collapse the many side to one row per parent, then join. Aggregating before the join means no parent row is repeated.
SELECT c.name, SUM(o.total) AS revenue, SUM(s.units) AS units_sold
FROM customers AS c
INNER JOIN orders AS o ON o.customer_id = c.id
INNER JOIN (
SELECT order_id, SUM(quantity) AS units
FROM order_items
GROUP BY order_id
) AS s ON s.order_id = o.id
GROUP BY c.id, c.name;The subquery s returns one row per order, so the join with orders does not multiply anything. For Ada, the result is revenue 125.00 and 17 units.
Fix 2: count or sum distinct keys
For counts, COUNT(DISTINCT o.id) counts each order once no matter how many items it has.
SELECT c.name,
COUNT(DISTINCT o.id) AS order_count,
SUM(i.quantity) AS units_sold
FROM customers AS c
INNER JOIN orders AS o ON o.customer_id = c.id
INNER JOIN order_items AS i ON i.order_id = o.id
GROUP BY c.id, c.name;SUM(i.quantity) is correct here because quantity belongs to the item rows, which are not repeated. COUNT(DISTINCT o.id) is correct because it ignores repeats.
Rule of thumb
Before aggregating a column, ask which table it belongs to and whether the join repeats that table's rows. Aggregating a column from the "many" side is safe. Aggregating a column from the "one" side needs one of the fixes above.
Filtering before and after grouping
WHERE filters joined rows before grouping. HAVING filters groups after aggregation.
SELECT c.name, SUM(o.total) AS revenue
FROM customers AS c
INNER JOIN orders AS o ON o.customer_id = c.id
WHERE o.order_date >= '2026-02-01'
GROUP BY c.id, c.name
HAVING SUM(o.total) > 50;WHERE drops order 101 (January) first. Ada then has one order of 75.00 and Ben has one of 20.00. HAVING keeps only groups above 50, so only Ada remains.
Put conditions on individual rows in WHERE. Put conditions on aggregate results in HAVING. An aggregate function is not allowed in WHERE, and the database will report an error if you try.
Aggregating across several joins
Each extra join can multiply rows again. Consider revenue per product, where the join path is orders to order_items to products.
SELECT p.name AS product,
SUM(i.quantity) AS units_sold,
COUNT(DISTINCT o.id) AS orders_containing
FROM products AS p
INNER JOIN order_items AS i ON i.product_id = p.id
INNER JOIN orders AS o ON o.id = i.order_id
GROUP BY p.id, p.name
ORDER BY units_sold DESC;Here the grouping column p.id sits at the "one" end, and the measure i.quantity sits on the item rows, which are the finest grain in the query. Choosing a measure from the finest-grained table is the simplest way to stay safe. When you need measures from two different "many" branches, such as items and payments for the same order, joining both at once multiplies the branches against each other. Aggregate each branch in its own subquery first.
A debugging habit
When an aggregate looks wrong, remove the GROUP BY and aggregates, and inspect the raw joined rows:
SELECT c.id, c.name, o.id AS order_id, o.total, i.product_id, i.quantity
FROM customers AS c
INNER JOIN orders AS o ON o.customer_id = c.id
INNER JOIN order_items AS i ON i.order_id = o.id
ORDER BY c.id, o.id;Look for repeated order_id and total values. If they repeat, any sum of o.total is inflated. Then compare COUNT(*) with COUNT(DISTINCT o.id) to confirm.
Summary of rules
- Aggregates run on the joined rows, so inner join exclusions and row multiplication both affect them.
- Group by the primary key, and include the display columns you select.
- Inner joins drop parents with no children, so they cannot show zero counts.
- Use
COUNT(DISTINCT key)to count parents after a one-to-many join. - Pre-aggregate the many side in a subquery before joining when you need to sum a parent column.
- Use
WHEREfor row filters andHAVINGfor aggregate filters.
Exercise
Using the sample data with order items 101 (two items), 102 (one item), and no items for order 103, what does this query return for revenue, and is it correct for Ben? SELECT c.name, SUM(o.total) AS revenue FROM customers AS c INNER JOIN orders AS o ON o.customerid = c.id INNER JOIN orderitems AS i ON i.order_id = o.id GROUP BY c.id, c.name; How would you change it so that revenue counts every order exactly once?
Show answer
Ada appears with revenue 175.00, because order 101 (50.00) is repeated for its two items, plus order 102 (75.00). The correct figure is 125.00. Ben does not appear at all, because order 103 has no items and the second inner join removes it, even though Ben has 20.00 in orders. To fix both problems, drop the join to orderitems and sum o.total over customers joined to orders only. If item data is also needed, pre-aggregate orderitems per order in a subquery, or use an outer join so orders without items are kept.
Exercise
A report must show, for each customer, the number of orders and the total units ordered. Which COUNT form should you use for the order count when joining customers, orders and order_items, and why?
Show answer
Use COUNT(DISTINCT o.id). After joining to order_items, each order appears once per item, so COUNT(*) would count items rather than orders. COUNT(DISTINCT o.id) counts each order once. SUM(i.quantity) gives the total units, since quantity belongs to the item rows.