Learning navigation

Code with Animation

Joining Many Tables

Chain several JOINs to follow keys across four tables, one step at a time, and keep the row count under control.

SQL5 min readConcept 16 of 44

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.

SELECT c.name, o.id AS order_id
FROM customers AS c
INNER JOIN shop_orders AS o ON c.id = o.customer_id
ORDER BY c.id, o.id NULLS LAST;
Result (3 rows)
nametextorder_idinteger
Asha101
Asha102
Ben103

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.

  1. 1In `A JOIN B ON ... JOIN C ON ...`, what does the second join use as its left input?
  2. 2Order 101 has two items. After joining customers, orders and order_items, how many rows does order 101 make?
  3. 3You want every customer to stay, even those without orders, in a four table chain. Where do you start?

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.