Skip to content

[Performance]: ORDER BY never uses index order - full scan plus Sort even with LIMIT #31856

Open

Description

@Ariznawlll

Description

ORDER BY over an indexed column always degrades to a full-table Sort node — the planner never delivers rows in index order even when the ORDER BY column has a perfectly matching secondary index (including the covering-index case where all needed columns live in the index). This is a planner-layer miss, distinct from and orthogonal to the executor-layer DESC top-N defect (#31803): here the plan itself reads the whole table and sorts, where MySQL reads N rows from the index and stops.

Evidence on main c6683bd2f5 (2026-10-30), table px.f 200k rows, KEY ik(k) (500-cardinality int), plus a 500k-row confirmation table (perf.big, KEY i_amt):

query plan scan inputRows Sort node
SELECT k FROM px.f ORDER BY k LIMIT 10 (covering!) Table Scan 200,000 yes
SELECT amt FROM perf.big ORDER BY amt LIMIT 10 (500k) Table Scan 57,344 yes
SELECT id, amt FROM perf.big WHERE amt BETWEEN 100 AND 200 ORDER BY amt DESC LIMIT 10 Table Scan 106,496 yes
SELECT k FROM px.f WHERE k = 3 ORDER BY k LIMIT 10 (constant-redundant sort) Index Table Scan (equality) 400 still yes
SELECT k FROM px.f FORCE INDEX(ik) ORDER BY k LIMIT 10 Index Table Scan 260 still yes

The FORCE INDEX row is the smoking gun in both directions:

  1. The executor perfectly supports index-order delivery (inputRows collapses 200,000 → 260 the moment the index is forced) — the fast path exists end-to-end;
  2. The default planner never chooses it, and even when forced onto the index it still emits a Sort node — there is no "rows already arrive sorted by index → drop Sort" derivation in the rules at all, which also explains the constant-redundant-sort row.

Row amplification for the top-N shapes is 5,000-20,000× (10 rows wanted, 57k-200k read). Wall-clock hides most of it at these in-memory scalefolds (2-15ms), but the cost is real and scales: at billion-row size or in memory-constrained CN this is the gap between a sub-ms point-read and a multi-second scan, invisible in EXPLAIN-plan shape until one checks inputRows.

MySQL 8 behavior: all four query shapes pick the index and read only the top-N prefix; the Sort node never appears when the index provides the order.

Impact

  • "Latest N rows" (ORDER BY created_at LIMIT N — the single most common operational query shape) pays a full-table read + sort on every execution when the column is indexed but the planner doesn't know the index can serve the order.
  • Because the executor honors the index when forced, the entire fix is planner rules: (a) prefer index-scan for ORDER BY-prefix + LIMIT shapes, (b) drop the Sort node when the delivery order already satisfies it, (c) drop the constant-redundant sort on col = const ORDER BY col. Three rules, no storage work.

Expected behavior

ORDER BY on an indexed column (with or without LIMIT, with or without a range predicate on the same index) should be served by index-ordered scan without a Sort node, reading only LIMIT rows (+offset).

Reproduction

CREATE TABLE f(id INT PRIMARY KEY, k INT, v INT, s VARCHAR(20), KEY ik(k));  -- 200k rows
SELECT k FROM f ORDER BY k LIMIT 10;          -- Table Scan 200k + Sort on MO; index prefix-read on MySQL
SELECT k FROM f FORCE INDEX(ik) ORDER BY k LIMIT 10;  -- 260 rows — proves the executor path exists

main @ c6683bd, EXPLAIN ANALYZE inputRows shown for every row in the table above. Same session verified DISTINCT/group/UNION/anti-join shapes for completeness: those take other (correct) paths; the miss is specific to order-delivery.

Activity

  1. added theissue type on Oct 30, 2026
  2. Ariznawlll commented on Oct 30, 2026

    @Ariznawlll
    CollaboratorAuthor

    Scope widening with a stronger case from the same session: even the PRIMARY KEY's natural order is not delivered — the miss is not secondary-index-specific:

    query (same px.f 200k) plan inputRows Sort
    SELECT id FROM px.f ORDER BY id LIMIT 10 (PK ascending!) Table Scan 8,192 yes
    SELECT id FROM px.f ORDER BY id DESC LIMIT 10 Table Scan 5,000 yes

    A table-scan of a MO table should already yield PK order (or its reverse) for free with zero-sort delivery; instead the planner still emits a Sort over the first blocks. This puts the defect in the most basic path — not "planner refuses secondary-index order" but "planner has no concept of ordered delivery at all, not even for the storage layout's own ordering". The FORCE-INDEX evidence (260 rows when pushed) plus these PK rows suggest one shared root: the ORDER-BY satisfaction check against any ordered source (pk scan, index scan) is absent.

    Also noted for triage completeness, same matrix: constant-false predicates short-circuit perfectly (inputRows=0 — good), IS NULL scans minimal, large IN(2000) lists collapse to exact 200-row point reads (good), LIKE-prefix on a non-indexed column full-scans as expected (no defect).

  3. Ariznawlll commented on Oct 30, 2026

    @Ariznawlll
    CollaboratorAuthor

    Family member #3 from the ongoing matrix (500k table perf.big, KEY i_grp(grp), 10k distinct values): SELECT DISTINCT grp FROM perf.big LIMIT 5 reads all 500,000 rows (inputRows=500000, Table Scan) for a 5-row answer deliverable from the first ~2 index blocks. Same root as the ORDER BY rows — no ordered-delivery path, so DISTINCT cannot stream-subaggregate from index order either. All three shapes (ORDER BY+LIMIT, constant ORDER BY, DISTINCT+LIMIT) collapse to one planner capability: recognizing an index (or PK) can deliver rows in an order sufficient for the operator, then letting Aggregate/DISTINCT stream and Sort vanish. Grouping in one rule family for triage.

  4. Ariznawlll commented on Oct 30, 2026

    @Ariznawlll
    CollaboratorAuthor

    Related covering-index data point from today's matrix (main c6683bd2f5, 200k-row composite index ic2(k,k2) and plain ik(k), warm median of 2):

    shape time observation
    SELECT id, k, k2 FROM cov2 WHERE k < 10000 (index columns only → could be "covering") 342 ms inputRows 200,000
    same + note (non-index column) → needs base rows 334 ms —
    COUNT(*) cov2 WHERE k < 10000 33 ms —
    selective 1% WHERE k<10000 AND k2=25, index cols only 44 ms —
    same with note 39 ms —

    Two relevant notes for triage:

    1. Composite covering yields no wall-clock advantage over the back-table shape on the same rows — 2-column covering runs ~equal to the +note variant within a few ms in both full-range and 1%-selective cases. The "covering" lookup benefits that support database-style covering indexes are absent here; the executor reads the serialized index columns for both forms at nearly identical costs. (MO's physical model stores index as a separate serialized row table, so the covering-vs-not economic gap is structurally narrow, but the plan + scan should still skip touching the base-table blocks when a query needs only index columns — currently InputSize reads the same in both.)

    2. Positive control from the same session: small lookups (k = n) DO gain 25→1 inputBlocks via the index (95.9% IO reduction) and COUNT(k)/MIN(v)/MAX(v) are answered from metadata with inputBlocks=0. So the metadata fast-path exists and is strong — it just doesn't extend to range scans over composite keys in the query shapes above. These are planner executor gaps to fold into [Performance]: ORDER BY never uses index order - full scan plus Sort even with LIMIT #31856's planned rule-family (index-order delivery + ordered-scan covering).

  5. Ariznawlll commented on Nov 2, 2026

    @Ariznawlll
    CollaboratorAuthor

    Retest on main@HEAD (c6683bd, built 2026-11-02): partially fixed. SELECT * FROM t ORDER BY pk LIMIT 100 still shows a Sort node in EXPLAIN, but the early-stop path now works: LIMIT 100 = 0.6 ms vs full sort = 188.4 ms (314× gap, 100k-row table). The remaining question is whether the Sort node's presence for the PK-ordered case is just cosmetic or still forces a full read before the limit applies at larger scales.

  6. XuPeng-SH commented on Nov 30, 2026

    @XuPeng-SH
    Contributor

    补充 4.2-dev 边界实测:#33532 最终合并 34b63d72614b81bf8fd4d08dd5930a0773342345 和实际测试 head 01514ba404ce31d47ffd6bd12e7c2e5c29bad2d7 是同一 Git tree。读取了 悲观多 CN BVT 原始日志:使用该 head 的共享 mo-service,force_index_order.sql 229/229、top.test 33/33、pushdown.test 40/40(1 个已有跳过),无测试失败。另有 同 head 独立单 CN SQL 对照:未使用的宽尾列场景自动改扫基表 128.66 KiB,强制宽覆盖索引 32.77 MiB,数据结果一致;加紧凑索引后自动选中。这个 I/O 数字不是大规模或多 CN 性能结论。当前只补覆盖有界 Top-N 的发布分支证据,未覆盖 main、无 LIMIT 的有序扫描和 DISTINCT 早停;工单继续开放,不转测。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

kind/bugneeds-triageperformance

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions