> [!NOTE] Nested Loop > <table> > <tr> > <td width="25%"><img src="assets/ex_nestedloop.png"></td> > <td>The most basic join algorithm. For every row processed in the 'outer' relation, the engine performs a lookup in the 'inner' relation. Extremely efficient when the outer set is small and the inner relation has a supporting index to avoid repeated full scans.</td> > </tr> > </table> > > ```sql > -- Joining with a highly selective filter on one side > EXPLAIN (ANALYZE, COSTS, BUFFERS, VERBOSE) > SELECT * FROM animals a > JOIN species s ON a.species_id = s.id > WHERE s.id = 1; > ``` > > ![NestedLoop Plan Tree](assets/plan_tree_op_nested_loop.svg) > > ```text > Nested Loop (cost=27.79..147.85 rows=2000 width=42) (actual time=0.035..0.296 rows=2000 loops=1) > Output: a.id, a.name, a.species_id, a.created_at, s.id, s.name, s.diet_type > Buffers: shared hit=78 > -> Seq Scan on public.species s (cost=0.00..1.06 rows=1 width=15) (actual time=0.003..0.004 rows=1 loops=1) > Output: s.id, s.name, s.diet_type > Filter: (s.id = 1) > Rows Removed by Filter: 4 > Buffers: shared hit=1 > -> Bitmap Heap Scan on public.animals a (cost=27.79..126.78 rows=2000 width=27) (actual time=0.031..0.197 rows=2000 loops=1) > Output: a.id, a.name, a.species_id, a.created_at > Recheck Cond: (a.species_id = 1) > Heap Blocks: exact=74 > Buffers: shared hit=77 > -> Bitmap Index Scan on idx_animals_species_id (cost=0.00..27.29 rows=2000 width=0) (actual time=0.023..0.023 rows=2000 loops=1) > Index Cond: (a.species_id = 1) > Buffers: shared hit=3 > Planning: > Buffers: shared hit=170 > Planning Time: 0.303 ms > Execution Time: 0.360 ms > ``` > > ![Nested Loop measured plan performance signature](assets/trace_op_nested_loop.svg) > > <table> > <tr> > <td rowspan="2" width="25%"><img src="assets/ex_nested.svg"></td> > <td><b>Performance</b></td><td>High performance when the inner relation has a supporting index and the outer relation is small.</td> > </tr> > <tr><td><b>Cost</b></td><td><code>outer cost + inner cost * rows in outer</code></td></tr> > </table>