Lesson 6 of 29Joining and aggregating
Joins of Every Kind
INNER, LEFT, RIGHT, FULL, CROSS and self joins, semi and anti joins, the ON versus WHERE trap, and the fan-out that doubles your totals.
So far every query has read one table at a time. Real questions almost never live in one table. "Which customers have not ordered since March?" needs customers and orders. "Revenue by category" needs four tables. Joins are how you combine them, and they are where most wrong numbers come from: a report that quietly drops customers with no orders, or a revenue dashboard that doubles after someone adds one more join. This lesson builds an exact mental model of what a join does with rows, then works through every kind you will use, the traps that produce wrong answers without any error, and what interviewers probe.
What a join actually does
Forget Venn diagrams. They show sets of values, but a join works on pairs of rows. The precise model is:
- Take every row of the left table paired with every row of the right table.
- Keep the pairs where the
ONcondition is true. - For an outer join, add back left (or right) rows that found no partner, with NULLs for the other side.
The database never really builds every pair, because that would be far too slow. But the result is always the same as if it had, and reasoning this way predicts row counts exactly. In particular, a row that matches three rows appears three times. A Venn diagram cannot show that, and it is the cause of most join bugs.
Four customers and six of their orders. Conceptually, a join considers every pair: 4 × 6 = 24 candidates.
INNER JOIN
An inner join keeps only matching pairs. JOIN on its own means INNER JOIN.
Press Run (⌘ Enter) to see what happens.Give every table a short alias and qualify every column (c.name, o.status). Unqualified names break as soon as both tables gain a column with the same name, such as created_at, which both of these tables already have.
You will also see the old comma style: FROM customers c, orders o WHERE o.customer_id = c.id. It means the same thing, but if you forget the condition you get every pair with no error. Explicit JOIN ... ON keeps the join logic next to the join, so prefer it.
Joining three or more tables
Joins chain. Each new JOIN attaches to the rows built so far. To list every line of every order with the customer, product and category:
Press Run (⌘ Enter) to see what happens.Follow the foreign keys: orders to customers, orders to items, items to products, products to categories. Each join here goes from a "many" row to its single parent, except order_items, which multiplies each order by its number of lines. Knowing which joins multiply rows is the skill behind the fan-out section below.
LEFT JOIN, and the ON versus WHERE trap
LEFT JOIN keeps every row of the left table. Rows with no match get NULLs for the right side. It is how you answer any question that must include "and those with none":
Press Run (⌘ Enter) to see what happens.This is the most common join bug at work. The ON condition decides which rows match. WHERE runs after the join, on the combined rows. For customers with no shipped order, the join produced NULLs, o.status = 'shipped' is unknown for NULL (as NULL and three-valued logic showed), and WHERE throws those rows away. The LEFT JOIN has silently become an inner join. The rule: conditions on the right-hand table of a LEFT JOIN go in ON, unless you are deliberately testing for NULL.
How many rows does this return? (Shipped orders belong to customers 1, 1, 2 and 5.)
from shopdb import connect
db = connect()
rows = db.execute("""
SELECT c.id, o.id
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.id AND o.status = 'shipped'
""").fetchall()
print(len(rows))RIGHT and FULL OUTER JOIN
RIGHT JOIN is a LEFT JOIN with the tables swapped. It is valid, but most teams rewrite it as a LEFT JOIN so every query reads "keep all of the first table". You will see it mostly in generated SQL.
FULL OUTER JOIN keeps unmatched rows from both sides. Its everyday job is reconciliation: comparing two sources that should agree, such as a warehouse count against the product table, or yesterday's export against today's.
Press Run (⌘ Enter) to see what happens.Every kind of disagreement shows up in one query: products nobody counted, a count for a product that does not exist, and stock that differs.
CROSS JOIN
CROSS JOIN returns every pair with no condition: 6 categories times 4 statuses is 24 rows. That sounds useless until you need a complete grid, such as every product for every day so that days with zero sales still appear as zero rather than missing:
Press Run (⌘ Enter) to see what happens.You then LEFT JOIN the real data onto the grid. The accidental cross join is the dangerous one: a missing or wrong join condition between two tables of 100,000 rows each produces 10 billion pairs, and the query either runs forever or returns nonsense.
Self joins
A table can join to itself. employees.manager_id points at another row of employees, so finding each person's manager means using the table twice under two aliases:
Press Run (⌘ Enter) to see what happens.The LEFT JOIN keeps the people with no manager (the CTO and the head of sales). With an inner join they would disappear. A self join climbs one level. Walking a whole management chain of unknown depth needs a recursive CTE, which comes later in this unit.
Semi joins and anti joins
Two questions come up constantly and are not really joins at all:
- Semi join: "customers who have at least one paid order". You want each customer once, no matter how many matches.
- Anti join: "customers with no orders". You want the rows that match nothing.
Press Run (⌘ Enter) to see what happens.Writing the semi join as a plain JOIN would list Ada three times, and people often reach for DISTINCT to hide that. EXISTS says what you mean, and it stops at the first match. For the anti join, the IS NULL test must be on a column that can never be NULL in a real match, such as the right table's primary key. Prefer NOT EXISTS over NOT IN: as NULL and three-valued logic showed, NOT IN returns nothing at all if the subquery contains a single NULL. Postgres usually plans NOT EXISTS and the LEFT JOIN ... IS NULL form as the same anti join, so choose the one that reads best.
Fan-out: the double-counted total
Joining a parent to one child table multiplies each parent row by its number of children. That is fine until you join two child tables of the same parent, or sum a parent-level number after joining a child. Then the totals are silently multiplied:
Press Run (⌘ Enter) to see what happens.Ada's real revenue is 2,374.00, but the first query reports six times that, because she has six events and every item row was copied once per event. Notice that COUNT(DISTINCT e.id) still looked right, which makes the bug harder to spot. DISTINCT cannot rescue a SUM: two different items that both cost 39.00 would be collapsed into one. The reliable fix is to aggregate each one-to-many branch to one row per key before joining. When a total looks too big, count the rows per key before the aggregate; fan-out shows up immediately.
USING, and why NATURAL JOIN is dangerous
When both columns share a name, JOIN ... USING (customer_id) is shorthand for ON a.customer_id = b.customer_id, and the output has a single customer_id column. It is tidy and safe because you list the column.
NATURAL JOIN goes further and joins on every column with the same name, without listing them. In this schema, orders and customers share id and created_at:
Press Run (⌘ Enter) to see what happens.The natural join matched order id against customer id and required equal created_at dates, which is meaningless, and found nothing. Worse, a natural join that works today changes meaning the day someone adds an updated_at column to both tables. Never use it in application code.
LATERAL joins in Postgres
Sometimes the right side of a join needs to depend on the current left row, such as "each customer's two most recent orders". Postgres has LATERAL for this: the subquery runs once per left row and may refer to it.
SELECT c.name, recent.id, recent.created_at
FROM customers AS c
LEFT JOIN LATERAL (
SELECT o.id, o.created_at
FROM orders AS o
WHERE o.customer_id = c.id
ORDER BY o.created_at DESC
LIMIT 2
) AS recent ON true;With an index on orders (customer_id, created_at), each lookup is a short index read, which makes this fast for "top N per group". SQLite has no LATERAL, and MySQL added it in 8.0.14. Window functions solve the same problem in every database, and they get their own lesson later in this unit.
How the database runs a join
You describe the result; the planner picks the algorithm. There are three:
- Nested loop: for each outer row, look up matches in the inner table. Fast when the outer side is small and the inner side has an index on the join column.
- Hash join: build a hash table from the smaller input, then stream the larger one past it. The workhorse for large joins on equality.
- Merge join: walk two inputs already sorted on the join key side by side.
The practical lesson is to index your foreign key columns. Postgres indexes primary keys automatically but not the columns that point at them, so orders.customer_id needs its own index before nested loops on it become cheap. Reading EXPLAIN shows you how to see which algorithm was chosen and why.
See SQLite's plan for a join
SQLite only uses nested loops, but it reorders tables and uses indexes to make them cheap. EXPLAIN QUERY PLAN shows the choice:
Press Run (⌘ Enter) to see what happens.Each line is one loop, outermost first. Before the index, SQLite scans orders and looks up each customer by primary key. After it, the scan reads the smaller covering index on customer_id instead of the table. On bigger tables, the same index is what lets the planner search orders per customer instead of scanning it.
Match each question to the join that answers it.
orders to order_items and to payments (an order can have several partial payments), then sums payments.amount. Totals look too high. Why?- inner join
- Returns only the pairs of rows where the join condition is true.
JOINon its own means inner join. - outer join
- LEFT, RIGHT or FULL: also keeps rows with no match from one or both sides, filling the other side with NULLs.
- self join
- Joining a table to itself under two aliases, such as an employee row to their manager's row.
- semi join
- Keeps rows from one table that have at least one match in another, each once. Written with EXISTS or IN.
- anti join
- Keeps rows that have no match. Written with NOT EXISTS or
LEFT JOIN ... WHERE right.id IS NULL. - fan-out
- The row multiplication from joining one-to-many relations, which inflates sums and counts if you aggregate afterwards.
- LATERAL
- A Postgres join where the subquery on the right can refer to the current left row, useful for top N per group.