> [!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; > ``` > > ![Sort Plan Tree](assets/plan_tree_op_sort.svg) > > ```text > Sort (cost=838.39..863.39 rows=10000 width=27) (actual time=0.756..1.030 rows=10000 loops=1) > Output: id, name, species_id, created_at > Sort Key: animals.created_at > Sort Method: quicksort Memory: 853kB > Buffers: shared hit=77 > -> Seq Scan on public.animals (cost=0.00..174.00 rows=10000 width=27) (actual time=0.003..0.340 rows=10000 loops=1) > Output: id, name, species_id, created_at > Buffers: shared hit=74 > Planning: > Buffers: shared hit=93 > Planning Time: 0.185 ms > Execution Time: 1.309 ms > ``` > > ![Sort measured plan performance signature](assets/trace_op_sort.svg) > > <table> > <tr> > <td rowspan="2" 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>Cost</b></td><td><code>sorting cost * number of rows</code></td></tr> > </table>