Sub topic 11
Aggregating across joins without inflating totals
This chapter assumes you can write INNER JOIN and LEFT JOIN, and that you know GROUP BY, COUNT(*) versus COUNT(column), and how aggregates treat NULL. The examples use three tables: customers, orders and order_items.
The problem: a join changes the row count
An aggregate sums whatever rows reach it. A join can produce more rows than the table you started from. When it does, SUM and COUNT add the same data several times. This is called join fan-out.
Consider these tables:
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(50) NOT NULL
);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers (customer_id),
amount DECIMAL(10, 2) NOT NULL,
status VARCHAR(20) NOT NULL
);
CREATE TABLE order_items (
item_id INTEGER PRIMARY KEY,
order_id INTEGER NOT NULL REFERENCES orders (order_id),
sku VARCHAR(20) NOT NULL,
quantity INTEGER NOT NULL
);
INSERT INTO customers VALUES (1, 'Ada'), (2, 'Ben'), (3, 'Cleo');
INSERT INTO orders VALUES
(10, 1, 100.00, 'paid'),
(11, 1, 50.00, 'paid'),
(12, 2, 80.00, 'paid');
INSERT INTO order_items VALUES
(1, 10, 'A-1', 2),
(2, 10, 'B-2', 1),
(3, 10, 'C-3', 5),
(4, 11, 'A-1', 1),
(5, 12, 'B-2', 4);Ada has two orders totalling 150.00. Ben has one order of 80.00. Cleo has no orders. Order 10 has three item rows.
Fan-out in action
Suppose you want each customer's total order amount, and you join all three tables:
SELECT c.customer_id,
SUM(o.amount) AS total_amount
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id
JOIN order_items AS i ON i.order_id = o.order_id
GROUP BY c.customer_id;The result is:
| customer_id | total_amount |
|---|---|
| 1 | 350.00 |
| 2 | 80.00 |
Ada's true total is 150.00. The join repeated order 10 once for each of its three items, so its 100.00 was added three times: 100 × 3 + 50 = 350. Ben's total is correct only because order 12 has a single item.
The error is easy to miss. The query runs without complaint, and totals are right for any customer whose orders each have one child row.
Why it happens
A join produces one output row for every matching pair. Joining orders to order_items is a one-to-many relationship: one order, many items. The "one" side is repeated for every row on the "many" side.
Aggregating happens after the join. The GROUP BY sees only the joined rows and cannot tell that three of them came from the same order.
Fan-out occurs whenever you aggregate a column from the "one" side after joining to the "many" side. Aggregating a column from the "many" side, such as SUM(i.quantity), is safe because each item row appears once.
Fix 1: aggregate before you join
The most reliable fix is to collapse each child table to the grain you need, then join the result. Grain means what one row represents. After the aggregation, each subquery has one row per join key, so the join cannot multiply anything.
SELECT c.customer_id,
c.name,
COALESCE(o.total_amount, 0) AS total_amount,
COALESCE(i.total_quantity, 0) AS total_quantity
FROM customers AS c
LEFT JOIN (
SELECT customer_id,
SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id
) AS o ON o.customer_id = c.customer_id
LEFT JOIN (
SELECT o2.customer_id,
SUM(oi.quantity) AS total_quantity
FROM orders AS o2
JOIN order_items AS oi ON oi.order_id = o2.order_id
GROUP BY o2.customer_id
) AS i ON i.customer_id = c.customer_id
ORDER BY c.customer_id;The result:
| customer_id | name | total_amount | total_quantity |
|---|---|---|---|
| 1 | Ada | 150.00 | 4 |
| 2 | Ben | 80.00 | 4 |
| 3 | Cleo | 0 | 0 |
Each derived table has exactly one row per customer_id. Joining on that key is one-to-one, so no row is repeated. The LEFT JOIN keeps Cleo, and COALESCE turns her missing sums into 0.
Use this approach when you need aggregates from two or more independent child tables. If you join two many-side tables directly, each one multiplies the other.
Fix 2: aggregate at the right level with a CTE
A common table expression (CTE) is a named subquery defined with WITH. It does the same job as the derived tables above and is easier to read when there are several steps:
WITH order_totals AS (
SELECT customer_id,
COUNT(*) AS order_count,
SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id
)
SELECT c.name,
COALESCE(t.order_count, 0) AS order_count,
COALESCE(t.total_amount, 0) AS total_amount
FROM customers AS c
LEFT JOIN order_totals AS t ON t.customer_id = c.customer_id
ORDER BY c.name;The pattern is the same. Reduce first, join second.
Fix 3: COUNT(DISTINCT) for counts
For counting, COUNT(DISTINCT ...) removes the repeats. To count each customer's orders after joining to items:
SELECT c.customer_id,
COUNT(DISTINCT o.order_id) AS order_count,
COUNT(i.item_id) AS item_count
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
LEFT JOIN order_items AS i ON i.order_id = o.order_id
GROUP BY c.customer_id
ORDER BY c.customer_id;| customer_id | order_count | item_count |
|---|---|---|
| 1 | 2 | 4 |
| 2 | 1 | 1 |
| 3 | 0 | 0 |
Plain COUNT(o.order_id) would give 4 for Ada, because order 10 appears three times and order 11 once.
Do not use SUM(DISTINCT o.amount) to fix a sum. It removes repeated amounts by value, not by order. If two different orders both have an amount of 50.00, the second one is dropped and the total is wrong. DISTINCT is safe for counting identifiers, because a primary key value uniquely names a row. It is not safe for summing measures.
COUNT(*) versus COUNT(column) with LEFT JOIN
When you join from a parent table with LEFT JOIN, a parent with no children still produces one row, with NULL in every child column. COUNT(*) counts that row. COUNT(o.order_id) skips it because the value is NULL.
SELECT c.customer_id,
COUNT(*) AS wrong_count,
COUNT(o.order_id) AS order_count
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
GROUP BY c.customer_id
ORDER BY c.customer_id;| customer_id | wrong_count | order_count |
|---|---|---|
| 1 | 2 | 2 |
| 2 | 1 | 1 |
| 3 | 1 | 0 |
Cleo shows 1 with COUNT(*) and 0 with COUNT(o.order_id). Count a column from the child side, preferably its primary key, which is never NULL in a real row.
Where to put filters on the child table
A condition on the child table has a different meaning in ON than in WHERE when you use LEFT JOIN.
-- Keeps every customer; counts only paid orders
SELECT c.customer_id,
COUNT(o.order_id) AS paid_orders
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.customer_id
AND o.status = 'paid'
GROUP BY c.customer_id;If you moved o.status = 'paid' into a WHERE clause, Cleo's row (where o.status is NULL) would fail the test and disappear. The LEFT JOIN would then behave like an inner join. Keep the child filter in ON when you want to preserve parents with no matches.
Many-to-many joins
Fan-out is worst when two many-side tables hang off the same parent. Imagine each customer also has several phone_numbers rows. Joining orders and phone_numbers to customers yields orders × phones rows per customer. A customer with 3 orders and 4 phones produces 12 rows, and every order amount is counted 4 times. The fix is the same: aggregate each child separately, then join the one-row-per-customer results.
Checking for fan-out
Before trusting a joined total, compare it with a figure you can get without the join.
- Compute the total from the single source table:
SELECT SUM(amount) FROM orders;. - Compute it from the joined query, with the same filters.
- If the numbers differ, the join is multiplying rows.
You can also compare row counts. Run SELECT COUNT(*) on the parent table and on the joined result. If the joined count is larger than the parent count, then each parent row is repeated, and aggregating parent columns is unsafe.
A third check is to confirm the grain. Ask what one row of the joined result represents. If the answer is "one item" and you are summing an order-level column, you have a mismatch.
Summary of rules
| Situation | Safe approach |
|---|---|
| Sum or average a parent column after joining to a child | Aggregate the child first, or aggregate the parent separately |
| Count parents after joining to children | `COUNT(DISTINCT parent_key)` |
| Aggregates from two independent child tables | One pre-aggregated subquery or CTE per child |
| Keep parents with no children | `LEFT JOIN`, count a child column, `COALESCE` the sums |
| Filter child rows but keep all parents | Put the condition in `ON` |
Exercise
Using the tables in this chapter, you run SELECT c.customer_id, SUM(o.amount) FROM customers c JOIN orders o ON o.customer_id = c.customer_id JOIN order_items i ON i.order_id = o.order_id WHERE c.customer_id = 1 GROUP BY c.customer_id; and get 350.00. Why is it wrong, and how would you rewrite it to return 150.00?
Show answer
Order 10 has three item rows, so the join repeats its 100.00 three times (100 × 3 + 50 = 350). Remove the join to orderitems, since the amount does not need item data: SELECT customerid, SUM(amount) FROM orders WHERE customerid = 1 GROUP BY customerid. If item data is also needed, aggregate orders and order_items in separate subqueries (one row per customer each) and join those.
Exercise
A LEFT JOIN from customers to orders uses COUNT(*) and shows 1 for a customer with no orders. Which expression gives 0, and why?
Show answer
COUNT(o.order_id). The unmatched customer row has NULL in every orders column, and COUNT(column) skips NULLs, while COUNT(*) counts the row itself.