### Sort ![[assets/ex_sort.png|256]] ### The Explain Trace ```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 (...) ``` --- - **Description**: Sorts rows. - **Performance**: CPU and memory intensive; may spill to disk (external sort) if the dataset exceeds `work_mem`. - **Factors**: Dataset size, available `work_mem`, and the complexity of the sort key. - **Cost**: `sorting cost * number of rows` ![[assets/ex_sort.svg|256]] - **Operates on**: [[Structures/Result Set]] - **Workloads**: - [[Workloads/IO/BufFile/BufFileRead|IO: BufFileRead]] - [[Workloads/IO/BufFile/BufFileWrite|IO: BufFileWrite]] - [[Workloads/LWLock/Buffers/BufferContent|LWLock: BufferContent]]