What you'll learn: By the end of this lesson you will be able to choose between inner, left, right, full, cross, self, semi, anti and lateral joins, explain why a filter in
ONand inWHEREgive different answers on an outer join, avoid theNOT INand NULL-key traps, spot and fix a join that multiplies rows and inflates a sum, and describe how PostgreSQL executes a join as a nested loop, a hash join or a merge join, using a PostgreSQL lab that runs every query.
Picture two guest lists at a wedding: people who were invited and people who replied. Matching them by name gives those who did both. The questions people actually ask are variations: who was invited but has not replied, who replied without an invitation, who is on either list. A join answers each, and each variation has its own join.
Databases Basics uses joins without defining them, and Normalization and Denormalization explains why normalized data needs them. This lesson covers the families, the traps and what happens underneath. Indexing join keys, reading plans and aggregation are separate lessons (backend-b-tree-indexes-and-sql-indexing, backend-query-plans-explain-analyze, backend-sql-aggregation-window-functions-and-ctes).
Verified with PGlite 0.6.1 (PostgreSQL 19.0, the engine the lab reports) and the PostgreSQL 18 documentation, on 2026-12-01.
The core idea
A join combines rows from two tables according to a condition, and the join type decides what happens to the rows that find no partner: an inner join drops them, an outer join keeps them with NULLs, a semi join keeps one row for each that has a partner, and an anti join keeps only the ones that have none. Most join bugs are not syntax errors; they are rows that quietly disappeared, rows that quietly multiplied, or a NULL that never matched.
Three illustrations run through the lesson:
- Minimal example: five shoppers and five orders you can read at a glance.
- Realistic example: ShopStream's win-back email list.
- Failure example: a
NOT INthat returns nothing because one order has no shopper.
The join family
Figure 1. The sample tables. How to read this: crow's-foot lines read left to right as "one shopper places many orders". Order 105 is a guest checkout, so its shopper_id is NULL. subscribers is joined to shoppers by email, not by a foreign key.
| Join | Keeps | Unmatched rows | Typical use |
|---|---|---|---|
INNER JOIN |
matching pairs | dropped from both sides | orders with their shoppers |
LEFT JOIN |
every left row | left row kept, right columns NULL | every shopper with their orders, if any |
RIGHT JOIN |
every right row | right row kept, left columns NULL | the same as a left join with the tables swapped |
FULL JOIN |
every row from both | kept on whichever side is missing | reconciling two lists |
CROSS JOIN |
every pairing | none: no condition | all shoppers by all delivery slots |
| semi join | left rows that have a partner, once each | dropped | shoppers who have ordered |
| anti join | left rows with no partner | those are the result | shoppers who have never ordered |
The PostgreSQL manual defines the outer joins by what they add: a left join is an inner join plus, "for each row in T1 that does not satisfy the join condition with any row in T2, a joined row ... with null values in columns of T2"; a right join is its converse; a full join adds both kinds. Semi and anti are not keywords in PostgreSQL; they are written with EXISTS, NOT EXISTS or LEFT JOIN ... IS NULL.
Figure 2. Choosing a join from the question. How to read this: start with the business question, not the SQL. "Only testing" means you do not need columns from the other table, which is the signal for semi and anti joins.
Inner, left and full on real rows
Expected output, captured from a real run (PGlite 0.6.1, PostgreSQL 19.0; a left join keeps Dara and Eli):
-- LEFT JOIN: every shopper, NULLs where no order matches
select s.name, o.order_id from shoppers s left join orders o on o.shopper_id = s.shopper_id order by s.shopper_id, o.order_id
name order_id
---- --------
Asha 101
Asha 103
Ben 102
Chen 104
Dara NULL
Eli NULL
A full join on email keeps both kinds of orphan: shoppers who do not subscribe and a subscriber who is not a shopper.
Expected output, captured from a real run (full join on email):
-- FULL JOIN on email: shoppers who do not subscribe, and subscribers who are not shoppers
select s.name, b.email as subscriber from shoppers s full join subscribers b on b.email = s.email order by s.shopper_id, b.email
name subscriber
---- ----------------
Asha asha@example.com
Ben ben@example.com
Chen NULL
Dara NULL
Eli NULL
NULL zoe@example.com
Where outer joins go wrong
Counting after a left join
count(*) counts rows, including the NULL-extended one a left join adds; count(column) counts only rows where the column is not null. The aggregate documentation says so directly: count(*) "Computes the number of input rows" and count("any") "Computes the number of input rows in which the input value is not null". Counting orders per shopper needs the second form.
Expected output, captured from a real run (Dara and Eli have a row but no order):
-- count(*) counts the NULL-extended row, count(o.order_id) does not
select s.name, count(*) as count_star, count(o.order_id) as orders
from shoppers s left join orders o on o.shopper_id = s.shopper_id group by s.shopper_id, s.name order by s.shopper_id
name count_star orders
---- ---------- ------
Asha 2 2
Ben 1 1
Chen 1 1
Dara 1 0
Eli 1 0
A filter in ON versus in WHERE
The manual explains why the two differ: "a restriction placed in the ON clause is processed before the join, while a restriction placed in the WHERE clause is processed after the join. That does not matter with inner joins, but it matters a lot with outer joins." A condition on the optional side belongs in ON if you want the unmatched rows kept. Put it in WHERE and the NULL-extended rows fail it and vanish, turning the left join into an inner join.
Expected output, captured from a real run (the same filter in ON, then in WHERE):
-- status filter in ON: Chen (only a cancelled order) and the others stay, with NULL
select s.name, o.order_id from shoppers s left join orders o on o.shopper_id = s.shopper_id and o.status = 'paid' order by s.shopper_id, o.order_id
name order_id
---- --------
Asha 101
Asha 103
Ben 102
Chen NULL
Dara NULL
Eli NULL
-- same filter in WHERE: runs after the join, so the NULL rows are discarded and the LEFT JOIN behaves like an INNER JOIN
select s.name, o.order_id from shoppers s left join orders o on o.shopper_id = s.shopper_id where o.status = 'paid' order by s.shopper_id, o.order_id
name order_id
---- --------
Asha 101
Asha 103
Ben 102
Semi joins, anti joins and the NOT IN trap
An anti join answers "who has no partner". Two forms are safe: NOT EXISTS, and LEFT JOIN ... WHERE right.key IS NULL. The third form, NOT IN, has a trap. The manual states it: if the subquery produces a null and no equal value, "the result of the NOT IN construct will be null, not true". In a WHERE clause a null result rejects the row.
Expected output, captured from a real run (NOT EXISTS finds two shoppers):
-- anti join with NOT EXISTS: shoppers with no order
select s.name from shoppers s where not exists (select 1 from orders o where o.shopper_id = s.shopper_id) order by s.shopper_id
name
----
Dara
Eli
Expected output, captured from a real run (NOT IN finds none, because the guest order's NULL shopper_id poisons the comparison):
-- NOT IN: orders.shopper_id contains one NULL (the guest order), so NOT IN is never true
select s.name from shoppers s where s.shopper_id not in (select shopper_id from orders) order by s.shopper_id
(no rows)
For EXISTS "the output list of the subquery is normally unimportant", so select 1 is the convention. A semi join never multiplies rows: a shopper with five orders still appears once.
Fan-out: joins can multiply rows
An inner join pairs each left row with every matching right row. Join an order to its lines and the order appears once per line. That is correct for a list of lines and wrong for summing a column that belongs to the order.
Expected output, captured from a real run (shipping summed three ways):
-- shipping total over orders: correct
select sum(shipping_cents)::int as shipping_total from orders
shipping_total
--------------
1500
-- the same sum after joining order_lines: each order is counted once per line
select sum(o.shipping_cents)::int as shipping_total, count(*)::int as joined_rows from orders o join order_lines l on l.order_id = o.order_id
shipping_total joined_rows
-------------- -----------
2400 8
-- fix: aggregate the many side first, then join
select sum(o.shipping_cents)::int as shipping_total, sum(t.items)::int as items
from orders o join (select order_id, sum(qty) as items from order_lines group by order_id) t on t.order_id = o.order_id
shipping_total items
-------------- -----
1500 9
The first sum is right (5 orders of 300 cents). After the join to order_lines the same sum is 2400, because eight joined rows repeat each order's shipping once per line. The fix is to aggregate the many side first, then join, so each order stays one row.
Self joins, cross joins and lateral joins
A self join joins a table to itself and needs aliases; the manual notes that "it is necessary to use them when joining a table to itself". Referrals are the classic case: a left self join keeps the shoppers nobody referred.
A cross join has no condition: "If the tables have N and M rows respectively, the joined table will have N * M rows." It suits a calendar-by-slot grid and is a disaster when a missing ON makes it accidental. NATURAL JOIN is risky too: "any schema changes to either relation that cause a new matching column name to be present will cause the join to combine that new column as well".
A LATERAL subquery "allows them to reference columns provided by preceding FROM items". Its common use is a top-N per row, such as the latest order per shopper, and a LEFT JOIN LATERAL ... ON true keeps shoppers with no rows.
Expected output, captured from a real run (latest order per shopper):
-- LEFT JOIN LATERAL with ORDER BY ... LIMIT 1 (the subquery sees s.shopper_id)
select s.name, last.order_id, last.placed_on::text as placed_on
from shoppers s
left join lateral (select o.order_id, o.placed_on from orders o where o.shopper_id = s.shopper_id order by o.placed_on desc limit 1) last on true
order by s.shopper_id
name order_id placed_on
---- -------- ----------
Asha 103 2026-01-09
Ben 102 2026-01-06
Chen 104 2026-01-10
Dara NULL NULL
Eli NULL NULL
NULL keys never match
An ordinary comparison with a null yields null. The manual says so: "Do not write expression = NULL because NULL is not 'equal to' NULL." A join on = therefore never pairs two NULL keys. If you do want NULLs to pair, IS NOT DISTINCT FROM "is identical to = for non-null inputs, but it returns true when both inputs are null".
Expected output, captured from a real run (two tables, each with a NULL code):
-- join with =: the NULL rows do not match each other
select a.code as a, b.code as b from region_a a join region_b b on a.code = b.code order by 1, 2
a b
- -
N N
-- join with IS NOT DISTINCT FROM: they do
select a.code as a, b.code as b from region_a a join region_b b on a.code is not distinct from b.code order by 1, 2
a b
---- ----
N N
NULL NULL
How the database runs a join
The join type says what the answer is; the planner chooses how to compute it. The manual describes three strategies:
- Nested loop. "The nested-loop join node will run its second, or 'inner' child once for each row obtained from the outer child."
- Hash join. "Rows of one table are entered into an in-memory hash table, after which the other table is scanned and the hash table is probed for matches to each row."
- Merge join. "Merge join requires its input data to be sorted on the join keys."
Figure 3. Build, then probe. How to read this: the first half reads one input once into a hash table; the second half reads the other input once and does a lookup per row. Which table is hashed, and whether a nested loop or merge join is cheaper, depends on sizes, statistics and indexes.
The planner chooses by estimated cost. To study alternatives the manual suggests switching strategies off with the enable_* settings, "a crude tool, but useful"; turning enable_nestloop off, for example, "discourages the planner from using one if there are other methods available".
Build it: every join on PostgreSQL
This is the minimal example, a lab you can run on PGlite, the real PostgreSQL server compiled to WebAssembly and run in-process. It reports PostgreSQL 19.0 while the course targets 18, and plan shapes depend on version, sizes and statistics, so the lab prints them for these sizes only.
Setup. From examples/postgres-labs, after npm install:
node --test labs/sql-joins/test.mjs
cd labs/sql-joins && node run.mjs
The first command runs 11 tests; the code is in examples/postgres-labs/labs/sql-joins/. The data is illustrative: 5 shoppers (Dara and Eli have no orders), 5 orders (one a guest checkout), 3 subscribers; section 9 generates 1,000 shoppers and 5,000 orders.
Steps. Run the tests, then the demo; sections 1 to 8 are the outputs above. Section 9 plans one query three ways, returning the same 5,000 rows each time:
Expected output, captured from a real run (default, then enable_hashjoin = off, then also enable_nestloop = off):
-- default settings
Hash Join
Hash Cond: (o.shopper_id = s.shopper_id)
-> Seq Scan on big_orders o
-> Hash
-> Seq Scan on big_shoppers s
rows: 5000
-- set enable_hashjoin = off
Nested Loop
-> Seq Scan on big_orders o
-> Memoize
Cache Key: o.shopper_id
Cache Mode: logical
-> Index Scan using big_shoppers_pkey on big_shoppers s
Index Cond: (shopper_id = o.shopper_id)
rows: 5000
-- set enable_hashjoin = off; set enable_nestloop = off
Merge Join
Merge Cond: (s.shopper_id = o.shopper_id)
-> Index Scan using big_shoppers_pkey on big_shoppers s
-> Sort
Sort Key: o.shopper_id
-> Seq Scan on big_orders o
rows: 5000
By default the planner chose a Hash Join. With hash joins discouraged it chose a Nested Loop with an index scan on the shoppers' primary key, and with nested loops discouraged too, a Merge Join that sorts the orders.
Break it. In the lab's count query add where o.status = 'paid' and watch Dara and Eli vanish. In the test file swap the ON and WHERE placements and the ON-versus-WHERE test fails. Restore both and re-run the tests.
Stretch. Try NATURAL JOIN on shoppers and orders, then add a status column to shoppers and see what changes.
What the model leaves out. Concurrent sessions, realistic table sizes and data skew, indexes beyond primary keys, and PostgreSQL 18 itself.
Trade-offs
| Option | Gain | Cost | Wrong when |
|---|---|---|---|
| Inner join | Smallest, simplest result | Silently drops unmatched rows | You must keep rows with no partner |
| Left join | Keeps every row on one side | NULLs to handle, counting traps | A WHERE on the right side turns it back into an inner join |
NOT EXISTS anti join |
Safe with NULLs | Slightly longer to write | You need columns from the other table |
NOT IN |
Short | Returns nothing if the subquery has a NULL | The column is nullable |
LATERAL |
Top-N per row | Runs once per outer row | A plain join would do |
In practice: ShopStream's win-back email list
This is the realistic example, an educational scenario on the course's running example ShopStream; nothing in it describes a real company. Every number is illustrative.
This is a realistic scenario, not a case history.
The situation
Marketing wants a weekly list of shoppers who have never placed an order, for a win-back offer. ShopStream's stage target is 500,000 orders per day (illustrative, from the course's shared numbers) and guest checkout is allowed, so some orders carry no shopper_id.
Starting architecture
Figure 4. The win-back path. How to read this: the whole feature is one query. The correctness of that query is the entire risk.
Options considered
| Option | Behaviour | Risk |
|---|---|---|
A. where shopper_id not in (select shopper_id from orders) |
Short | Returns no rows once any guest order exists |
B. where not exists (select 1 from orders o where o.shopper_id = s.shopper_id) |
Correct with NULLs | None for this question |
C. left join orders ... where o.order_id is null |
Correct, the same answer | Easy to break by adding an ON filter to WHERE |
The decision
Option B, with a test that includes a guest order, because the query's failure mode is silent: an empty list looks like "everyone has ordered".
Rollout and verification
Run the query on a copy and compare its count with one computed independently: all shoppers minus shoppers who appear in orders.
The 2 a.m. failure
The page reads: the win-back campaign sent zero emails. The query had been written with NOT IN, and the first guest order of the month put a NULL into orders.shopper_id, so the comparison was never true (the lab's last anti-join output shows exactly this).
The checks: run the subquery alone and look for NULLs. The mitigation is to switch to NOT EXISTS. The lasting fix is a test with a NULL key and a review rule against NOT IN over a nullable column.
Architect's notes
- Start from the question. "Every X, with its Y if any" is a left join; "X without Y" is an anti join.
- Put filters on the optional side in
ON; filters on the kept side go inWHERE. - Prefer
NOT EXISTStoNOT INwhenever the column can be null. - Join keys need indexes too. A foreign key "does not automatically create an index on the referencing columns" (PostgreSQL manual).
Common mistakes
- A
WHEREon the right table of a left join. It quietly makes the join inner. NOT INover a nullable column. It returns nothing.- Summing across a one-to-many join. The parent's value repeats.
- Forgetting that NULL keys do not match.
- A cross join by accident. A missing
ONis a Cartesian product.
Key takeaways
- The join type decides what happens to unmatched rows: dropped, kept with NULLs, or the point of the query.
- A filter in
ONruns before the outer join adds its rows; inWHEREit runs after. NOT INwith a NULL in the subquery returns nothing; useNOT EXISTS.- A join to the many side multiplies rows, so aggregate first.
- The same join can run as a nested loop, a hash join or a merge join; the planner picks by estimated cost.
Practice exercises
Exercise 1 (20 min). For each question, name the join: shoppers who never ordered; orders whose shopper was deleted; every shopper with every slot; the latest order per shopper.
Exercise 2 (45 min). Run the lab. Add a shopper with a NULL referred_by and predict the self-join output first.
Exercise 3 (1 hour). Compute revenue per shopper once with the fan-out bug and once fixed, and compare.
Exercise 4 (2 hours). Write the win-back query as NOT IN, NOT EXISTS and LEFT JOIN, run each with and without a guest order, and note which changes.
Related reading
- Databases Basics: the relational model, indexes and ACID.
- Normalization and Denormalization: why normalized tables need joins and when to copy data instead.
- ShopStream Stage 3: Choosing the Right Data Store for Each Job: the order tables used in the examples.
Official documentation
- PostgreSQL 18: Table Expressions: joined tables,
ONversusUSING,LATERAL. - PostgreSQL 18: SELECT: the
FROMclause, join types andNATURAL. - PostgreSQL 18: Subquery Expressions:
EXISTS,INandNOT IN. - PostgreSQL 18: Comparison Functions and Operators and Aggregate Functions.
- PostgreSQL 18: Using EXPLAIN and Planner Method Configuration.