> **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;
> ```
>
> 
>
> <!-- literal-explain-plan
> Captured EXPLAIN provenance for the adjacent reader-facing visual plan.
> Canonical capture metadata lives in scratch/actual_operation_plans.json.
>
> 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
> -->
>
>
> <!--
> Raw-capture provenance — separate run.
> SQL, setup, dataset, settings, and scope: artifacts/chapter4_capture_matrix.json.
> Target: PostgreSQL 18.x companion fixture. Cache state: uncontrolled.
> Boundary: pg_wait_tracer backend execution root; client states are included when the chart shows them.
> Fidelity: exact pg_wait_tracer export. Not the adjacent EXPLAIN run; compare state shape, not durations.
> -->
>
> 
>
> <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>