Sub topic 11
Combining tables with joins
This chapter assumes you can write CREATE TABLE, INSERT, and SELECT ... WHERE. It also assumes you know how primary keys and foreign keys link tables. It uses the customers, orders, products, and order_items tables from earlier chapters.
Why joins exist
A well-designed schema stores each fact once. A customer's name lives in customers, and an order stores only the customer_id that points to that customer. The cost of this design is that no single table has everything you want to see. A join rebuilds the combined view at query time. It pairs rows from two tables whenever a condition you write is true. For a foreign key relationship, that condition compares the foreign key with the key it references.
A join does not change the stored data. It produces a temporary result set, and the tables stay as they were.
Sample data
The examples need a few more rows than the earlier chapters created. If you already inserted customer 1 and order 100, run only the statements below. Otherwise, insert those two rows first.
INSERT INTO customers (customer_id, name, email) VALUES
(2, 'Grace Hopper', '[email protected]'),
(3, 'Alan Turing', '[email protected]');
INSERT INTO orders (order_id, customer_id, order_date, total_amount) VALUES
(101, 1, '2026-02-03', 20.00),
(102, 2, '2026-02-10', 35.50);
INSERT INTO products (product_id, name) VALUES
(1, 'Keyboard'),
(2, 'Mouse'),
(3, 'Monitor');
INSERT INTO order_items (order_id, product_id, quantity) VALUES
(100, 1, 1),
(100, 2, 2),
(101, 2, 1),
(102, 3, 1);Alan Turing has no orders. That matters for the outer join later.
The inner join
An inner join returns a row only when the ON condition matches in both tables.
SELECT c.name, o.order_id, o.order_date, o.total_amount
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id
ORDER BY o.order_date;JOIN on its own means INNER JOIN. The result has three rows:
| name | order_id | order_date | total_amount |
|---|---|---|---|
| Ada Lovelace | 100 | 2026-01-15 | 59.90 |
| Ada Lovelace | 101 | 2026-02-03 | 20.00 |
| Grace Hopper | 102 | 2026-02-10 | 35.50 |
Alan does not appear. No order matches his customer_id, so the inner join drops him. Ada appears twice because she has two orders. A join produces one output row per matching pair, not one per customer.
The aliases c and o shorten the query. They also remove ambiguity. Both tables could have a column called name, and an unqualified name would then raise an "ambiguous column" error. Qualify any column that exists in more than one table. Oracle does not accept AS before a table alias, so write customers c there. PostgreSQL, MySQL, and SQLite accept both forms.
How a join is evaluated
Conceptually, the database pairs each row from one table with the rows from the other that satisfy ON. Real engines pick an efficient strategy, such as a nested loop, a hash join, or a merge join. The result is the same either way.
Outer joins and the missing side
A LEFT JOIN keeps every row from the left table, which is the one named before the JOIN keyword. Where no match exists, the right table's columns are filled with NULL.
SELECT c.name, o.order_id, o.order_date
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
ORDER BY c.customer_id, o.order_date;| name | order_id | order_date |
|---|---|---|
| Ada Lovelace | 100 | 2026-01-15 |
| Ada Lovelace | 101 | 2026-02-03 |
| Grace Hopper | 102 | 2026-02-10 |
| Alan Turing | NULL | NULL |
This gives you the "find rows with no related rows" pattern. Filter on a column from the right table that can only be NULL when no match exists. The primary key is the safest choice.
SELECT c.name
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;This returns only Alan Turing. Use IS NULL here, not = NULL, because comparing anything to NULL with = never yields true.
The other join types are summarized below.
| Join | Keeps | Notes |
|---|---|---|
| `INNER JOIN` | Only matching pairs | The default for `JOIN` |
| `LEFT JOIN` | All left rows, matches from the right | Most common outer join |
| `RIGHT JOIN` | All right rows, matches from the left | Same as a left join with the tables swapped |
| `FULL JOIN` | All rows from both sides | Not in MySQL. SQLite supports it from version 3.39 |
| `CROSS JOIN` | Every left row paired with every right row | No `ON` condition |
Most people write left joins and reorder the tables, so RIGHT JOIN is rarely needed.
Joining through a junction table
The many-to-many relationship between orders and products goes through order_items. Reading it needs a chain of joins. Each join adds one table, and each ON links the new table to one already in the query.
SELECT c.name, o.order_id, p.name AS product, oi.quantity
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id
JOIN order_items AS oi ON oi.order_id = o.order_id
JOIN products AS p ON p.product_id = oi.product_id
ORDER BY o.order_id, p.name;| name | order_id | product | quantity |
|---|---|---|---|
| Ada Lovelace | 100 | Keyboard | 1 |
| Ada Lovelace | 100 | Mouse | 2 |
| Ada Lovelace | 101 | Mouse | 1 |
| Grace Hopper | 102 | Monitor | 1 |
The junction table sits between orders and products. Its composite key (order_id, product_id) means one order can list a product only once, so the join cannot create duplicate pairs from the same line.
Counting with outer joins
Aggregates interact with NULL in ways that surprise people. Count a column from the right table, not *.
SELECT c.name, COUNT(o.order_id) AS order_count
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name
ORDER BY c.customer_id;Ada gets 2, Grace gets 1, and Alan gets 0. COUNT(o.order_id) skips NULL values. COUNT(*) would count Alan's single placeholder row and report 1.
Common errors
Forgetting the join condition
A join with no matching condition pairs every row with every other row. With 3 customers and 3 orders you get 9 rows. With 100,000 of each you get ten billion. Older comma syntax (FROM customers, orders) makes this easy to do by accident. Always use JOIN ... ON.
Row multiplication (fan-out)
Joining a "one" side to a "many" side repeats the one-side values. That is harmless for display but wrong for sums. This query tries to total each customer's order amounts after joining the line items:
SELECT c.name, SUM(o.total_amount) AS wrong_total
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id
JOIN order_items AS oi ON oi.order_id = o.order_id
GROUP BY c.customer_id, c.name;Order 100 has two line items, so its 59.90 is added twice. Ada's total comes out as 139.80 instead of 79.90. Aggregate before joining the many side, or sum a column that belongs to the many side, such as an item price.
Filtering an outer join in the wrong place
A WHERE condition on the right table runs after the join. For unmatched rows, those columns are NULL, and NULL >= '2026-02-01' is not true. The unmatched rows disappear and the query behaves like an inner join.
-- Drops Alan: the left join silently becomes an inner join
SELECT c.name, o.order_id
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
WHERE o.order_date >= '2026-02-01';
-- Keeps Alan: the filter is part of the match rule
SELECT c.name, o.order_id
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.customer_id
AND o.order_date >= '2026-02-01'
ORDER BY c.customer_id;The second query returns Ada with order 101, Grace with order 102, and Alan with NULL. Ada's January order no longer matches, but Ada still appears because order 101 does.
NULL keys never match
NULL = NULL is not true, so rows with a NULL in the join column never match anything in an inner join. This is rare with NOT NULL foreign keys like orders.customer_id. It does appear with optional foreign keys, and a left join keeps those rows.
Joins and performance
The database must find matching rows in the second table for every row from the first. Without help, it may scan the whole table each time. A primary key is indexed automatically, so lookups from orders.customer_id to customers.customer_id are fast. The reverse direction, finding all orders for one customer, uses the foreign key column. Many databases do not index foreign keys for you. PostgreSQL and SQL Server are examples. The index chapter covers this trade-off, but remember that join columns are the first candidates for an index.
Exercise
Write a query that lists each product's name and the total quantity ordered across all orders, including products that were never ordered (with a total of 0). Which join type do you need, and which table goes on the left?
Show answer
Put products on the left and use a LEFT JOIN to orderitems, so products with no line items are kept. Use COALESCE because SUM over no rows is NULL. SELECT p.name, COALESCE(SUM(oi.quantity), 0) AS totalquantity FROM products AS p LEFT JOIN orderitems AS oi ON oi.productid = p.productid GROUP BY p.productid, p.name ORDER BY p.product_id;
Exercise
A query uses LEFT JOIN orders to list all customers, then adds WHERE o.total_amount > 30. Alan, who has no orders, disappears from the result. Why, and how do you keep him?
Show answer
For Alan the order columns are NULL, and NULL > 30 is not true, so WHERE removes his row and the left join acts like an inner join. Move the condition into the join: LEFT JOIN orders AS o ON o.customerid = c.customerid AND o.total_amount > 30. Alan is then kept with NULL order columns.