skip to content

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.

algorithm =
join =
data =
customers
idname
before first
1Maya Chen
2Grace Okafor
3Sam Lee
4Zoë Martin
orders
idcustomer_id
before first
11
471
5113
5292
5662
7163
15966
comparisons
0
rows read
0
memory
·
batches
·
output
idnameorders.idcustomer_id
(0 rows)

scanfor each customers row, scan all of orders. no index, no memory, just two loops.

step 1/30
model of the join algorithms · checked against postgres 18.6
four customers and seven orders. switch between the plain nested loop and the index nested loop, and step through. the plain one compares every customer with every order: 4 × 7 = 28 comparisons. with an index on 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:

inner side =
query.sql
  1. 1SET enable_hashjoin = off;
  2. 2SET enable_mergejoin = off;
  3. 3SET enable_memoize = off;
  4. 4SET enable_indexscan = off;
  5. 5SET enable_bitmapscan = off;
  6. 6EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
  7. 7SELECT c.name, o.id
  8. 8FROM customers AS c JOIN orders AS o ON o.customer_id = c.id
  9. 9WHERE c.city = 'Paris';
what postgres printed
  1. Nested Loop (actual rows=369.00 loops=1)
  2. Join Filter: (c.id = o.customer_id)
  3. Rows Removed by Join Filter: 644709
  4. Buffers: shared hit=15 read=92
  5. -> Seq Scan on orders o (actual rows=10000.00 loops=1)
  6. Buffers: shared hit=14 read=69
  7. -> Materialize (actual rows=64.51 loops=10000)
  8. Storage: Memory Maximum Storage: 19kB
  9. Buffers: shared hit=1 read=23
  10. -> Seq Scan on customers c (actual rows=66.00 loops=1)
  11. Filter: (city = 'Paris'::text)
  12. Rows Removed by Filter: 1934
  13. Buffers: shared hit=1 read=23
pages touched (Buffers: shared hit + read)
107 pages
30,083 pages
5,969 pages
10,817 pages

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.

real output, postgres 18.6 (PGlite 0.5.12) · nested-loop
the same join, four ways, all with hash and merge joins switched off. watch the inner side: 10,000 loops through a materialized list, then 10,000 index lookups, then Memoize answering most of them from a cache, then the same cache squeezed into 64kB.
  • 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, because c.id is unique: once an order finds its customer, the rest of the list can't match, so the loop stops early.)
  • index: loops=10000 and Index 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:

sqldb=shop
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;
output, from postgres 18.6
EXPLAIN
Limit (actual rows=1000.00 loops=1) Buffers: shared hit=2192 read=41 -> Nested Loop (actual rows=1000.00 loops=1) Buffers: shared hit=2192 read=41 -> Index Scan using orders_pkey on orders o (actual rows=1000.00 loops=1) Index Searches: 1 Buffers: shared read=13 -> Memoize (actual rows=1.00 loops=1000) Cache Key: o.customer_id Cache Mode: logical Hits: 260 Misses: 740 Evictions: 0 Overflows: 0 Memory Usage: 65kB Buffers: shared hit=2192 read=28 -> Index Scan using customers_pkey on customers c (actual rows=1.00 loops=740) Index Cond: (id = o.customer_id) Index Searches: 740 Buffers: shared hit=2192 read=28 Planning: Buffers: shared hit=95 read=11 dirtied=1
predict the output
Hits: 260, Misses: 740, Evictions: 0. how many different customers placed those 1,000 orders?
text
->  Memoize (actual rows=1.00 loops=1000)
      Cache Key: o.customer_id
      Hits: 260  Misses: 740  Evictions: 0
outer rows
1,000
misses (lookups)
740
hits (from cache)
260
miss: the index scan runs hit: the cache answershits per 100 rows: 5 · 5 · 19 · 21 · 30 · 32 · 27 · 35 · 48 · 38
real output, postgres 18.6 (PGlite 0.5.12) · nested-loop
the 1,000 orders in the order the plan read them, one square each. miss: a customer not seen yet, so the index scan runs. hit: answered from the cache. hits get more common as the cache fills up. the counts are worked out from the captured keys and match the plan's Hits and Misses.

why 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:

sqldb=shop
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;
output, from postgres 18.6
#1 · SET
#2 · SET
#3 · EXPLAIN
Hash Full Join Disabled: true Hash Cond: (o.customer_id = c.id) -> Seq Scan on orders o -> Hash -> Seq Scan on customers c

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:

sqldb=shop
SELECT c.name, o.id
FROM customers AS c FULL JOIN orders AS o ON o.customer_id < c.id;
output, from postgres 18.6
ERROR 0A000: FULL JOIN is only supported with merge-joinable or hash-joinable join conditions

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.