Sub topic 6
Nested loop, hash and merge joins
This chapter assumes you can read a plan as a tree of nodes, know what the cost and row estimates mean, and can tell scan node types apart. Here you learn the three algorithms PostgreSQL uses to combine two inputs, how each looks in EXPLAIN output, and why the planner picks one over another.
What a join node does
A join node has exactly two children. The first child is the outer input and the second is the inner input. The planner chooses the algorithm and the order of the inputs from its row estimates and cost model. You never write the algorithm in SQL. You read it from the node name:
| Node name | Needs | Typical strength |
|---|---|---|
| Nested Loop | Nothing. It handles any join condition. | Few outer rows, fast lookup on the inner side |
| Hash Join | An equality condition such as `a.x = b.y` | Large unsorted inputs |
| Merge Join | An equality condition and inputs sorted on the join key | Inputs already sorted, or very large inputs |
For outer, semi and anti joins the node name carries the join type, for example Hash Left Join, Hash Semi Join or Merge Anti Join. The algorithm is the same.
Nested loop
A nested loop reads one row from the outer input, then searches the inner input for matching rows. It repeats this for every outer row.
EXPLAIN (ANALYZE)
SELECT c.name, o.id
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE c.id = 42;Nested Loop (cost=0.57..16.64 rows=3 width=36) (actual time=0.040..0.052 rows=3 loops=1)
-> Index Scan using customers_pkey on customers c (cost=0.28..8.30 rows=1 width=32) (actual time=0.015..0.016 rows=1 loops=1)
Index Cond: (id = 42)
-> Index Scan using orders_customer_id_idx on orders o (cost=0.29..8.31 rows=3 width=8) (actual time=0.020..0.028 rows=3 loops=1)
Index Cond: (customer_id = 42)The outer side returns one row, so the inner index scan runs once (loops=1). That is the ideal case.
When the outer side returns many rows, the inner scan runs once per row. Then loops on the inner node equals the number of outer rows. Two rules follow from this:
actual timeandrowson a node are per loop averages. Multiply byloopsto get the node's total time and total rows.- The inner side is only cheap if it can use an index on the join column. Without one, each loop is a full scan, and the cost grows as outer rows times inner rows.
The planner also chooses a nested loop for non-equality conditions such as a.ts BETWEEN b.start_ts AND b.end_ts. Hash and merge joins cannot evaluate those as the join condition.
flowchart TDHash join
A hash join reads the entire inner input once and builds an in-memory hash table keyed on the join column. It then scans the outer input once and probes the table for each row. The plan shows a separate Hash node as the second child.
EXPLAIN (ANALYZE)
SELECT c.name, o.id
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE o.created_at >= DATE '2026-01-01';Hash Join (cost=290.00..2150.40 rows=48000 width=36) (actual time=3.1..41.7 rows=47650 loops=1)
Hash Cond: (o.customer_id = c.id)
-> Seq Scan on orders o (cost=0.00..1650.00 rows=48000 width=8) (actual time=0.02..22.4 rows=47650 loops=1)
Filter: (created_at >= '2026-01-01'::date)
Rows Removed by Filter: 152350
-> Hash (cost=165.00..165.00 rows=10000 width=32) (actual time=3.0..3.0 rows=10000 loops=1)
Buckets: 16384 Batches: 1 Memory Usage: 723kB
-> Seq Scan on customers c (cost=0.00..165.00 rows=10000 width=32) (actual time=0.01..1.4 rows=10000 loops=1)Things to notice:
- The inner side (
customers) is hashed. The planner puts the smaller input there so the table fits in memory. - The join's startup cost is high, because no output can appear until the hash table is complete. The
Hashnode's total cost shows up in the join's startup cost. - Each input is read once, so the cost grows roughly with the sum of the input sizes, not their product.
Batches and spilling
The hash table must fit in work_mem (multiplied by hash_mem_multiplier in PostgreSQL 13 and later). If it does not, PostgreSQL splits both inputs into batches, writes the extra batches to temporary files, and processes them one at a time.
Buckets: 65536 Batches: 8 Memory Usage: 4096kBBatches: 1 means everything stayed in memory. A value above 1 means disk spill, which is slower. With EXPLAIN (ANALYZE, BUFFERS) you also see temp read and temp written counts on the node. A bad row estimate on the inner side is a common cause. The planner sizes the table for the rows it expects, and PostgreSQL may need extra batches when many more rows arrive.
Merge join
A merge join walks two inputs that are both sorted on the join key, advancing a pointer in each, much like merging two sorted lists. Each input is read once.
EXPLAIN (ANALYZE)
SELECT c.name, o.id
FROM customers c
JOIN orders o ON o.customer_id = c.id
ORDER BY c.id;Merge Join (cost=0.57..9120.00 rows=200000 width=36) (actual time=0.05..96.0 rows=200000 loops=1)
Merge Cond: (c.id = o.customer_id)
-> Index Scan using customers_pkey on customers c (cost=0.29..420.00 rows=10000 width=32) (actual time=0.02..3.5 rows=10000 loops=1)
-> Index Scan using orders_customer_id_idx on orders o (cost=0.42..7200.00 rows=200000 width=8) (actual time=0.02..55.0 rows=200000 loops=1)Here both inputs come out of indexes already in key order, so no sorting is needed. If an input is not sorted, the plan inserts a Sort node below the merge join, and the cost of that sort counts against the join. A merge join is attractive when:
- Both inputs are already sorted, for example from indexes.
- The query has an
ORDER BYon the join key, so the sorted output is useful beyond the join. - Both inputs are too large for a hash table to fit in memory.
Unlike a hash join, a merge join can start returning rows quickly, because it does not need to build anything first.
How the planner chooses
The planner estimates the cost of each algorithm for each join order and keeps the cheapest. These rules of thumb match its usual choices:
- A small outer input with an index on the inner join column leads to a nested loop.
- Large, unsorted inputs with an equality condition lead to a hash join.
- Inputs that are sorted already, or that must be sorted for the
ORDER BYanyway, lead to a merge join. - A non-equality join condition leads to a nested loop.
All of these depend on row estimates. If the planner thinks the outer side has 5 rows and it has 500,000, it will choose a nested loop and the inner side runs 500,000 times.
Spotting a bad join choice
Compare estimated and actual rows on the outer input, then look at loops on the inner node.
Nested Loop (cost=0.43..120.00 rows=5 width=40) (actual time=0.1..8400.0 rows=480000 loops=1)
-> Seq Scan on orders o (cost=0.00..35.00 rows=5 width=16) (actual time=0.0..60.0 rows=480000 loops=1)
Filter: (status = 'pending' AND region = 'eu')
-> Index Scan using customers_pkey on customers c (cost=0.29..16.80 rows=1 width=24) (actual time=0.01..0.01 rows=1 loops=480000)
Index Cond: (id = o.customer_id)The planner expected 5 outer rows and got 480,000. The inner scan is fast per loop (0.01 ms), but 480,000 loops add up to about 4.8 seconds. The fix is to correct the estimate, not to change the join. For correlated filter columns, extended statistics often help:
CREATE STATISTICS orders_status_region_stats (dependencies)
ON status, region FROM orders;
ANALYZE orders;After this, run the EXPLAIN again. The planner may now choose a hash join.
Testing alternatives
To see whether another algorithm would be faster, disable one for your session and compare. Use this only for diagnosis.
SET enable_nestloop = off;
EXPLAIN (ANALYZE)
SELECT c.name, o.id
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE o.status = 'pending' AND o.region = 'eu';
RESET enable_nestloop;These settings do not forbid the algorithm. They add a very large cost penalty, so the planner still uses it if there is no other way to run the join. If the alternative plan is faster, the real problem is usually a misestimate, a missing index or stale statistics.
Quick reference
| Symptom in the plan | Likely cause | First thing to try |
|---|---|---|
| Nested Loop, inner `loops` in the thousands or more | Outer rows underestimated | Check estimate vs actual, refresh or extend statistics |
| Nested Loop with a Seq Scan on the inner side | No usable index on the inner join column | Create an index on that column |
| Hash with `Batches` above 1 | Hash table larger than memory | Check the inner row estimate, then consider `work_mem` |
| Merge Join with a large Sort below it | Inputs not pre-sorted | Consider an index on the join key, or accept the sort |
Exercise
A plan shows Nested Loop (cost=0.43..95.00 rows=10 width=40) (actual time=0.1..5200.0 rows=300000 loops=1). Its inner child is an Index Scan with actual time=0.01..0.01 rows=1 loops=300000. About how much total time does the inner scan take, and what is the most likely root cause?
Show answer
The inner scan takes about 0.01 ms times 300,000 loops, which is about 3 seconds of the 5.2 seconds total. The root cause is most likely that the planner estimated 10 outer rows but the outer input returned about 300,000. That misestimate made a nested loop look cheap. Compare estimated and actual rows on the outer node, then refresh statistics or create extended statistics for correlated filter columns.
Exercise
In a hash join, which input is hashed, and what does Batches: 4 tell you?
Show answer
The inner input (the second child, under the Hash node) is hashed. Batches: 4 means the hash table did not fit in memory, so PostgreSQL split the join into four batches and spilled data to temporary files. Check the inner row estimate and consider whether a higher work_mem is appropriate.