> [!NOTE] Sort
> <table>
> <tr>
> <td width="25%"><img src="assets/ex_sort.png"></td>
> <td>A resource-intensive operation that orders the result set. If the dataset exceeds <code>work_mem</code>, the engine will spill the sort to disk (external merge sort), which is significantly slower due to I/O overhead. Often used as a precursor to Merge Joins or Unique operations.</td>
> </tr>
> </table>
>
> ```sql
> -- Sorting the animals table by a non-indexed column
> EXPLAIN (ANALYZE, COSTS, BUFFERS, VERBOSE)
> SELECT * FROM animals ORDER BY created_at;
> ```
>
> ```text
> Sort (cost=1776.77..1826.77 rows=20000 width=27) (actual time=2.721..3.401 rows=20000 loops=1)
> Output: id, name, species_id, created_at
> Sort Key: animals.created_at
> Sort Method: quicksort Memory: 1862kB
> Buffers: shared hit=151
> -> Seq Scan on public.animals (...)
> ```
>
> <table>
> <tr>
> <td rowspan="5" width="25%"><img src="assets/ex_sort.svg"></td>
> <td><b>Performance</b></td><td>CPU and memory intensive; may spill to disk (external sort) if the dataset exceeds <code>work_mem</code>.</td>
> </tr>
> <tr><td><b>Factors</b></td><td>Dataset size, available <code>work_mem</code>, and the complexity of the sort key.</td></tr>
> <tr><td><b>Cost</b></td><td><code>sorting cost * number of rows</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/IO/BufFile/BufFileRead">IO: BufFileRead</a>, <a href="Workloads/IO/BufFile/BufFileWrite">IO: BufFileWrite</a>, <a href="Workloads/LWLock/Buffers/BufferContent">LWLock: BufferContent</a></td></tr>
> <tr><td colspan="3"><b>Description</b>: Sorts rows.</td></tr>
> </table>