Joining Many Tables
Chain several JOINs to follow keys across four tables, one step at a time, and keep the row count under control.
One JOIN per link
A real question often crosses more than two tables. You chain joins: each new JOIN adds one table and has its own ON test. The joins are applied from left to right, so the result of the first join is the input of the second.
A good habit is to follow the foreign keys. A customer has orders, an order has items, and an item points at a product. Each arrow is one join.
Names instead of ids
Tables store ids, because ids never change. A readable report needs the names behind them. Chained joins swap each id for the row it points at, in one query.
From customer to product name
SELECT c.name, o.id AS order_id, i.qty, p.name AS product
FROM customers AS c
JOIN shop_orders AS o ON c.id = o.customer_id
JOIN order_items AS i ON o.id = i.order_id
JOIN products AS p ON i.product_id = p.id;Build it one join at a time and check the result after each. The first join gives 3 rows (one per order). Joining the items gives 4, because order 101 has two items. Joining the products keeps 4 rows and adds the product name.
Every join is an INNER JOIN here, so a customer with no orders disappears. If that matters, make the first join a LEFT JOIN. Then Chen, Dara and Eli stay in the first step.
Add one join at a time
Press the three join steps and watch the SQL grow and the rows change. Then switch the first join to LEFT.
| nametext | order_idinteger |
|---|---|
| Asha | 101 |
| Asha | 102 |
| Ben | 103 |
Start with two tables: each customer is paired with each of their orders.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Chain one JOIN per link, each with its own ON, and follow the foreign keys.
- Joins are applied left to right: the result of one join feeds the next.
- A one-to-many join repeats the parent row once for each child row.
- Add the joins one at a time and check the row count after each.
Done with this concept?
Mark it complete to track your progress. No login needed.