When it applies
- The query has an
ORDER BYplus aLIMIT(orFETCH FIRST n ROWS), so the DBMS knows it does not need a globally sorted result — only the n greatest or smallest values10:18. - Worked example:
SELECT ... FROM enrolled ORDER BY sid ASC FETCH FIRST 4 ROWS WITH TIES—WITH TIESdecides whether tied records are included10:43.
The algorithm
- Allocate a small sorted heap / priority queue sized to the limit
11:07. - Scan the source data once. For each value:
- With
WITH TIES, the heap is allowed to grow slightly past n, and the system must track how far past n it has gone11:5912:36.
Trace from the lecture on input 3, 4, 6, 2, 9, 1, 4, 4, 8 with a 4-slot heap: 3 → 4 → 6 → 2 shifts in; 9 is skipped because it exceeds the heap max; 1 evicts 6; the duplicate 4s are appended as ties; 8 is skipped; done 11:07 11:49 11:59 12:36.
Why it wins
- One pass over the data, and nothing is actually sorted — no quicksort pivots, no partitioning
12:50. - One pass is "always going to be a huge win"; the caveat is petabyte-scale input where even one pass is expensive
12:5013:17. - Memory footprint is tiny: roughly one buffer-pool frame for the scan (with prefetching possible) plus one buffer for the heap
13:42.