Sub topic 12
Joining Along Keys
This chapter assumes you can write basic SELECT queries, know INNER JOIN and LEFT JOIN syntax, and have the customers, orders, products, and order_items tables from the earlier chapters. Here you will learn how keys decide which join to write, how many rows it returns, and where joins go wrong.
The join condition mirrors the foreign key
A foreign key declares which columns link a child table to its parent. A join states the same link in a query. For almost every key-based join, the ON clause is the foreign key column equal to the primary key column it references.
Reading the diagram tells you the join path. To connect customers to products, you must go through orders and order_items. No direct condition exists between customers and products.
One-to-many joins
SELECT c.name, o.order_id, o.ordered_at
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.customer_id
ORDER BY o.ordered_at;The parent side is unique on c.customer_id, so each order matches at most one customer. The result has one row per order, never more. Because orders.customer_id is NOT NULL and constrained, every order is guaranteed a matching customer. An inner join therefore cannot silently drop orders.
The reverse is not true. A customer with no orders has no match and disappears from an inner join. To keep such customers, use a LEFT JOIN from the parent:
SELECT c.name, o.order_id
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
ORDER BY c.name, o.order_id;Customers without orders appear once, with NULL in order_id.
Finding parents with no children
Checking the right-hand key for NULL after a left join finds parents that have no children. This is called an anti-join.
SELECT c.customer_id, c.name
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;Test the child's primary key, which can never be NULL in a real row. Testing a nullable column would confuse missing matches with real NULL values. NOT EXISTS expresses the same idea and is often clearer:
SELECT c.customer_id, c.name
FROM customers AS c
WHERE NOT EXISTS (
SELECT 1 FROM orders AS o WHERE o.customer_id = c.customer_id
);Many-to-many joins through a junction table
To list which products each order contains, join through order_items. Its two foreign keys give you two join conditions:
SELECT o.order_id, p.name AS product, oi.quantity
FROM orders AS o
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;Each join is many-to-one in the direction of travel: from order_items to orders, and from order_items to products. The result has one row per junction row. The composite primary key (order_id, product_id) guarantees that a product appears at most once per order, so you will not see duplicate pairs.
Row multiplication (fan-out)
Joining down a one-to-many path repeats the parent's values once per child row. That is correct, but it breaks aggregates computed at the parent level.
SELECT c.name,
COUNT(DISTINCT o.order_id) AS orders,
COALESCE(SUM(oi.quantity), 0) AS units
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
LEFT JOIN order_items AS oi ON oi.order_id = o.order_id
GROUP BY c.customer_id, c.name
ORDER BY c.name;After the second join there is one row per order item. A plain COUNT(*) would count items, and COUNT(o.order_id) would count each order once per item. COUNT(DISTINCT o.order_id) counts orders correctly. If you sum a column stored on orders (such as a shipping fee), the same repetition inflates the total. In that case, aggregate each child table in a subquery first and join the results.
Self-joins on hierarchies
A self-referencing key joins a table to itself. Give the two copies different aliases so you can tell the roles apart:
SELECT e.name AS employee, m.name AS manager
FROM employees AS e
LEFT JOIN employees AS m ON m.employee_id = e.manager_id
ORDER BY e.employee_id;e is the child side and m is the parent side. The LEFT JOIN matters because top-level employees have a NULL manager_id. An inner join would drop them. One self-join climbs exactly one level. For arbitrary depth, you need a recursive common table expression.
NULL foreign keys and join behavior
A NULL never equals anything, including another NULL. A row whose foreign key is NULL therefore never matches in an inner join, and it appears with NULL columns in a left join from the child. This is the intended behavior for an optional relationship. It also means you should choose the join type deliberately when a foreign key is nullable.
Putting filters in the right place
With an outer join, where you place a condition changes the result:
-- Keeps every customer; only matching orders are limited to 2026
SELECT c.name, o.order_id
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.customer_id
AND o.ordered_at >= TIMESTAMP '2026-01-01'
ORDER BY c.name;Moving the date test into WHERE removes rows where o.ordered_at is NULL. This turns the left join into an inner join and drops customers who have no orders.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Far more rows than expected | Missing or wrong `ON` condition, producing a cross product | Join on the foreign key and primary key columns |
| Parent rows missing from the result | Inner join where the child may not exist | Use `LEFT JOIN` from the parent |
| Inflated counts or sums | Fan-out from a one-to-many join | Use `COUNT(DISTINCT ...)` or pre-aggregate |
| Ambiguous column error | Same column name in both tables | Qualify columns with table aliases |
| Join on composite key returns duplicates | Only one of the key columns is in `ON` | Compare every column of the composite key |
Joins are faster when the foreign key column is indexed. The indexing chapter covers that.
Exercise
Write a query that lists every product that has never been ordered, using the tables above. Then explain why testing oi.order_id IS NULL works for this and what would break if you wrote the join as an inner join.
Show answer
SELECT p.productid, p.name FROM products AS p LEFT JOIN orderitems AS oi ON oi.productid = p.productid WHERE oi.orderid IS NULL; The left join keeps every product. Products with no matching junction row get NULL in all oi columns. `oi.orderid is part of the primary key of order_items`, so it can never be NULL in a real row, which means NULL here can only mean "no match". An inner join would discard unmatched products before the filter runs, so the query would return nothing.