Show contents
Chapter 1 of 7 · 20 min
Joins: linking tables
By the end of this chapter, you'll be able to
- Link two or more tables with JOIN … ON
- Keep rows without a match with LEFT JOIN
- Find orphan items with LEFT JOIN … IS NULL
- Use aliases to write readable, unambiguous queries
The shop's database
An online shop sells solar equipment and water filters. Its database contains four tables:
| Table | Content | Link |
|---|---|---|
customers | id, name, city, country | |
products | id, name, category, price | |
orders | id, customer_id, date, status | customer_id → customers.id |
order_items | order_id, product_id, quantity | one row per product ordered |
customer_id is a foreign key: it contains the id of a row in another table. It's what links an order to its customer.
JOIN: linking two tables
SELECT o.id AS order_id, c.name AS customer, c.city, o.status
FROM orders AS o
JOIN customers AS c ON c.id = o.customer_id
ORDER BY o.id;
order_id | customer | city | status
1 | Aïcha | Abidjan | delivered
2 | Bruno | Recife | delivered
3 | Aïcha | Abidjan | delivered
4 | Chen | Chengdu | shipped
5 | Dalia | Cairo | cancelled
6 | Aïcha | Abidjan | pending
FROM orders AS ogives the table the aliaso: you writeo.statusinstead oforders.status.JOIN customers AS c ON c.id = o.customer_idpairs each order with the customer whoseidequals itscustomer_id.JOINalone meansINNER JOIN: only rows that have a match on both sides are kept.
Erik has no orders: no row of orders points to him, so he doesn't appear. That's how INNER JOIN behaves.
Text description of the animation
- SQL takes order 1, whose customer_id is 1.
- It looks in customers for the row where id = 1: Aïcha. The combined row is produced.
- Same for order 2, with Bruno.
- Erik has no orders: no row of orders points to him, so he doesn't appear. That's how INNER JOIN behaves.
You can chain joins. An order's amount needs four tables: the order, its customer, its items and each product's price:
SELECT o.id AS order_id, c.name AS customer, ROUND(SUM(i.quantity * p.price), 2) AS amount
FROM orders AS o
JOIN customers AS c ON c.id = o.customer_id
JOIN order_items AS i ON i.order_id = o.id
JOIN products AS p ON p.id = i.product_id
WHERE o.status <> 'cancelled'
GROUP BY o.id
ORDER BY amount DESC;
order_id | customer | amount
4 | Chen | 140
3 | Aïcha | 107
1 | Aïcha | 59
2 | Bruno | 40
6 | Aïcha | 18.5
LEFT JOIN: keeping those who have nothing
"How many orders per customer, including those who have none?" A JOIN would make Erik disappear. LEFT JOIN keeps all the rows of the left table; when there's no match, the right-hand columns are NULL:
SELECT c.name, COUNT(o.id) AS nb_orders
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id
GROUP BY c.id
ORDER BY nb_orders DESC, c.name;
name | nb_orders
Aïcha | 3
Bruno | 1
Chen | 1
Dalia | 1
Erik | 0
COUNT(o.id) counts non-null values: 0 for Erik. COUNT(*) would have counted his row and displayed 1.
To find the orphans, those with no match, keep precisely the rows where the right side is NULL:
SELECT c.name AS customer
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id
WHERE o.id IS NULL;
customer
Erik
Your turn
Mini-lab: what each customer spentSQLite
Result
Click “Run”: the SQL engine (about 1 MB) will load in your browser the first time.
A fresh SQLite database is created on every run, in your browser · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Worked exercise
Solved exercise: revenue per category
Display, for each product category, the number of units sold and the revenue, counting only delivered orders. Sort by decreasing revenue.
Hint 1
order_items, which holds the quantities, and join products (for the price and category) and orders (for the status).Hint 2
i.quantity * p.price; add it up per category with GROUP BY p.category.Show the solution and common mistakes
SELECT p.category, SUM(i.quantity) AS units, ROUND(SUM(i.quantity * p.price), 2) AS revenue
FROM order_items AS i
JOIN products AS p ON p.id = i.product_id
JOIN orders AS o ON o.id = i.order_id
WHERE o.status = 'delivered'
GROUP BY p.category
ORDER BY revenue DESC;
category | units | revenue
energy | 5 | 157
water | 2 | 49
Common mistakes:
- Forgetting the join with
orders: you then can't filter on the status, and the cancelled order is counted. - Writing
ON i.product_id = i.order_id(a condition comparing two columns of the same table): the query runs, but pairs rows at random. Check that eachONlinks two different tables.
Summary
- 1A foreign key holds the id of a row in another table; JOIN … ON uses it to link the tables.
- 2JOIN (INNER JOIN) keeps only rows that have a match on both sides.
- 3LEFT JOIN keeps every left-hand row, with NULL when there's no match.
- 4LEFT JOIN … WHERE right.id IS NULL finds the orphans.
- 5With a join, always prefix columns with an alias.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.