Combining tables with JOIN
orders stores customer_id = 42, but the report needs the customer’s name, which lives in customers. A join puts them side by side:
SELECT o.id, o.created_at, c.name
FROM orders o
JOIN customers c ON c.id = o.customer_id;Read it as: “for each order, find the customer whose id equals the order’s customer_id, and give me columns from both.”
orders ogives the table a short nickname, an alias. Theno.idmeans “theidof orders” andc.id“theidof customers”. Both tables have anid, so without the prefix the database wouldn’t know which you mean.ONsays how rows match. It’s almost always “foreign key equals primary key”.JOINon its own meansINNER JOIN: only pairs that match are kept. An order whose customer doesn’t exist (impossible with a foreign key) would be dropped.
You get one row per match. Join orders to their items, and an order with three items comes back as three rows, each repeating the order’s columns. That’s not a bug, it’s what a join is: every combination that satisfies ON.
You can keep joining. Order, then its items, then each item’s product:
SELECT o.id AS order_id, p.name, oi.quantity
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
JOIN products p ON p.id = oi.product_id
WHERE o.id = 1001;A join is a filtered Cartesian product: every pair of rows for which the ON predicate is true. Things to have ready:
- Syntax. Explicit
JOIN … ONover comma joins (FROM a, b WHERE …), which hide a missing condition as an accidental cross join.USING (col)is fine when names match; avoidNATURAL JOIN, which silently joins on every same-named column (id,created_at). - Cardinality. Joining a parent to a one-to-many child repeats the parent per child. Joining it to two independent children (items and payments) produces items × payments rows per order, the “chasm trap”:
sum(oi.quantity * oi.unit_price)gets multiplied by the payment count. Aggregate each child first, then join (see below). - Algorithms. Nested loop: for each outer row, probe the inner side; great with a small outer side and an index on the inner join column. Hash join: build a hash table on the smaller input, stream the other; best for large equality joins, needs
work_mem. Merge join: both inputs sorted on the key (from indexes or a sort). The planner picks by estimated row counts, so bad estimates show up as nested loops over millions of rows. - Indexes. Index the foreign key side (
order_items.order_id,orders.customer_id); PostgreSQL doesn’t do it for you. - ORMs.
JOIN FETCH/@EntityGraphin JPA and@Relationin Room are joins (or follow-up queries) under the hood; the N+1 problemN+1 query problemRunning one query for a list and then one more query per item to load its related data.Open in glossary → is the absence of one.
Predict the output
Order 1001 has three items. Order 1002 has no items yet. How many rows does this return?
SELECT o.id, oi.product_id
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
WHERE o.id IN (1001, 1002);An inner join returns one row per matching pair. Order 1001 matches three items, so it appears three times. Order 1002 matches nothing, so it disappears completely. To keep orders without items you need a LEFT JOIN, the next part.
-- orders with the customer's name and email
SELECT o.id, o.status, o.total, c.name, c.email
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.created_at >= now() - interval '7 days'
ORDER BY o.created_at DESC;
-- everything in one order: product names, quantities, line totals
SELECT p.name, oi.quantity, oi.unit_price, oi.quantity * oi.unit_price AS line_total
FROM order_items oi
JOIN products p ON p.id = oi.product_id
WHERE oi.order_id = 1001
ORDER BY p.name;Worked example: a join, row by row
Take three tiny tables:
| customers.id | name |
|---|---|
| 1 | Ana |
| 2 | Ben |
| 3 | Cleo |
| orders.id | customer_id |
|---|---|
| 10 | 1 |
| 11 | 1 |
| 12 | 2 |
Now run SELECT o.id, c.name FROM orders o JOIN customers c ON c.id = o.customer_id;
- Start with order 10. Its
customer_idis 1. Which customer hasid = 1? Ana. Output:10, Ana. - Order 11. Also customer 1, so Ana again. Output:
11, Ana. Ana appears twice because she has two orders. - Order 12. Customer 2 is Ben. Output:
12, Ben. - What about Cleo? No order has
customer_id = 3, so no pair includes her. An inner join keeps only pairs, and Cleo isn’t in the result at all.
The result has three rows, one per order. If you need Cleo too, with an empty order, that’s a LEFT JOIN, coming next.
Deep diveJoin fan-out: the revenue report that doubledInterview favorite
The finance dashboard sums each day’s order value and payments:
SELECT o.created_at::date AS day,
sum(oi.quantity * oi.unit_price) AS sold,
sum(pay.amount) AS paid
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
JOIN payments pay ON pay.order_id = o.id
GROUP BY day;An order with 3 items and 2 payments (a split payment, or a failed attempt and a retry) produces 3 × 2 = 6 rows. sold counts every item twice, paid counts every payment three times. Most orders have one payment, so totals look plausible and the bug survives for months.
The fix is to aggregate each child to one row per order before joining:
WITH items AS (
SELECT order_id, sum(quantity * unit_price) AS sold
FROM order_items GROUP BY order_id
), paid AS (
SELECT order_id, sum(amount) AS paid
FROM payments GROUP BY order_id
)
SELECT o.created_at::date AS day, sum(i.sold) AS sold, sum(p.paid) AS paid
FROM orders o
JOIN items i ON i.order_id = o.id
LEFT JOIN paid p ON p.order_id = o.id
GROUP BY day;How to spot it in review: two one-to-many joins from the same parent plus an aggregate, or a DISTINCT / count(DISTINCT …) added “to fix duplicates”. Ask what the grain of the result is (one row per what?) and check that every join keeps it. When you only need to know whether a child exists, use EXISTS, which never multiplies rows.
JOIN … ON= filtered Cartesian product; inner join drops unmatched rows. Avoid comma joins andNATURAL JOIN.- One row per match: parent repeats per child. Two independent one-to-many joins multiply (chasm trap): aggregate children first, or use
EXISTS. - Nested loop (small outer, indexed inner), hash join (large equality), merge join (sorted). Index FK columns.
- Know the grain of every result before adding
sum,countorDISTINCT.
SELECT o.id, c.name, i.sold
FROM orders o
JOIN customers c ON c.id = o.customer_id
JOIN (SELECT order_id, sum(quantity * unit_price) AS sold
FROM order_items GROUP BY order_id) i ON i.order_id = o.id
WHERE EXISTS (SELECT 1 FROM payments p WHERE p.order_id = o.id);Check this part
What does ON c.id = o.customer_id do in a join?
A customer has no orders. Is she in the result of customers JOIN orders?
An order has 3 items and 2 payments. Joining orders to both and summing item values counts each item how many times?
When does the planner usually prefer a hash join?