> **Unique**
> <table>
> <tr>
> <td width="25%"><img src="assets/ex_unique.png"></td>
> <td>Filters out duplicate rows from a sorted input stream. It is the primary engine behind the <code>DISTINCT</code> clause when the input is pre-sorted or when a Hash Aggregate is not preferred. It only needs to keep track of the last seen row to detect duplicates.</td>
> </tr>
> </table>
>
> ```sql
> -- Performing a DISTINCT on a sorted index
> SET enable_hashagg = off;
>
> EXPLAIN (ANALYZE, COSTS, BUFFERS, VERBOSE)
> SELECT DISTINCT species_id
> FROM animals
> ORDER BY species_id;
> ```
>
> 
>
> <!-- literal-explain-plan
> Captured EXPLAIN provenance for the adjacent reader-facing visual plan.
> Canonical capture metadata lives in scratch/actual_operation_plans.json.
>
> Unique (cost=0.29..223.28 rows=5 width=4) (actual time=0.023..0.465 rows=5 loops=1)
> Output: species_id
> Buffers: shared hit=12
> -> Index Only Scan using idx_animals_species_id on public.animals (cost=0.29..198.28 rows=10000 width=4) (actual time=0.023..0.262 rows=10000 loops=1)
> Output: species_id
> Heap Fetches: 0
> Buffers: shared hit=12
> Planning:
> Buffers: shared hit=74
> Planning Time: 0.155 ms
> Execution Time: 0.485 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_unique.svg"></td>
> <td><b>Performance</b></td><td>High performance if the input is already sorted; removes duplicates in a single pass.</td>
> </tr>
> <tr><td><b>Cost</b></td><td><code>`cpu_tuple_cost * number of tuples`</code></td></tr>
> </table>