man duckdb/top-n

ORDER BY ... LIMIT in DuckDB: the TOP_N operator

lib / DuckDB 9 mindraft

checked against: DuckDB 2.0.1

ORDER BY x DESC LIMIT 3 asks for three rows. Does the database sort the whole table to find them? In DuckDB the answer is usually no, and the plan says so with an operator called Top N. This article reads the DuckDB 2.0.1 source (tag v2.0.1) and tests it with the duckdb 2.0.1 CLI on an Apple M2 Pro with 12 cores, on a table visits of 10 million rows in big.duckdb and one of 100,000 rows in art.duckdb:

CREATE TABLE visits AS
SELECT ((i * 7919 % 100003) * (i * 104729 % 99991) % 5000000)::INTEGER AS user_id
FROM range(1, 10000001) t(i);
-- art.duckdb: % 50000 and range(1, 100001)

The plan

$ duckdb big.duckdb -c "EXPLAIN ANALYZE SELECT user_id FROM visits ORDER BY user_id DESC LIMIT 3;"
╭─ Summary ───────────╮
│ Total Time: 0.0049s │
│ Data Read:   2.8 MB │
╰─────────────────────╯
╭─ Top N ────────────────────────────╮
│ Top: 3                             │
│ Order By: user_id DESC             │
│ 3 rows                         0µs │
╰──────────────────┒┎────────────────╯
╭─ Table Scan ─────┚┖────────────────╮
│ Table: big.main.visits             │
│ Type: Sequential Scan              │
│ Projections: user_id               │
│ Filters:                           │
│ optional: Dynamic Filter (user_id) │
│ Row Groups Scanned: 6 / 82         │
│ 737,280 rows                10.0ms │
╰────────────────────────────────────╯

There is no Order By and no Limit, just Top N. And the scan read 6 of the table’s 82 row groups, 737,280 rows out of 10 million, because of a filter nobody wrote. Both come from Top N.

From ORDER BY + LIMIT to Top N

The planner produces a LIMIT above an ORDER BY. The top_n optimizer (topn_optimizer.cpp) merges the two when the limit is a constant and the offset is a constant or absent, with one more condition:

// if the limit is > 0.7% of the child cardinality, sorting the whole table is faster
bool limit_is_large = constant_limit > 5000;
if (constant_limit > child_card * 0.007 && limit_is_large) {
    return false;
}

So a limit of up to 5,000 rows always becomes Top N. A bigger one does only while it is at most 0.7% of the estimated input. The boundary is exact:

$ for n in 5000 5001; do duckdb art.duckdb -c "EXPLAIN SELECT user_id FROM visits
    ORDER BY user_id DESC LIMIT $n;" | grep -oE '─ [A-Z][A-Za-z ]+[a-z] ─' | tr '\n' ' '; echo; done
─ Top N ─ ─ Seq Scan ─
─ Limit ─ ─ Projection ─ ─ Order By ─ ─ Projection ─ ─ Seq Scan ─
$ for n in 69000 71000; do duckdb big.duckdb -c "EXPLAIN ..." ...; done
─ Top N ─ ─ Seq Scan ─
─ Streaming Limit ─ ─ Order By ─ ─ Seq Scan ─

On 100,000 rows, LIMIT 5001 sorts. On 10 million, the switch comes between 69,000 and 71,000, around 0.7% of 10 million. The full sort behind Order By is different code. In sorted_run.cpp, TemplatedSort() sorts the keys of a run with vergesort and passes ska_sort, a radix sort, as its fallback.

A heap of sort keys

physical_top_n.cpp keeps a TopNHeap per thread. An entry is two fields:

struct TopNEntry {
	string_t sort_key;
	idx_t index;

	bool operator<(const TopNEntry &other) const {
		return sort_key < other.sort_key;
	}
};

The sort key is the ORDER BY columns encoded into one byte string by CreateSortKey(), with DESC and NULLS FIRST/LAST folded into the encoding, so comparing two rows on any number of columns is one string comparison. index points at the row’s other columns in a payload chunk.

The heap is std::push_heap and std::pop_heap over a vector, ordered so that the front is the worst row kept, the one that would be dropped next. Two functions do the work:

EntryShouldBeAdded(key):
    heap not full                  -> yes
    key < heap.front().sort_key    -> yes   (better than the worst kept)
    otherwise                      -> no

AddEntryToHeap(entry):
    if full: pop_heap, pop_back    (drop the worst)
    push_back, push_heap

The heap’s size is limit + offset, so LIMIT 3 OFFSET 1000 keeps 1,003 rows. For a chunk of 2,048 rows, the operator first computes all 2,048 sort keys, then offers each to the heap. Heaps of up to 100 entries (SMALL_HEAP_THRESHOLD) take a cheaper path that copies a row’s payload only if it is still in the heap after the whole chunk. Dropped rows leave garbage in the payload chunk. Reduce(), called after each sink, compacts it once the chunk holds at least max(5 * 2048, 2 * heap_size) rows.

At the end, each thread’s heap goes into the global one through Combine(), which can stop at the first entry that doesn’t qualify because the other heap is sorted by then. Finalize() sorts the surviving entries with std::sort, and the scan reads them in order.

The comparison is strict, so a row equal to the worst kept row is not added. Among equal keys, the first one a heap sees wins, and with several threads “first” changes from run to run.

The threads share a boundary

A heap that is full knows a threshold: nothing worse than its front can make the result. TopNBoundaryValue shares it across threads. After each chunk, a full heap offers its front key with UpdateValue(), which keeps the best one offered. Before computing sort keys for a new chunk, each thread compares the chunk’s ORDER BY values with the boundary in a vectorised pass, CheckBoundaryValues(), and drops every row that can’t qualify. If none qualifies, the chunk is skipped.

