> **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;
> ```
>
> 
>
> <!-- literal-explain-plan
> Captured EXPLAIN provenance for the adjacent reader-facing visual plan.
> Canonical capture metadata lives in scratch/actual_operation_plans.json.
>
> 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
> -->
>
>
> <!--
> Raw-capture provenance — separate run.
> SQL, setup, dataset, settings, and scope: artifacts/chapter4_capture_matrix.json.
> Target: PostgreSQL 18.x companion fixture. Cache state: uncontrolled.
> Boundary: pg_wait_tracer backend execution root; client states are included when the chart shows them.
> Fidelity: exact pg_wait_tracer export. Not the adjacent EXPLAIN run; compare state shape, not durations.
> -->
>
> 
>
> <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>