Joining tables
Combine rows from related tables with INNER JOIN and LEFT JOIN.
20 min
Good databases keep each fact in one place. A customer's name is stored once, in customers; an order only stores the customer's id. That id is a foreign key: it points at a row in another table. To see names next to orders, you join the tables.
SELECT c.name, o.order_date
FROM orders o
JOIN customers c ON c.id = o.customer_id;orders ogives the table a short alias,o, so you can writeo.order_date.ON c.id = o.customer_idsays how rows match: a customer row and an order row are paired when the ids are equal.- A plain
JOINis an INNER JOIN: only rows with a match on both sides appear.
Customers with no orders vanish from an inner join. A LEFT JOIN keeps every row from the left table and fills the right side with NULL when there is no match:
SELECT c.name, o.id
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id;Grace and Hugo appear, with NULL for the order id. This is how you find rows with nothing related: add WHERE o.id IS NULL.
Chain the joins. To get each order line with the book title, go order_items to books:
SELECT o.order_date, b.title, oi.qty
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
JOIN books b ON b.id = oi.book_id;Join first, then group: COUNT(o.id) counts only the real orders, so a customer with none gets 0, whereas COUNT(*) would give 1 for the NULL row.
The bookshop tables and the keys that link them.
The two joins you will use most.
INNER JOIN (JOIN)
- Rows kept
- only rows with a match in both tables
- No match on the right gives
- the row is dropped
- Typical use
- pair things that must be related: orders with their customers
Best for normal reports
LEFT JOIN
- Rows kept
- every row from the left table
- No match on the right gives
- NULL in the right-hand columns
- Typical use
- keep everyone, even with nothing related: customers with zero orders
Best for finding what is missing, counting zero
Show the name of the customer and the order_date for every order with status 'shipped' placed by a customer who lives in Leeds.
Tables you can query
- customers (id, name, city, joined, email)
- orders (id, customer_id, order_date, status)
- order_items (order_id, book_id, qty)
SELECT c.name, o.order_date
FROM orders oShow every customer's name and the number of orders they have placed, as orders_n. Customers with no orders must appear with 0.
Tables you can query
- customers (id, name, city, joined, email)
- orders (id, customer_id, order_date, status)
- order_items (order_id, book_id, qty)
SELECT c.name,
FROM customers cFor every book that has been ordered, show the title and the total quantity sold as units. Most units first, then title A to Z.
Tables you can query
- books (id, title, author, genre, price, year, stock)
- orders (id, customer_id, order_date, status)
- order_items (order_id, book_id, qty)
SELECT b.title
FROM order_items oi“If I forget the ON clause, SQL just joins the tables sensibly.”
The tables obviously share an id, and a person would pair them up.
What is actually true
The database does not guess. With no matching condition, every row of one table pairs with every row of the other (a cross join): 10 customers and 10 orders give 100 rows of nonsense. Always write ON.
How to catch yourself
If a result suddenly has far more rows than either table, check your ON conditions.
- A foreign key stores another table's id;
JOIN ... ONpairs rows whose keys match. - An inner join drops rows with no match; a LEFT JOIN keeps every left-hand row and fills the gaps with NULL.
LEFT JOIN ... WHERE right.id IS NULLfinds rows with nothing related.- Use short aliases and write
ONfor every join;COUNT(right.id)counts real matches only.
Join checks.
Which join returns customers who have never ordered, when combined with WHERE o.id IS NULL?
- AINNER JOIN
- BLEFT JOIN from customers to orders
- CLEFT JOIN from orders to customers
- DCROSS JOIN
In FROM orders o JOIN customers c ON c.id = o.customer_id, what is customer_id?
- AA primary key of orders
- BA foreign key pointing at customers
- CAn alias
- DA function
customers has 8 rows and orders has 10. A join with no ON would return how many rows?
Why use COUNT(o.id) rather than COUNT(*) after a LEFT JOIN?
- AIt is faster
- BIt skips the NULL row for customers with no orders
- CIt sums prices
- DCOUNT(*) is not allowed
The part of a join that says which rows match starts with the keyword .
Capitalisation, spacing and punctuation are ignored when grading.
Practise this lesson, not just read it
In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of SQL for Beginners is planned around your week. Free.