Sub topic 9
One-to-many matches and repeated rows
This chapter assumes you can write a LEFT JOIN, you know that unmatched rows come back padded with NULL, and you have the customers and orders tables from earlier in this tutorial. The focus here is row counts. A join can return more rows than either input table has, and that changes what COUNT and SUM report.
Why one row becomes several
The relationship between customers and orders is one-to-many. One customer can have many orders, but each order belongs to at most one customer. A join pairs each left row with every right row that satisfies the ON condition. If three right rows match, the left row appears three times in the output.
SELECT c.customer_id, c.name, o.order_id, o.total
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
ORDER BY c.customer_id, o.order_id;
-- 1 Ada 101 50.00
-- 1 Ada 102 20.00
-- 2 Ben 103 35.00
-- 3 Cleo NULL NULLAda is stored once in customers but appears twice in the result. Each output row is one (customer, order) pair. The result is no longer "one row per customer".
Predicting the row count
You can work out the size of an outer join result before running it. For a LEFT JOIN, each left row contributes the larger of 1 and its number of matches.
| Customer | Matching orders | Rows in the result |
|---|---|---|
| Ada | 2 | 2 |
| Ben | 1 | 1 |
| Cleo | 0 | 1 (NULL-padded) |
| Total | 3 | 4 |
A FULL OUTER JOIN adds one row for each right row that matched nothing. Order 104 matches no customer, so the full join returns 5 rows.
Checking whether a join key is unique
Fan-out happens when you assume the right side has one row per key and it does not. Before joining, check the key you join on:
SELECT customer_id, COUNT(*) AS row_count
FROM orders
GROUP BY customer_id
HAVING COUNT(*) > 1;
-- 1 2Ada appears twice, so joining customers to orders on customer_id repeats Ada. That is correct for listing orders. It becomes a bug when you then treat each output row as a customer.
Fan-out with two one-to-many branches
The worst case is joining two independent one-to-many tables to the same parent. To see it, add a table of support tickets.
CREATE TABLE tickets (
ticket_id INT PRIMARY KEY,
customer_id INT REFERENCES customers (customer_id)
);
INSERT INTO tickets (ticket_id, customer_id) VALUES
(201, 1),
(202, 1),
(203, 3);Ada has 2 orders and 2 tickets. Orders and tickets are unrelated to each other, so the join pairs every order with every ticket:
SELECT c.name, o.order_id, t.ticket_id
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
LEFT JOIN tickets t ON t.customer_id = c.customer_id
ORDER BY c.customer_id, o.order_id, t.ticket_id;
-- Ada 101 201
-- Ada 101 202
-- Ada 102 201
-- Ada 102 202
-- Ben 103 NULL
-- Cleo NULL 203Ada produces 2 × 2 = 4 rows. For a customer with a orders and b tickets, the join returns a × b rows when both are non-zero. If one side has no rows, the NULL padding counts as one row, so the customer returns max(a, 1) × max(b, 1) rows.
Now aggregate over this result and see what goes wrong:
SELECT c.name,
COUNT(o.order_id) AS order_count,
COALESCE(SUM(o.total), 0) AS total_spent,
COUNT(t.ticket_id) AS ticket_count
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
LEFT JOIN tickets t ON t.customer_id = c.customer_id
GROUP BY c.customer_id, c.name
ORDER BY c.customer_id;
-- Ada 4 140.00 4
-- Ben 1 35.00 0
-- Cleo 0 0 1Ada really has 2 orders totalling 70.00 and 2 tickets. The query reports 4, 140.00 and 4, because each order is counted once per ticket and each ticket once per order. Ben and Cleo come out right only because one of their sides had no rows. The wrong numbers affect only some customers, which makes this bug easy to miss.
Fix 1: aggregate each branch before joining
Collapse each many-side to one row per customer in a subquery, then join the results. Each join now matches at most one row, so nothing multiplies.
SELECT c.name,
COALESCE(o.order_count, 0) AS order_count,
COALESCE(o.total_spent, 0) AS total_spent,
COALESCE(t.ticket_count, 0) AS ticket_count
FROM customers c
LEFT JOIN (
SELECT customer_id, COUNT(*) AS order_count, SUM(total) AS total_spent
FROM orders
GROUP BY customer_id
) o ON o.customer_id = c.customer_id
LEFT JOIN (
SELECT customer_id, COUNT(*) AS ticket_count
FROM tickets
GROUP BY customer_id
) t ON t.customer_id = c.customer_id
ORDER BY c.customer_id;
-- Ada 2 70.00 2
-- Ben 1 35.00 0
-- Cleo 0 0 1The COALESCE calls are still needed. A customer with no orders has no row in the orders subquery, so the join pads order_count and total_spent with NULL. The COALESCE calls turn those NULLs into 0.
Fix 2: pick one row per parent
Sometimes you do not want totals. You want one representative row per customer, such as the largest order. Rank the many-side rows in a subquery, then join only the row ranked first.
SELECT c.name, o.order_id, o.total
FROM customers c
LEFT JOIN (
SELECT order_id, customer_id, total,
ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY total DESC, order_id
) AS rn
FROM orders
) o ON o.customer_id = c.customer_id AND o.rn = 1
ORDER BY c.customer_id;
-- Ada 101 50.00
-- Ben 103 35.00
-- Cleo NULL NULLThe tie-breaker order_id makes the choice deterministic. Without it, two orders with the same total could be ranked in either order, and the result could change between runs. The rank filter o.rn = 1 sits in the ON clause, so Cleo is kept. Putting it in WHERE would remove her, for the reason covered in the chapter on filtering in ON versus WHERE.
Why DISTINCT is not a fix
Adding SELECT DISTINCT removes duplicate output rows, but it hides the multiplication without correcting it. There are two problems.
- Duplicates that are genuinely different facts get merged. If Ada had two orders of 20.00,
SUM(DISTINCT o.total)would count 20.00 once and report too little. - It makes the database sort or hash every row, which can be expensive on large fan-out joins.
COUNT(DISTINCT o.order_id) does give the right order count in the two-branch query, because order_id is unique per order. It does not help SUM, since the values being summed are not unique identifiers. Pre-aggregating is the safer habit.
| Approach | Handles counts | Handles sums | Notes |
|---|---|---|---|
| Plain join, then `GROUP BY` | Only with one many-side | Only with one many-side | Inflated with two many-sides |
| `COUNT(DISTINCT id)` | Yes | No | Needs a unique id column |
| `SUM(DISTINCT value)` | No | Unreliable | Merges equal values |
| Aggregate before joining | Yes | Yes | Needs a subquery per branch |
| Rank and join `rn = 1` | Not applicable | Not applicable | Returns one detail row per parent |
A quick sanity check
A cheap test is to compare the row count against what you expect. For a query that should return one row per customer, run SELECT COUNT(*) on the joined result and compare it to SELECT COUNT(*) FROM customers. With the sample data both should be 3. The two-branch join above returns 6 rows, which tells you immediately that the result is not one row per customer.
Exercise
A customer has 3 orders and 4 tickets. You run customers LEFT JOIN orders LEFT JOIN tickets, joining each table on customerid. How many rows does that customer produce, and what does COUNT(o.orderid) return for them after GROUP BY? What is the correct order count?
Show answer
The customer produces 3 × 4 = 12 rows, because each order is paired with each ticket. COUNT(o.orderid) returns 12, since every one of the 12 rows has a non-NULL orderid. The correct order count is 3. To get it, aggregate orders and tickets in separate subqueries before joining, or use COUNT(DISTINCT o.order_id) for the count.
Exercise
Using the sample data, how many rows does customers FULL OUTER JOIN orders return, and why? Give the count for each customer and for order 104.
Show answer
It returns 5 rows. Ada has 2 matching orders, so 2 rows. Ben has 1, so 1 row. Cleo has none, so 1 NULL-padded row. Order 104 has a NULL customer_id and matches no customer, so it adds 1 row with a NULL customer side. Total: 2 + 1 + 1 + 1 = 5.