Nested loop joins: excellent for ten rows, disastrous for a million
A nested loop join takes one row from its outer input and, for that row, finds the matching rows in its inner input. It repeats for every outer row. The algorithm is simple and needs no memory for a hash table or a sort, which makes it the cheapest join when the outer side is tiny and the inner side has an index on the join key.
The cost model multiplies: outer rows times the cost of one inner pass. Ten outer rows and an inner index lookup of 0.1 ms is 1 ms. A million outer rows with the same lookup is 100 seconds. The same node type spans both extremes, which is why a nested loop in a plan is not good or bad by itself. The row counts and loops decide.
| Situation | Nested loop behaviour | Verdict |
|---|---|---|
| 10 outer rows, indexed inner | 10 lookups, a few pages each | Excellent |
| 1,000 outer rows, indexed inner | 1,000 lookups, still fast | Good |
| 1,000 outer rows, sequential inner | 1,000 full scans | Usually bad |
| 1,000,000 outer rows | 1,000,000 passes | Bad unless the inner is trivial |
| LIMIT 10 with an ordered outer | Stops after 10 rows | Excellent |
Reading the loops
In EXPLAIN ANALYZE the inner node reports its actual time and rows per loop. A line that says actual time=0.010..4.190 rows=1 loops=1000 means each pass took about 4.19 ms and returned one row, for roughly 4.19 seconds in total. The parent nested loop's total time will be close to that, and the outer node may look almost free. The analyzer multiplies before subtracting, so the inner scan's self time reflects the full 4.19 seconds.
If the inner side is a sequential scan, every pass reads the whole table. That is the classic missing-index plan: the join condition is applied as a filter after the scan, with rows removed. An index on the inner join column turns each pass into a lookup and usually reduces the total from seconds to milliseconds. If the outer side is large and the inner is selective, a hash join may be better still.
Materialise and memoise
When the inner side is expensive but produces few distinct results, PostgreSQL can insert a Materialize node above it. The first pass computes the rows and later passes read them from a tuplestore in memory, avoiding repeated scans. Materialize is a sign that the inner side is not indexed but the planner still wants a nested loop, often for a small outer set.
Memoize, added in PostgreSQL 14, caches the result of an inner index lookup keyed by the outer value. It helps when the outer side has many duplicate keys, so the same lookup repeats. A high number of hits in the Memoize node means the cache is doing its job; a low hit rate means the outer keys are mostly distinct and the cache is overhead.
When the planner chooses it
The planner picks a nested loop when the estimated outer row count is small, when the inner side has a cheap index path, or when the query has a LIMIT and the join can stop early. It also uses nested loops for joins that are not equality joins, because hash and merge joins need an equality condition. A lateral join or a correlated subquery often becomes a nested loop for the same reason.
The choice can be wrong when the outer estimate is too low. A scan estimated at 10 rows that returns 100,000 turns a cheap loop into a disaster, and the plan above it was built for the wrong size. That is why the actual-to-estimate ratio on the outer node is worth checking before blaming the join algorithm itself.
Fixing a slow nested loop
- Check the loops on the inner node and multiply the time; the total may be far larger than the line suggests.
- Check whether the inner side is a sequential scan and whether an index exists on the join column.
- Check the outer estimate against actual rows; a large error may explain the choice.
- If the outer side is large and the join is equality, compare with a hash join by testing the plan.
- If the inner side repeats, consider a materialised CTE or a memoise-friendly index.
- Measure again after each change; the planner may switch algorithms entirely.
The analyzer flags a nested loop whose inner side runs more than 500 times, and flags a sequential scan used as the inner side of a nested loop. Both are heuristics: a thousand loops over a tiny lookup table can be fine, and a sequential inner scan over ten rows is harmless. Read the row counts and the total time before acting.
For a nested loop, multiply before you judge. The printed inner time is one pass, not the total.
Sources
- PostgreSQL documentation — Planner and optimizer
- PostgreSQL documentation — enable_nestloop
- MySQL documentation — Nested-loop joins
Questions
Why does the inner side show loops=1000?
The nested loop executes the inner side once per outer row. If the outer side produced 1,000 rows, the inner node ran 1,000 times. Its actual time and rows are per loop, so the total work is the printed value multiplied by 1,000.
When is a nested loop the best join?
When the outer side is small and the inner side can be reached through an index, so each pass costs a few page reads. It is also the only join that can return the first rows quickly, which matters for LIMIT queries and for nested loops under a merge or hash join.
Can a nested loop use work_mem?
Not for the join itself. A nested loop does not build a hash table or sort both sides, so it has no work_mem allowance. It can still benefit from a materialise node that caches the inner result, or from a memoize node that caches repeated inner lookups.
Load the nested-loop sample: the inner scan reports one row per loop and a thousand loops.
Open the analyzerWritten against the PostgreSQL and MySQL documentation and the standard cost model; every plan in the examples can be pasted into the analyzer linked above.
Back to the guides