> [!NOTE] 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; > ``` > > ![Unique Plan Tree](assets/plan_tree_op_unique.svg) > > ```text > 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 > ``` > > ![Unique measured plan performance signature](assets/trace_op_unique.svg) > > <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>