Sub topic 2
Joining Three or More Tables
Prerequisites
This chapter assumes you can write a single INNER JOIN with an ON condition, use table aliases, and understand primary and foreign keys. The examples use the customers, orders, order_items and products tables.
Joining three or more tables
Add one INNER JOIN for each extra table. Each join needs its own ON condition that links the new table to a table already in the query.
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;The database pairs rows one join at a time. A row appears in the result only if it matches on every join.
Filtering joined rows: WHERE versus ON
The ON condition decides which rows pair up. The WHERE clause filters the paired rows. For inner joins, moving a condition between ON and WHERE gives the same result. Keep join logic in ON and business filters in WHERE so the query stays readable and remains correct if you later switch to an outer join.
SELECT c.name, o.id AS order_id, o.total
FROM customers AS c
INNER JOIN orders AS o ON o.customer_id = c.id
WHERE o.total > 30;Why rows with NULL keys disappear
NULL means "no value." A comparison with NULL is never true, not even NULL = NULL. So a row with a NULL join column never matches. Order 104 has no customer, so this query leaves it out:
SELECT o.id AS order_id, c.name
FROM orders AS o
INNER JOIN customers AS c ON c.id = o.customer_id;The result contains orders 101, 102 and 103 only.
One-to-many matches and row counts
One customer can have many orders, and one order can have many items. Each matching pair becomes one output row. Joining orders to order_items therefore repeats each order once per item. Summing a column from the orders table after that join overcounts:
-- Wrong: each order total is counted once per item.
SELECT SUM(o.total) AS inflated_revenue
FROM orders AS o
INNER JOIN order_items AS i ON i.order_id = o.id;To count each order once, filter the orders table with a subquery instead of joining the items:
SELECT SUM(o.total) AS revenue
FROM orders AS o
WHERE o.id IN (SELECT i.order_id FROM order_items AS i);Exercise
Using the customers, orders, order_items and products tables, order 101 contains two items and order 102 contains one. Each item has a matching product. How many rows does the three-join query return for those two orders?
Show answer
Three rows. Order 101 produces two rows, one for each item, and order 102 produces one row.