Skip to content

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.

24 min read0/4 questions

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:

  1. Take every row of the left table paired with every row of the right table.
  2. Keep the pairs where the ON condition is true.
  3. 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.

customers JOIN orders ON orders.customer_id = customers.id
o1 c1o2 c2o3 c1o4 c3o6 c2o8 c1
Ada (1)??????
Grace (2)??????
Alan (3)??????
Katherine (4)??????

Four customers and six of their orders. Conceptually, a join considers every pair: 4 × 6 = 24 candidates.

1/4

INNER JOIN

An inner join keeps only matching pairs. JOIN on its own means INNER JOIN.

Pythoninner_join.py
from shopdb import connect, showdb = connect() show(db, """SELECT c.name, o.id AS order_id, o.status, o.created_atFROM customers AS cJOIN orders AS o ON o.customer_id = c.idWHERE c.city = 'London'ORDER BY o.created_at""")
Output
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:

Pythonmulti_join.py
from shopdb import connect, showdb = connect() show(db, """SELECT o.id AS order_id, c.name AS customer, p.name AS product, cat.name AS category, oi.quantity * oi.unit_price_cents AS line_centsFROM orders AS oJOIN customers AS c ON c.id = o.customer_idJOIN order_items AS oi ON oi.order_id = o.idJOIN products AS p ON p.id = oi.product_idJOIN categories AS cat ON cat.id = p.category_idWHERE o.id IN (1, 5)ORDER BY o.id, p.name""")
Output
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":

Pythonleft_join.py
from shopdb import connect, showdb = connect() print("Filter in ON: every customer stays")show(db, """SELECT c.name, o.id AS shipped_orderFROM customers AS cLEFT JOIN orders AS o ON o.customer_id = c.id AND o.status = 'shipped'ORDER BY c.id, o.id""") print("Filter in WHERE: customers without a shipped order vanish")show(db, """SELECT c.name, o.id AS shipped_orderFROM customers AS cLEFT JOIN orders AS o ON o.customer_id = c.idWHERE o.status = 'shipped'ORDER BY c.id, o.id""")
Output
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.

Predict the outputPython

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))
Need a nudge? Hints walk you through it.

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.

Pythonfull_join.py
from shopdb import connect, showdb = connect() db.executescript("""CREATE TABLE warehouse_counts (product_id INTEGER PRIMARY KEY, counted INTEGER);INSERT INTO warehouse_counts VALUES (1, 12), (2, 28), (3, 150), (7, 0), (99, 4);""") show(db, """SELECT COALESCE(p.id, w.product_id) AS product_id, p.stock, w.counted, CASE WHEN p.id IS NULL THEN 'only in warehouse' WHEN w.product_id IS NULL THEN 'not counted' WHEN p.stock <> w.counted THEN 'mismatch' ELSE 'ok' END AS check_resultFROM products AS pFULL OUTER JOIN warehouse_counts AS w ON w.product_id = p.idWHERE p.id IS NULL OR w.product_id IS NULL OR p.stock <> w.countedORDER BY product_id""")
Output
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:

Pythoncross_join.py
from shopdb import connect, showdb = connect() show(db, """SELECT cat.name AS category, s.statusFROM categories AS catCROSS JOIN (SELECT DISTINCT status FROM orders) AS sWHERE cat.parent_id IS NULLORDER BY cat.name, s.status""")
Output
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:

Pythonself_join.py
from shopdb import connect, showdb = connect() show(db, """SELECT e.name, e.title, m.name AS managerFROM employees AS eLEFT JOIN employees AS m ON m.id = e.manager_idORDER BY e.department, m.name NULLS FIRST, e.name""")
Output
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.
Pythonsemi_anti.py
from shopdb import connect, showdb = connect() print("Semi join with EXISTS: each customer once")show(db, """SELECT c.nameFROM customers AS cWHERE EXISTS ( SELECT 1 FROM orders AS o WHERE o.customer_id = c.id AND o.status IN ('paid', 'shipped'))ORDER BY c.name""") print("Anti join with LEFT JOIN ... IS NULL")show(db, """SELECT c.nameFROM customers AS cLEFT JOIN orders AS o ON o.customer_id = c.idWHERE o.id IS NULLORDER BY c.name""") print("Anti join with NOT EXISTS: same answer, clearer intent")show(db, """SELECT c.nameFROM customers AS cWHERE NOT EXISTS (SELECT 1 FROM orders AS o WHERE o.customer_id = c.id)ORDER BY c.name""")
Output
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.

Quick check
Which query reliably finds products that have never been ordered?
Need a nudge? A hint rules out a wrong answer.

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:

Pythonfan_out.py
from shopdb import connect, showdb = connect() print("Wrong: joining items AND events multiplies every item by every event")show(db, """SELECT c.name, SUM(oi.quantity * oi.unit_price_cents) AS revenue_cents, COUNT(DISTINCT e.id) AS eventsFROM customers AS cJOIN orders AS o ON o.customer_id = c.idJOIN order_items AS oi ON oi.order_id = o.idJOIN events AS e ON e.user_id = c.idWHERE c.id IN (1, 2)GROUP BY c.id, c.name""") print("Right: aggregate each child table first, then join one row per customer")show(db, """SELECT c.name, r.revenue_cents, ev.eventsFROM customers AS cJOIN (SELECT o.customer_id, SUM(oi.quantity * oi.unit_price_cents) AS revenue_cents FROM orders AS o JOIN order_items AS oi ON oi.order_id = o.id GROUP BY o.customer_id) AS r ON r.customer_id = c.idJOIN (SELECT user_id, COUNT(*) AS events FROM events GROUP BY user_id) AS ev ON ev.user_id = c.idWHERE c.id IN (1, 2)ORDER BY c.id""")
Output
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:

Pythonnatural_join.py
from shopdb import connect, showdb = connect() show(db, "SELECT COUNT(*) AS natural_rows FROM orders NATURAL JOIN customers")show(db, """SELECT COUNT(*) AS correct_rowsFROM orders AS o JOIN customers AS c ON c.id = o.customer_id""")
Output
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:

Pythonjoin_plan.py
from shopdb import connectdb = connect() sql = "SELECT c.name, o.id FROM customers c JOIN orders o ON o.customer_id = c.id"for row in db.execute("EXPLAIN QUERY PLAN " + sql): print(row[-1]) db.execute("CREATE INDEX orders_customer_id ON orders (customer_id)")print("-- after indexing orders.customer_id")for row in db.execute("EXPLAIN QUERY PLAN " + sql): print(row[-1])
Output
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 the pairs0/6 matched

Match each question to the join that answers it.

Choose an item, then its match on the other side.
Quick check
A report joins orders to order_items and to payments (an order can have several partial payments), then sums payments.amount. Totals look too high. Why?
Need a nudge? A hint rules out a wrong answer.
Key terms
inner join
Returns only the pairs of rows where the join condition is true. JOIN on 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.