> [!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; > ``` > > ```text > Unique (cost=1.29..438.29 rows=5 width=4) (actual time=1.009..1.879 rows=5 loops=1) > Output: species_id > Buffers: shared hit=22 > -> Index Only Scan using idx_animals_species_id on public.animals (...) > ``` > > <table> > <tr> > <td rowspan="5" 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>Factors</b></td><td>Dataset size and the cost of the child sort/index scan node.</td></tr> > <tr><td><b>Cost</b></td><td><code>`cpu_tuple_cost * number of tuples`</code></td></tr> > <tr><td><b>Operates on</b></td><td><a href="Structures/Result Set">Result Set</a></td></tr> > <tr><td><b>Workloads</b></td><td><a href="Workloads/LWLock/Buffers/BufferContent">LWLock: BufferContent</a></td></tr> > <tr><td colspan="3"><b>Description</b>: Removes duplicate rows from the result set.</td></tr> > </table>