Skip to content

[Performance]: Secondary index scan does not leverage sort order for ORDER BY ... LIMIT early termination #23965

Closed

Description

@XuPeng-SH

Is there an existing issue for the same feature request?

  • I have checked the existing issues.

Is your feature request related to a problem?

When a query uses ORDER BY on a column present in a secondary index followed by LIMIT N, MatrixOne scans all matching rows in the index before sorting, instead of leveraging the index order to return the top-N rows directly with early termination.

This means a query like SELECT id FROM t WHERE user_id = ? ORDER BY id DESC LIMIT 20 on a table with 5000 matching rows will scan all 5000 index entries, sort them, then return 20 — instead of scanning only ~20 entries from the index in reverse order.

Steps to Reproduce

CREATE TABLE test_tbl (
  id VARCHAR(64) PRIMARY KEY,
  user_id VARCHAR(64) NOT NULL,
  is_active TINYINT DEFAULT 1,
  content TEXT,
  INDEX idx_user (user_id, is_active)
);

-- Insert 5000 rows for one user
-- (use cross join with a small numbers table)

EXPLAIN ANALYZE
SELECT id, content FROM test_tbl WHERE id IN (
  SELECT id FROM test_tbl
  WHERE user_id = 'user1' AND is_active = 1
  ORDER BY id DESC LIMIT 20
) ORDER BY id DESC;

Observed: Inner Index Table Scan shows inputRows=5000 outputRows=5000 — full scan of all matching rows, then Sort with Limit 20.

Expected: Index scan should be able to iterate in PK (id) descending order and stop after finding 20 matching rows, avoiding the full scan + sort.

Describe the feature you would like

Support index-ordered scan with early termination for queries that combine:

  1. Equality predicates on secondary index prefix columns
  2. ORDER BY on the implicit PK column (appended to secondary index in storage)
  3. LIMIT N

The optimizer should recognize that the secondary index entries are physically ordered by PK within each prefix group, and scan in reverse order stopping after N rows — eliminating the need for a full scan + explicit Sort node.

Use Cases

Paginated listing queries are very common in applications:

  • SELECT ... WHERE user_id = ? ORDER BY id DESC LIMIT 20 (first page)
  • SELECT ... WHERE user_id = ? AND id < ? ORDER BY id DESC LIMIT 20 (cursor pagination)

These are the most frequent queries in our application and currently scan the entire per-user dataset regardless of the LIMIT value.

Additional information

  • MatrixOne version: 3.0.x (Docker image)
  • The workaround of using a subquery reduces the data volume passed to the Sort node (only PK values instead of full rows), but the index scan count remains the same.

Activity

  1. added this to the MO-202603 milestone on Mar 26, 2026
  2. added
    severity/s0
    on Mar 26, 2026
  3. added theissue type on Mar 26, 2026
  4. pinned this issue on Mar 27, 2026
  5. unpinned this issue on Mar 27, 2026
  6. LeftHandCold commented on Jul 7, 2026

    @LeftHandCold
    Collaborator

    fixed

  7. assigned and unassigned on Jul 7, 2026
  8. 15 remaining items

  9. added
    severity/s0
    and removed on Jul 10, 2026
  10. LeftHandCold commented on Jul 14, 2026

    @LeftHandCold
    Collaborator

    fixed

  11. Ariznawlll commented on Jul 16, 2026

    @Ariznawlll
    Collaborator

    已在最新 main 分支验证,该问题已修复。

    测试基线

    测试过程

    1. 按照 issue 中的表结构创建测试表及二级索引:
    CREATE TABLE test_tbl (
      id VARCHAR(64) PRIMARY KEY,
      user_id VARCHAR(64) NOT NULL,
      is_active TINYINT DEFAULT 1,
      content TEXT,
      INDEX idx_user (user_id, is_active)
    );
    1. 为同一个 user_id='user1' 写入 5000 行数据,ID 范围为 id_00000000~id_00004999。

    2. 验证普通 Top-N 查询:

    SELECT id
    FROM test_tbl
    WHERE user_id = 'user1' AND is_active = 1
    ORDER BY id DESC
    LIMIT 20;

    结果正确返回 20 行,范围为 id_00004999~id_00004980。

    1. 验证游标分页查询:
    SELECT id
    FROM test_tbl
    WHERE user_id = 'user1'
      AND is_active = 1
      AND id < 'id_00004900'
    ORDER BY id DESC
    LIMIT 20;

    结果正确返回 20 行,范围为 id_00004899~id_00004880。

    1. 验证 issue 中的原始子查询形式:
    SELECT id, content
    FROM test_tbl
    WHERE id IN (
      SELECT id
      FROM test_tbl
      WHERE user_id = 'user1' AND is_active = 1
      ORDER BY id DESC
      LIMIT 20
    )
    ORDER BY id DESC;

    结果正确返回 20 行,范围为 id_00004999~id_00004980。

    以上三类查询连续重复执行 3 轮,结果均一致。

    执行计划验证

    普通 Top-N 查询的二级索引扫描:

    Index Table Scan on test_tbl.idx_user
    Analyze: inputBlocks=1 inputRows=20 outputRows=20
    Sort Key: __mo_index_idx_col DESC
    Index Reader Param: Sort Key: __mo_index_idx_col DESC Limit: 20
    

    游标分页查询的二级索引扫描:

    Index Table Scan on test_tbl.idx_user
    Analyze: inputBlocks=1 inputRows=20 outputRows=20
    Sort Key: __mo_index_idx_col DESC
    Index Reader Param: Sort Key: __mo_index_idx_col DESC Limit: 20
    Filter Cond: prefix_in_range(__mo_index_idx_col),
                 (__mo_index_pri_col < 'id_00004900')
    

    验证结论

    • 普通 Top-N、游标分页以及 issue 原始子查询的结果均正确。
    • ORDER BY id DESC 和 LIMIT 20 已下推到二级索引读取器。
    • 两种索引查询均只读取 20 行,不再扫描全部 5000 行。
    • 连续验证 3 轮均稳定通过。

    因此,该问题在当前最新 main 上已修复。

  12. Ariznawlll commented on Jul 16, 2026

    @Ariznawlll
    Collaborator

    补充回归测试信息:

    该问题已经加入 motr 黑盒回归,并已合入 motr main:

    回归用例构造 5000 行数据及二级索引,覆盖:

    1. ORDER BY id DESC LIMIT 20 第一页查询,校验返回的 20 个 ID 及降序顺序;
    2. id < 'id_00004900' ORDER BY id DESC LIMIT 20 游标分页查询,校验返回的 20 个 ID 及降序顺序。

    后续可通过 motr 持续防止该问题发生结果正确性回退。

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

Metadata

Metadata

Assignees

Labels

area/performanceseverity/s0

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions