Video in progress
When does the planner choose Nested Loop, Hash Join or Merge Join?
How it works / When it's good — Nested Loop: for each outer row, searches the inner side / tens of rows on the outer side, an index on the inner; Hash Join: builds an in-memory hash table from the smaller side, scans the larger / both sides large, only an = condition; Merge Join: walks two sorted streams in parallel /…
📖 Answer
| Algorithm | How it works | When it's good |
|---|---|---|
| Nested Loop | for each outer row, searches the inner side | tens of rows on the outer side, an index on the inner |
| Hash Join | builds an in-memory hash table from the smaller side, scans the larger | both sides large, only an = condition |
| Merge Join | walks two sorted streams in parallel | the order is ready, or the result is needed in order |
Nested loop is the only option for non-equality conditions like >/<. Hash join depends on memory: if the hash table is larger than work_mem × hash_mem_multiplier, it's split into batches and spilled to disk. If you see Batches: 8 in EXPLAIN ANALYZE, memory wasn't enough.
The most common problem on prod isn't the algorithm, it's the estimate. The planner expects 10 rows, picks a nested loop, and 500 thousand arrive. When that happens, I:
- try
ANALYZE table; - add
CREATE STATISTICSif there are correlated columns; - for a test, run
SET enable_nestloop = offin the session and measure how fast the other plan is.
The third is for diagnostics only. Turning off enable_* flags globally on prod means breaking hundreds of other queries.
Sign up to mark studied questions and save your progress.