The boundary reaches the scan

TopN::PushdownDynamicFilters() goes one step further. If the first ORDER BY term is a plain column of a numeric or VARCHAR type, it creates a DynamicFilterData and pushes a filter into the table scan: user_id > boundary for DESC with one ORDER BY term, >= with more terms, and the mirror images for ASC. The filter is marked not initialized until the first UpdateValue() sets it, and then it moves as the heap’s boundary improves. That is the optional: Dynamic Filter (user_id) in the plan. The word “optional” is meant literally. The wrapper’s function data is commented “always returns TRUE, used for statistics only”. The filter never removes a row by itself. The scan uses it against min/max statistics to skip data that can’t contain a qualifying value, and Top N does the exact filtering.

A second optimizer, the row group pruner (“Reorder and try to prune row groups in queries with LIMIT or simple aggregates”), orders row groups by the ORDER BY column’s statistics, so the most promising are read first, and drops the ones a LIMIT can’t reach. Disabling each optimizer in turn separates the effects:

$ duckdb big.duckdb -c "SET disabled_optimizers=...;" -c ".timer on" -c "SELECT user_id FROM visits ORDER BY user_id DESC LIMIT 3;"
disabledplanrow groups readrealuser
nothingTop N6 / 820.003 s0.006 s
top_nLimit, Order By6 / 820.008 s0.033 s
row_group_prunerTop N29 / 820.004 s0.020 s
top_n,row_group_prunerLimit, Order By82 / 820.056 s0.432 s

With both off, DuckDB sorts 10 million integers in 56 to 76 ms of wall time and 0.42 to 0.44 s of CPU over three runs. With both on, it reads 7% of the table and keeps three rows. With only the dynamic filter, the number of row groups skipped depends on how fast the boundary rises while 12 threads race through the table: 29 here, 30 in an earlier run.

The same idea without LIMIT: QUALIFY

The per-group top N is the other common form:

CREATE TABLE scores AS
SELECT (i % 1000)::INTEGER AS player, hash(i) % 1000000 AS score
FROM range(10000000) t(i);

SELECT player, score FROM scores
QUALIFY row_number() OVER (PARTITION BY player ORDER BY score DESC) <= 3;

A window function with ORDER BY sorts each partition. DuckDB 2.0.1 doesn’t run one here:

$ duckdb big.duckdb -c "EXPLAIN SELECT player, score FROM scores
    QUALIFY row_number() OVER (PARTITION BY player ORDER BY score DESC) <= 3;"
╭─ Projection ───────────────────╮
│ Projections: #0, #2            │
╰────────────────┬───────────────╯
╭─ Unnest ───────┴───────────────╮
╰────────────────┬───────────────╯
╭─ Perfect Hash Group By ────────╮
│ Groups: #0                     │
│ Aggregates:                    │
│ arg_max_nulls_last(#1, #2, #3) │
╰────────────────┬───────────────╯
╭─ Projection ───┴───────────────╮
│ Projections: player, score,    │
│              score, 3          │
╰────────────────┬───────────────╯
╭─ Seq Scan ─────┴───────────────╮

(Estimated row counts trimmed.) The top_n_window_elimination optimizer turned the window and its filter into a GROUP BY player with arg_max_nulls_last(score, score, 3), which returns a list of the top three per player, and an Unnest that turns the lists back into rows. The aggregate behind it is a BinaryAggregateHeap, the same push_heap/pop_heap idea with a capacity of 3, one per group.

TopNWindowElimination::CanOptimize() lists what it accepts: a filter on row_number() with <= (at least 1), < (at least 2), or = 1; a constant below 1,000,000, the limit of the n argument; one ORDER BY key, NULLS LAST; partitions that are plain columns. Anything else keeps the window. On these 10 million rows:

$ duckdb big.duckdb -c ".timer on" -c "SELECT count(*), sum(score) FROM (<the QUALIFY query>);"
Run Time (s): real 0.037 user 0.376087 sys 0.012630
$ duckdb big.duckdb -c "SET disabled_optimizers='top_n_window_elimination';" -c ".timer on" -c "..."
Run Time (s): real 0.139 user 1.419883 sys 0.068936

Both return 3,000 rows with the same sum. The rewrite is 3.7 times faster.

Curious facts

  • LIMIT 5000 becomes Top N on any table, LIMIT 5001 only on tables of more than about 714,000 estimated rows.
  • With a single ORDER BY term the pushed filter is strict (> for DESC); with two or more it is >=, because rows equal on the first term can still win on the second.
  • = 1 is the only equality the window rewrite takes, marked in the source with “TODO: Handle other values”.
  • LIMIT 0 makes the heap’s capacity zero, and Sink returns before computing a single sort key.
  • Under NULLS FIRST, the pushed filter becomes x IS NULL OR x > boundary, so NULL rows aren’t filtered out of a result they belong in.

History

  • physical_top_n.cpp exists in the v0.1.9 tag.
  • At v1.1.0 the operator kept its rows in a sort state (LocalSortState in the source, no push_heap). At v1.2.0 (2025-02-05) it calls std::push_heap and has a dynamic_filter.
  • 1.4.0 (2025-09-16): the release notes describe a sorting rework using “a k-way merge sort to reduce data movement”, the sort behind Order By.
  • topn_window_elimination.cpp is absent from the v1.4.0 tag and present in v1.5.0 (2026-03-09).

Sources

ls duckdb/