Sub topic 11
Chaining Several Joins
Prerequisites and what this chapter covers
This chapter assumes you can write LEFT JOIN and INNER JOIN with an ON condition. It also assumes you know why unmatched rows come back with NULL and how a filter in ON differs from one in WHERE. Real queries rarely join just two tables. Once you chain joins, a new class of bugs appears: an earlier outer join silently loses its "keep every row" guarantee. This chapter covers how a chain is evaluated, how a later join can undo an earlier one, and how row counts grow along the chain.
A third table for the examples
The chapter uses the customers and orders tables from earlier. It adds order_items, a child table of orders with one row per product in an order.
CREATE TABLE order_items (
item_id INT PRIMARY KEY,
order_id INT REFERENCES orders (order_id),
product VARCHAR(50) NOT NULL
);
INSERT INTO order_items (item_id, order_id, product) VALUES
(1, 101, 'Keyboard'),
(2, 101, 'Mouse'),
(3, 103, 'Monitor');Order 101 has two items, order 103 has one, and orders 102 and 104 have none. Cleo still has no orders at all.
How a chain is evaluated
A query with several joins is read from left to right. The first join combines two tables into an intermediate result. The next join takes that intermediate result as its left input and combines it with the next table. Each ON clause can refer to any table that appears earlier in the chain, not only the one directly before it.
SELECT c.name, o.order_id, i.product
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
LEFT JOIN order_items i ON i.order_id = o.order_id;
-- Ada 101 Keyboard
-- Ada 101 Mouse
-- Ada 102 NULL
-- Ben 103 Monitor
-- Cleo NULL NULLThe first join produces four rows: Ada twice, Ben, and Cleo padded with NULL. The second join takes those four rows and looks for items. Order 101 matches two items, so that row becomes two rows. Order 102 matches nothing, so it is kept with NULL in the item column. Cleo's row has NULL in o.order_id, and NULL = anything is never true, so no item matches and the row is kept with NULL padding.
When a chain gives a surprising answer, work through it one join at a time. Run the first join alone, check its rows, then add the next join. Each step's output is the input to the next.
The main trap: a later inner join undoes an earlier outer join
The first join in the chain preserves every customer. The second join works on the intermediate result, and it knows nothing about your intention to keep Cleo. If the second join is an INNER JOIN, it discards every intermediate row that finds no match.
SELECT c.name, o.order_id, i.product
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
INNER JOIN order_items i ON i.order_id = o.order_id;
-- Ada 101 Keyboard
-- Ada 101 Mouse
-- Ben 103 MonitorCleo is gone because her padded row has no matching item. Ada's order 102 is gone for the same reason. The query reads as a left join, but it behaves like an inner join over all three tables.
The same thing happens when a later join is a RIGHT JOIN or a FULL JOIN, or when a WHERE condition tests a right-side column. The rule is that every join in the chain decides what survives to the next step.
The usual fix is to use an outer join for each link that should not lose rows. The first query in this chapter does that. If you want customers and orders to be inner-joined but the items optional, choose the join type for each link separately.
| Chain | Cleo kept? | Ada order 102 kept? | Why |
|---|---|---|---|
| `customers LEFT JOIN orders LEFT JOIN order_items` | Yes | Yes | Both links preserve their left side. |
| `customers LEFT JOIN orders INNER JOIN order_items` | No | No | The inner join drops intermediate rows with no item. |
| `customers LEFT JOIN (orders INNER JOIN order_items)` | Yes | No | Orders without items vanish before the outer join runs. |
The third row of the table uses parentheses, which are covered next.
Controlling the order with parentheses
Sometimes you want one pair of tables joined first, as a unit, and then attached to the rest. Most databases let you put a join in parentheses, and the parenthesised join is evaluated first.
SELECT c.name, o.order_id, i.product
FROM customers c
LEFT JOIN (
orders o
INNER JOIN order_items i ON i.order_id = o.order_id
) ON o.customer_id = c.customer_id;
-- Ada 101 Keyboard
-- Ada 101 Mouse
-- Ben 103 Monitor
-- Cleo NULL NULLHere only orders that have items are eligible to match a customer. Cleo is kept because the outer join preserves customers. Ada's order 102 is absent because, inside the parentheses, it had no item.
Parenthesised joins are standard SQL, but they are not equally comfortable everywhere. If your database or tooling rejects them, a subquery in the FROM clause does the same job:
SELECT c.name, x.order_id, x.product
FROM customers c
LEFT JOIN (
SELECT o.order_id, o.customer_id, i.product
FROM orders o
INNER JOIN order_items i ON i.order_id = o.order_id
) x ON x.customer_id = c.customer_id;Filters in a chain
The ON versus WHERE rule from the previous chapter applies to every link. A condition on a right-side table placed in WHERE removes the NULL-padded rows, which turns the join it belongs to, and all the outer joins before it, into inner joins.
-- Cleo and Ben disappear: WHERE rejects NULL and non-matching products
SELECT c.name, o.order_id, i.product
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
LEFT JOIN order_items i ON i.order_id = o.order_id
WHERE i.product = 'Keyboard';
-- Ada 101 Keyboard
-- Customers and orders are all kept; only the item match is limited
SELECT c.name, o.order_id, i.product
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
LEFT JOIN order_items i ON i.order_id = o.order_id
AND i.product = 'Keyboard';
-- Ada 101 Keyboard
-- Ada 102 NULL
-- Ben 103 NULL
-- Cleo NULL NULLPut the condition in the ON clause of the join whose table it describes. Use WHERE only for conditions that should remove whole rows from the final result, and for the IS NULL test in an anti-join.
The anti-join test also needs care in a chain. To find customers with no items at all, test a column from the last table that cannot be NULL when a match exists:
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
LEFT JOIN order_items i ON i.order_id = o.order_id
WHERE i.item_id IS NULL;
-- CleoAda and Ben have items, so they do not appear. Cleo has no orders, so she has no items either.
Row multiplication grows along the chain
Each one-to-many join multiplies the rows of its left input by the number of matches. In a chain, the multiplication compounds. Order 101 appears twice after the item join, because it has two items. Any value from orders is repeated on both rows, and summing it counts it twice.
SELECT c.name,
COUNT(o.order_id) AS order_count,
SUM(o.total) AS total_spent
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
LEFT JOIN order_items i ON i.order_id = o.order_id
GROUP BY c.customer_id, c.name;
-- Ada 3 120.00
-- Ben 1 35.00
-- Cleo 0 NULLAda has two orders worth 70.00 in total, but the query reports three orders and 120.00. Order 101 is counted once for each of its two items. This is the most common silent error in chained joins, because the query runs without complaint and the numbers look plausible.
There are two ways to fix it:
- Use
COUNT(DISTINCT o.order_id). This works for counts, but not for sums:SUM(DISTINCT o.total)would also merge two different orders that happen to have the same total. - Collapse the many-side to one row per join key before joining it, using a subquery.
The second option is more reliable, and it scales to several child tables.
SELECT c.name,
COUNT(o.order_id) AS order_count,
COALESCE(SUM(o.total), 0) AS total_spent,
COALESCE(SUM(i.item_count), 0) AS item_count
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
LEFT JOIN (
SELECT order_id, COUNT(*) AS item_count
FROM order_items
GROUP BY order_id
) i ON i.order_id = o.order_id
GROUP BY c.customer_id, c.name;
-- Ada 2 70.00 2
-- Ben 1 35.00 1
-- Cleo 0 0 0The subquery returns at most one row per order, so the join to orders no longer multiplies rows. Orders without items get NULL for item_count, and SUM ignores those. COALESCE turns the all-NULL case for Cleo into 0.
A checklist for chained outer joins
- Start the chain from the table whose rows you must keep, and make each link an outer join if its left side must survive.
- Run the chain one join at a time and compare row counts at each step.
- Put filters on right-side tables in the
ONclause of that table's join. - Before using
SUMorCOUNT, ask whether any join in the chain matches one left row to several right rows. - Use a column that is never
NULLin a real match when you test for "no match".
Exercise
Using the tables from this chapter, a colleague writes the query below to list every customer with the products they ordered, keeping customers who ordered nothing. It returns only Ada and Ben. Explain why Cleo is missing and rewrite the query so she appears. SELECT c.name, i.product FROM customers c LEFT JOIN orders o ON o.customerid = c.customerid INNER JOIN orderitems i ON i.orderid = o.order_id;
Show answer
The first join keeps Cleo with NULL in the orders columns. The INNER JOIN then looks for an item whose orderid equals o.orderid, which is NULL for Cleo, so there is no match and her row is discarded. Ada's order 102, which has no items, is discarded the same way. Changing the second join to LEFT JOIN keeps every intermediate row: SELECT c.name, i.product FROM customers c LEFT JOIN orders o ON o.customerid = c.customerid LEFT JOIN orderitems i ON i.orderid = o.order_id; This returns Ada/Keyboard, Ada/Mouse, Ada/NULL, Ben/Monitor and Cleo/NULL.
Exercise
With the LEFT JOIN chain customers, orders, orderitems, the query SELECT c.name, SUM(o.total) FROM customers c LEFT JOIN orders o ON o.customerid = c.customerid LEFT JOIN orderitems i ON i.orderid = o.orderid GROUP BY c.customer_id, c.name reports 120.00 for Ada. Her orders total 70.00. Why, and how do you fix it?
Show answer
Order 101 (total 50.00) has two items, so the join to orderitems produces two rows for it, and SUM adds its total twice: 50 + 50 + 20 = 120. To fix it, avoid joining orderitems at all if no item data is needed. If items are needed, aggregate them per order in a subquery (SELECT orderid, COUNT(*) AS itemcount FROM orderitems GROUP BY orderid) and join that subquery instead, so each order stays on one row.