skip to content

merge joins

two sorted inputs, two cursors walking forward. why sorted order is a resource.

address
everything.execution.merge_join
part
part 9, how a query runs
chapter
chapter 10 of 13
reading time
8 min

a merge join takes two inputs sorted on the join key and walks them with two cursors, always advancing the one that's behind. each row is read once, apart from a short step back over runs of duplicate keys.

the catch is the sorting. if an index (or an earlier step) already delivers the rows in order, the merge is nearly free. if not, a Sort has to pay for it first. sorted order is a resource.

the picture

you know how you'd compare two guest lists that are both in alphabetical order? one finger on each. if the names match, tick them. if not, move the finger that's on the earlier name. you never go back to the top, and you're done when either list runs out.

that's the whole algorithm. the inputs being sorted is what lets one finger skip ahead without ever missing a match: everything before it is smaller, everything after it is bigger.

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

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

step 1/42
model of the join algorithms · checked against postgres 18.6
eight orders and five customers. switch to merge join and step through: it sorts both sides on the key, then the two cursors walk down together. two orders for the same customer send the customers cursor back to its mark; add a duplicate key gives a customer a twin, and the rewind walks a run of two. the nested loop is there to compare comparison counts with.

when the index already did the sorting

orders and their items, in order:

sqldb=shop
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT o.id, o.status, oi.line_no, oi.qty
FROM orders AS o JOIN order_items AS oi ON oi.order_id = o.id
ORDER BY o.id;
output, from postgres 18.6
EXPLAIN
Merge Join (actual rows=24942.00 loops=1) Merge Cond: (o.id = oi.order_id) Buffers: shared hit=6 read=335 -> Index Scan using orders_pkey on orders o (actual rows=10000.00 loops=1) Index Searches: 1 Buffers: shared hit=3 read=109 -> Index Scan using order_items_pkey on order_items oi (actual rows=24942.00 loops=1) Index Searches: 1 Buffers: shared hit=3 read=226 Planning: Buffers: shared hit=88 read=14 dirtied=1

no Sort anywhere. orders_pkey hands over orders by id, order_items_pkey starts with order_id, so its rows come out sorted on the join key too. the merge join walks the two index scans side by side, and its output is already in o.id order, so the ORDER BY costs nothing either. one sorted stream feeds the next.

predict the output
customers JOIN orders ON o.customer_id = c.id, by merge join. which input needs a Sort?
sql
-- shop has an index on customers.id (the primary key)
-- and none on orders.customer_id
SELECT c.name, o.id
FROM customers AS c JOIN orders AS o ON o.customer_id = c.id;

that's not hypothetical. here's the same join with an ORDER BY, before and after that index:

index on orders.customer_id =
query.sql
  1. 1EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
  2. 2SELECT c.id, c.name, o.id
  3. 3FROM customers AS c JOIN orders AS o ON o.customer_id = c.id
  4. 4ORDER BY c.id
what postgres printed
  1. Sort (actual rows=10000.00 loops=1)
  2. Sort Key: c.id
  3. Sort Method: quicksort Memory: 648kB
  4. Buffers: shared hit=84 read=23
  5. -> Hash Join (actual rows=10000.00 loops=1)
  6. Hash Cond: (o.customer_id = c.id)
  7. Buffers: shared hit=84 read=23
  8. -> Seq Scan on orders o (actual rows=10000.00 loops=1)
  9. Buffers: shared hit=83
  10. -> Hash (actual rows=2000.00 loops=1)
  11. Buckets: 2048 Batches: 1 Memory Usage: 87kB
  12. Buffers: shared hit=1 read=23
  13. -> Seq Scan on customers c (actual rows=2000.00 loops=1)
  14. Buffers: shared hit=1 read=23

customers and their orders, by customer. nothing hands orders over sorted by customer_id, so postgres hashes, then sorts all 10,000 rows for the ORDER BY.

real output, postgres 18.6 (PGlite 0.5.12) · merge-join
without an index on orders.customer_id, postgres hashes and then sorts all 10,000 joined rows for the ORDER BY. with one, it merges two index scans, and the result comes out in customer order for free.

that's what "sorted order is a resource" means. a b-tree is a sorted copy of its columns (what an index actually is), and a plan can spend that order on a merge join, an ORDER BY, a GROUP BY or a DISTINCT, sometimes all at once.

