Sub topic 6
Joining Three or More Tables
This chapter assumes you can write a two-table INNER JOIN with an ON condition and table aliases, and that you know primary keys and foreign keys. It extends that to three or more tables, shows how to read a chained join, and covers the errors that appear once a query grows.
Why chain joins
A normalized schema splits facts across tables. A customer's name lives in customers, the order in orders, the line items in order_items, and product names in products. To answer "which customer bought which product, and how many?" you must walk through all four tables.
Here are the two tables that complete the sample schema, together with the query that uses them.
CREATE TABLE products (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
CREATE TABLE order_items (
order_id INTEGER NOT NULL REFERENCES orders (id),
product_id INTEGER NOT NULL REFERENCES products (id),
quantity INTEGER NOT NULL,
PRIMARY KEY (order_id, product_id)
);
SELECT c.name AS customer, o.id AS order_id, p.name AS product, i.quantity
FROM customers AS c
INNER JOIN orders AS o ON o.customer_id = c.id
INNER JOIN order_items AS i ON i.order_id = o.id
INNER JOIN products AS p ON p.id = i.product_id;This code assumes customers and orders from the earlier chapters already exist. order_items is a junction table. It holds one row per product in an order, and its composite primary key (order_id, product_id) prevents the same product from appearing twice in one order.
The pattern: one table and one ON per join
Each additional INNER JOIN adds exactly one table and exactly one ON condition. The condition links the new table to a table that is already part of the query.
- Start with
customers AS c. - Join
orders AS oono.customer_id = c.id. - Join
order_items AS ioni.order_id = o.id. - Join
products AS ponp.id = i.product_id.
A query with N tables needs N - 1 join conditions. If you count fewer conditions than that, some pair of tables is being combined without a link, which produces a Cartesian product (every row paired with every row).
The diagram below shows the path as a chain of foreign keys.
Notice that order_items sits between orders and products. The relationship between orders and products is many-to-many, and the junction table resolves it into two one-to-many relationships.
Conceptual order versus execution order
You read a chained join from top to bottom as if each join takes the result so far and adds one table. That is the logical model:
customersjoined withordersproduces a set of rows.- That set joined with
order_itemsproduces a larger or equal set. - That set joined with
productsproduces the final rows.
The database does not have to execute it in that order. The optimizer is free to start from any table and join in any sequence, as long as the result matches the logical model. For inner joins, the order you write them in does not change the result. It can change the speed, which a later chapter covers.
Where the ON condition can reference
An ON condition can refer to the new table and any table written earlier in the FROM clause. It cannot refer to a table that appears later.
-- Fails: the ON for orders refers to order_items, which is joined later.
SELECT c.name
FROM customers AS c
INNER JOIN orders AS o ON o.id = i.order_id
INNER JOIN order_items AS i ON i.order_id = o.id;Most databases reject this with an error such as "missing FROM-clause entry" or "invalid identifier". Reorder the joins so that each table is introduced before something refers to it.
A condition may also link the new table to an earlier table other than the most recent one. In a star-shaped schema, several tables each link directly to one central table:
SELECT o.id, c.name AS customer, s.name AS shipper
FROM orders AS o
INNER JOIN customers AS c ON c.id = o.customer_id
INNER JOIN shippers AS s ON s.id = o.shipper_id;This example assumes an additional shippers table and a shipper_id column on orders. Both joins connect to orders, so the shape is a star, not a chain. Either shape works.
Every join can remove rows
With inner joins, a row survives only if it finds a match at every step. Adding a table can therefore shrink the result as well as widen it.
Suppose order 103 has no rows in order_items. The three-table join through order_items drops order 103, and Ben disappears from the output even though he does have an order. The earlier join to orders kept him, but the later join removed him.
This is the most common surprise with long inner-join chains. A single sparse table late in the chain can silently discard rows you wanted. To check, count rows after each join as you build the query.
SELECT COUNT(*) FROM customers AS c
INNER JOIN orders AS o ON o.customer_id = c.id;
SELECT COUNT(*) FROM customers AS c
INNER JOIN orders AS o ON o.customer_id = c.id
INNER JOIN order_items AS i ON i.order_id = o.id;If the second count is lower than expected, find which orders have no items. When the missing rows should still appear, you need an outer join, which a later chapter introduces.
Row counts grow with one-to-many links
The result has one row per complete matching path through the tables. If order 101 has three items, it produces three rows in the four-table query, and its customer value repeats on each. Joining through two one-to-many links multiplies the effect: an order with 3 items, joined to a second child table with 2 rows per order, yields 6 rows for that order.
This matters for aggregation. Summing o.total after joining to order_items counts each order's total once per item.
-- Wrong: each order's total is repeated once per matching order item.
SELECT SUM(o.total) AS inflated_revenue
FROM orders AS o
INNER JOIN order_items AS i ON i.order_id = o.id;Sum a column only from the table at the level you are aggregating. If you need order-level totals next to item-level detail, aggregate the child table in a subquery first, then join the result.
Building a long join safely
A reliable method for queries with many tables:
- Write the first two tables and run it. Check the row count and a few rows.
- Add one join at a time. Run it after each addition.
- Compare the row count with what the relationship predicts. A one-to-many join should grow the count or keep it the same, and a missing match should shrink it.
- Select only the columns you need once it is correct.
Use short, consistent aliases and qualify every column. With four or five tables, several will have columns named id or name, and an unqualified name raises an "ambiguous column" error.
Mixed and incomplete conditions
Two mistakes show up in multi-table queries.
- Wrong column in ON. Joining
p.id = o.idruns without error when both are integers, but it matches unrelated rows. Always check that the condition pairs a foreign key with the key it references. - Composite keys. If a table's key has two columns, the join needs both. Joining on only one column matches too many rows.
-- Hypothetical: shipments are keyed by (order_id, product_id).
SELECT i.order_id, i.product_id, s.shipped_on
FROM order_items AS i
INNER JOIN shipments AS s
ON s.order_id = i.order_id
AND s.product_id = i.product_id;This example assumes a shipments table with order_id, product_id and shipped_on columns.
Summary of the key points
| Situation | Effect on the result |
|---|---|
| A row has no match in a joined table | The row is dropped |
| A row has several matches | The row is repeated once per match |
| An ON condition is missing for a table | Every combination of rows appears |
| An ON condition uses only part of a composite key | Extra, unrelated matches appear |
Exercise
Customers Ada (orders 101 and 102) and Ben (order 103) are joined through orders to order_items to products. Order 101 has 2 items, order 102 has 1 item, and order 103 has no items. How many rows does the four-table inner join return, and which customer appears in them?
Show answer
Three rows, all for Ada: two for order 101 and one for order 102. Order 103 has no matching rows in order_items, so the join drops it and Ben does not appear. Chloe has no orders and is also absent.
Exercise
You join customers, orders and order_items with two ON conditions, then run SUM(o.total) grouped by customer. The revenue figures are too high. Why, and how would you fix it?
Show answer
Each order's total repeats once per order item after the join, so the sum counts it several times. Fix it by summing at the right level: aggregate orderitems in a subquery or avoid joining to orderitems when you only need order totals.