Plan nodes · Joins
Nested Loop
For each row of the outer input, scans the inner input.
The simplest join: for each row from the first child, run the second child and keep the pairs that match. It is fast when the outer side is small and the inner side is an index lookup parameterized by the outer row. It is the only join that works for any condition, including non-equality ones.
What to look for
A Nested Loop whose outer side was estimated at a few rows but produced thousands is a common cause of slow queries: look for an underestimate below it.
Example
SET enable_hashjoin = off; SET enable_mergejoin = off; SELECT t.name, a.name FROM tracks t JOIN artists a ON a.id = t.id % 100 + 1 WHERE t.id < 5000
3 nodes
- Nested Looprows 4,999 (estimated 5,159) cost 0.57..1834.17 buffers: 10,062 hit
- Index Scan using tracks_pkey on tracks trows 4,999 (estimated 5,159) cost 0.29..202.57 buffers: 63 hitindex condition
(id < 5000)1 index searches - Index Scan using artists_pkey on artists arows 1 × 4,999 loops (estimated 1) cost 0.28..0.32 buffers: 9,999 hitindex condition
(id = ((t.id % 100) + 1))4,999 index searches
Run with EXPLAIN (ANALYZE, BUFFERS, TIMING OFF, SUMMARY OFF) on the sample database, PostgreSQL 19.0. Open it in the EXPLAIN visualizer →
Related
Hash Join · Hash · Merge Join · Memoize · Materialize