nested loop joins
for each outer row, look for matches. dumb, and perfect when one side is tiny. plus Memoize.
- address
- everything.execution.nested_loop_join
- part
- part 9, how a query runs
- chapter
- chapter 8 of 13
- reading time
- 8 min
a nested loop join is two loops: for each row of the outer side, look through the inner side for matches. with nothing to help, that's n × m comparisons. with an index on the inner side, each outer row is one index lookup, and EXPLAIN shows the inner node with loops=n.
dumb, and perfect when the outer side is small. Memoize makes it smarter when the outer side keeps asking for the same keys.
the picture
you know the join you'd write by hand in any language? for each customer: for each order: if order.customer_id == customer.id: emit. that's it. that's a nested loop, and postgres really does run it.
think of a coat check with no tickets. for each guest who comes back (the outer side), the attendant walks the whole rack (the inner side) looking for their coat. give the rack numbered hooks and a list of who's on which hook (an index), and each guest becomes one look at the list and one walk to one hook.
| id | name | |
|---|---|---|
| before first | ||
| 1 | Maya Chen | |
| 2 | Grace Okafor | |
| 3 | Sam Lee | |
| 4 | Zoë Martin | |
| id | customer_id | |
|---|---|---|
| before first | ||
| 1 | 1 | |
| 47 | 1 | |
| 511 | 3 | |
| 529 | 2 | |
| 566 | 2 | |
| 716 | 3 | |
| 1596 | 6 | |
| id | name | orders.id | customer_id |
|---|
scanfor each customers row, scan all of orders. no index, no memory, just two loops.
orders.customer_id, each customer is a short search for its key, and Zoë Martin, with no orders here, costs almost nothing.the outer side is read once. the inner side is read once per outer row: rescanned, in postgres's word. that's where the loops in EXPLAIN ANALYZE come from, and why actual rows on the inner side is a per-loop average (EXPLAIN ANALYZE).
four nested loops for one query
paris customers and their orders. postgres's own choice here is a hash join: 10,000 orders against 66 customers is exactly what hashing is for. switch hash and merge joins off, and it has to nested-loop, which shows every way it knows how:
- 1SET enable_hashjoin = off;
- 2SET enable_mergejoin = off;
- 3SET enable_memoize = off;
- 4SET enable_indexscan = off;
- 5SET enable_bitmapscan = off;
- 6EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
- 7SELECT c.name, o.id
- 8FROM customers AS c JOIN orders AS o ON o.customer_id = c.id
- 9WHERE c.city = 'Paris';
- Nested Loop (actual rows=369.00 loops=1)
- Join Filter: (c.id = o.customer_id)
- Rows Removed by Join Filter: 644709
- Buffers: shared hit=15 read=92
- -> Seq Scan on orders o (actual rows=10000.00 loops=1)
- Buffers: shared hit=14 read=69
- -> Materialize (actual rows=64.51 loops=10000)
- Storage: Memory Maximum Storage: 19kB
- Buffers: shared hit=1 read=23
- -> Seq Scan on customers c (actual rows=66.00 loops=1)
- Filter: (city = 'Paris'::text)
- Rows Removed by Filter: 1934
- Buffers: shared hit=1 read=23
hash and merge joins off, and no index either: every order is compared with the 66 paris customers, kept in memory by a Materialize, until it finds its own.
- no index: the 66 paris customers are scanned once and kept in memory by a Materialize, so the 10,000 rescans cost no page reads at all (107 pages in total). the cost is all CPU:
Rows Removed by Join Filter: 644709, more than 600,000 comparisons for 369 rows. (it's 64.51 per loop, not 66, becausec.idis unique: once an order finds its customer, the rest of the list can't match, so the loop stops early.) - index:
loops=10000andIndex Searches: 10000. every order goes down customers_pkey and fetches the customer: about 3 pages each, 30,083 in all. the Filter throws away the non-parisians after fetching them. - index + Memoize: the same lookups, through a cache keyed on
o.customer_id. 1,962 misses (different customers, looked up for real) and 8,038 hits (a customer seen before, answered from memory). 5,969 pages. - Memoize in 64kB: the cache needs 95kB to hold every customer it sees. at 64kB it throws the oldest out (
Evictions: 2253), customers come back after being evicted, and misses go up to 3,578.
Memoize, up close
Memoize pg 14+ sits between a nested loop and its inner side and remembers the inner result for each key. it pays off when the outer side repeats keys and the inner lookup costs something. postgres picks it on its own here, for the first 1,000 orders and their customers:
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT o.id, c.name
FROM orders AS o JOIN customers AS c ON c.id = o.customer_id
ORDER BY o.id
LIMIT 1000;-> Memoize (actual rows=1.00 loops=1000)
Cache Key: o.customer_id
Hits: 260 Misses: 740 Evictions: 0why a nested loop at all here, when hashing won the paris join? because of the LIMIT. a hash join has to build its whole hash table before it returns a row; this plan returns its first row after one index lookup, and stops after 1,000. that's a low startup cost, which is what a LIMIT pays for (the iterator model).
the joins a nested loop can do (and the one it can't)
a nested loop is the only join that works with any condition. hash and merge joins need an equality (a.x = b.y); a nested loop just evaluates the condition, whatever it is: <, BETWEEN, && on ranges, a function call. inequality joins are nested loops, always.
the one thing it can't do is FULL JOIN. a nested loop walks the inner side once per outer row, so it can tell you which outer rows never matched, but an inner row that never matched anyone has no moment where that becomes known... until the very end, after every rescan, and the nested loop doesn't keep score. so postgres doesn't offer it, even with hash joins switched off:
SET enable_hashjoin = off;
SET enable_mergejoin = off;
EXPLAIN (COSTS OFF)
SELECT c.name, o.id
FROM customers AS c FULL JOIN orders AS o ON o.customer_id = c.id;it picks the hash join anyway, and since postgres 18 it says so: Disabled: true pg 18+. switching a join type off only makes it look expensive. and with a condition neither hash nor merge can use, there's nothing left:
SELECT c.name, o.id
FROM customers AS c FULL JOIN orders AS o ON o.customer_id < c.id;keylines
- for each outer row, run the inner side: n × m without help, n index lookups with an index.
- the inner node's loops = outer rows, and its actual rows are per loop.
- Memoize caches the inner result per key: hits are free, misses run the lookup.
- the only join for conditions that aren't equalities, and the one that can't do FULL JOIN.
- low startup cost: the natural plan under a LIMIT, and the victim of a small row estimate.