when it has to sort first

switch off hash joins and nested loops, and a join with no useful index gets two Sorts:

sqldb=shop
SET enable_hashjoin = off;
SET enable_nestloop = off;
 
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT p.name, oi.qty
FROM order_items AS oi JOIN products AS p ON p.id = oi.product_id;
output, from postgres 18.6
#1 · SET
#2 · SET
#3 · EXPLAIN
Merge Join (actual rows=24942.00 loops=1) Merge Cond: (oi.product_id = p.id) Buffers: shared read=164 -> Sort (actual rows=24942.00 loops=1) Sort Key: oi.product_id Sort Method: quicksort Memory: 1097kB Buffers: shared read=159 -> Seq Scan on order_items oi (actual rows=24942.00 loops=1) Buffers: shared read=159 -> Sort (actual rows=199.00 loops=1) Sort Key: p.id Sort Method: quicksort Memory: 24kB Buffers: shared read=5 -> Seq Scan on products p (actual rows=200.00 loops=1) Buffers: shared read=5 Planning: Buffers: shared hit=165 read=9

both Sorts are blocking (the iterator model), so this plan can't return a row until all 24,942 order lines are sorted. and look at the products side: its scan read 200 rows, and its Sort handed over 199. product 200 is the left-handed teapot, which nobody has ever ordered: once the order lines ran out, the merge stopped, and nobody asked for the last product. a merge join is done when either side is.

quick check
what does a merge join need from its join condition?

duplicates, rewinds, and Materialize

if both sides have the same key more than once, every outer row with that key has to meet every inner row with it. so when the outer cursor moves to the next row with the same key, the inner cursor has to go back to the start of the run. postgres calls it mark and restore: the inner side marks where a run of equal keys starts, and restores to the mark for each duplicate on the outer side.

an extreme case: orders joined to itself on customer_id. every customer's orders meet each other, so a customer with 57 orders produces 57 × 57 rows.

inner side =
query.sql
  1. 1SET enable_hashjoin = off;
  2. 2SET enable_nestloop = off;
  3. 3EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
  4. 4SELECT a.id, b.id FROM orders AS a JOIN orders AS b ON a.customer_id = b.customer_id;
what postgres printed
  1. Merge Join (actual rows=75398.00 loops=1)
  2. Merge Cond: (a.customer_id = b.customer_id)
  3. Buffers: shared hit=166
  4. -> Sort (actual rows=10000.00 loops=1)
  5. Sort Key: a.customer_id
  6. Sort Method: quicksort Memory: 491kB
  7. Buffers: shared hit=83
  8. -> Seq Scan on orders a (actual rows=10000.00 loops=1)
  9. Buffers: shared hit=83
  10. -> Sort (actual rows=75398.00 loops=1)
  11. Sort Key: b.customer_id
  12. Sort Method: quicksort Memory: 491kB
  13. Buffers: shared hit=83
  14. -> Seq Scan on orders b (actual rows=10000.00 loops=1)
  15. Buffers: shared hit=83

orders joined to itself on customer_id, merge forced. the inner Sort hands over more rows than it holds: every run of duplicate keys is read again.

real output, postgres 18.6 (PGlite 0.5.12) · merge-join
the self-join, with hash joins and nested loops switched off. with Sorts on both sides, the inner Sort hands over 75,398 rows from the 10,000 it holds: every rewind replays rows from its sorted output. over the index, a Materialize keeps the current run in memory, so a rewind doesn't fetch the rows again.

a Sort can restore to a mark by itself: it has its whole sorted output in memory (or on disk). an index scan can too, but restoring means walking the index and fetching the rows again. so the planner may put a Materialize on top: a node that remembers what passed through it, and replays it on request. Storage: Memory Maximum Storage: 20kB pg 18+ says it never needed more than one run's worth at a time. the same node shows up under a nested loop's inner side, holding a scan's result so that 10,000 rescans cost nothing (nested loop joins).

keylines

  • two inputs sorted on the key, two cursors, always advance the smaller one.
  • an index can supply the order for free; otherwise a Sort pays for it up front.
  • equal keys on both sides mean rewinds: the inner side restores to a mark.
  • Materialize keeps rows in memory so a rewind or rescan doesn't redo the work below it.
  • sorted order is a resource: one sort can serve a merge join and an ORDER BY at once.