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.
| id | customer_id | |
|---|---|---|
| before first | ||
| 1 | 1 | |
| 12 | 4 | |
| 47 | 1 | |
| 92 | 5 | |
| 511 | 3 | |
| 529 | 2 | |
| 566 | 2 | |
| 1596 | 6 | |
| id | name | |
|---|---|---|
| before first | ||
| 1 | Maya Chen | |
| 2 | Grace Okafor | |
| 3 | Sam Lee | |
| 4 | Zoë Martin | |
| 5 | Zoe Martin | |
| id | customer_id | customers.id | name |
|---|
scanfor each orders row, scan all of customers. no index, no memory, just two loops.
when the index already did the sorting
orders and their items, in order:
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;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.
-- 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:
- 1EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
- 2SELECT c.id, c.name, o.id
- 3FROM customers AS c JOIN orders AS o ON o.customer_id = c.id
- 4ORDER BY c.id
- Sort (actual rows=10000.00 loops=1)
- Sort Key: c.id
- Sort Method: quicksort Memory: 648kB
- Buffers: shared hit=84 read=23
- -> Hash Join (actual rows=10000.00 loops=1)
- Hash Cond: (o.customer_id = c.id)
- Buffers: shared hit=84 read=23
- -> Seq Scan on orders o (actual rows=10000.00 loops=1)
- Buffers: shared hit=83
- -> Hash (actual rows=2000.00 loops=1)
- Buckets: 2048 Batches: 1 Memory Usage: 87kB
- Buffers: shared hit=1 read=23
- -> Seq Scan on customers c (actual rows=2000.00 loops=1)
- 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.
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:
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;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.
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.
- 1SET enable_hashjoin = off;
- 2SET enable_nestloop = off;
- 3EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
- 4SELECT a.id, b.id FROM orders AS a JOIN orders AS b ON a.customer_id = b.customer_id;
- Merge Join (actual rows=75398.00 loops=1)
- Merge Cond: (a.customer_id = b.customer_id)
- Buffers: shared hit=166
- -> Sort (actual rows=10000.00 loops=1)
- Sort Key: a.customer_id
- Sort Method: quicksort Memory: 491kB
- Buffers: shared hit=83
- -> Seq Scan on orders a (actual rows=10000.00 loops=1)
- Buffers: shared hit=83
- -> Sort (actual rows=75398.00 loops=1)
- Sort Key: b.customer_id
- Sort Method: quicksort Memory: 491kB
- Buffers: shared hit=83
- -> Seq Scan on orders b (actual rows=10000.00 loops=1)
- 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.
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.