Skip to content

[Performance]: OR across two indexed columns scans the full table #31863

Closed

Description

@Ariznawlll

Description

There is no index-merge: an OR predicate spanning two different indexed columns falls back to a full table scan, even though each column has a perfectly usable secondary index. MySQL 8 executes these via union(index1, index2) — reading a few hundred rows instead of the whole table.

Controlled census (main c6683bd2f5, 2026-10-30, table px.f 200k rows, separate indexes ik(k) 500-card and iv(v) 200k-card; plus a 200k-row multi-index otx.orders with i_buyer(buyer) 5k-card and i_cat(cat) 20-card):

predicate shape plan inputRows expected (MySQL union)
k = 3 OR v = 10 (OR across two indexes) Table Scan 200,000 ~800 + 1 via union(ik, iv)
buyer = 7 OR cat = 5 (orders, two sparse indexes) Table Scan 200,000 ~40 + ~10000 via union
k = 3 OR k = 7 (OR within one index) Index Table Scan ik 800 ✓ fine — same-index OR uses the index
k = 3 AND v = 10 (AND cross-index) Index Table Scan 1 ✓ fine
k IN (7 values) Index Table Scan ik 2,800 ✓ fine — IN expands to same-index OR correctly

So the gap is precisely the cross-index OR: the planner resolves OR-branches only when they share one index; two branches hitting two indexes fall back to a full scan losing 3 orders of magnitude of selectivity (200k rows read for ~800 relevant). Every other boolean shape in the same census behaves correctly, which isolates the missing rule cleanly.

This shape is common in real schemas: WHERE tenant_id = X OR status = 'RETRY' (multi-tenant job tables), WHERE buyer = ? OR seller = ? (marketplace orders — both indexed, the OR is the natural query for "my trades"), WHERE flagged = 1 OR expires_soon.

Impact

  • Queries that MySQL serves in milliseconds via a two-index union cost a full scan on MO; on the 200k test tables that is 5ms, on a 500GB table it is the difference between interactive and batch.
  • Users writing the natural OR form get silently-slow plans; the workaround (split into UNION ALL of two indexed queries) is an unusual rewrite few will try.

Expected behavior

Cross-index OR → union(index-scan-1, index-scan-2) with dedup on PK, exactly MySQL's index_merge union. The same-index OR path already exists in the planner (second census row), so the rule is an extension of existing machinery, not a new execution primitive.

Reproduction

CREATE TABLE f(id INT PRIMARY KEY, k INT, v INT, KEY ik(k), KEY iv(v));  -- 200k rows
EXPLAIN ANALYZE SELECT COUNT(*) FROM f WHERE k = 3 OR v = 10;  -- Table Scan 200,000 on MO; union(ik,iv) ~800 rows on MySQL

main @ c6683bd; five-shape census table above, all from the same session, medians where timed.

Activity

  1. added
    kind/bug
    on Oct 30, 2026
  2. added theissue type on Oct 30, 2026
  3. Ariznawlll commented on Oct 30, 2026

    @Ariznawlll
    CollaboratorAuthor

    结论

    测试不通过。当前 main 的跨二级索引 OR 仍走表扫描;本轮检查未发现结果错误。

    关键证据

    • main@d39d8a40343ccd40bf665036388df7a40ee867f8,隔离双 CN / 单 TN。按本 issue 的建表和原查询,在 3 个新库各生成 200,000 行;跨索引 OR 的 Table Scan 每次输入 200,000 行、输出 401 行。单索引 OR 的对照走索引并输出 800 行。
    • 可复现数据:按 issue 建表后执行 INSERT INTO f SELECT result,MOD(result,500),result FROM generate_series(200000) g;,再运行 issue 中的 OR 查询及 EXPLAIN ANALYZE。
    • 另测三组约 12 万行数据、两个 MO 入口及 MySQL 8.3:对 bucket=43 OR score=10,MO 走表扫描,MySQL 在所测数据上选择两个索引的 index_merge;使用互斥分支的 UNION ALL 对照时,180 次结果对比均一致。两组数据包含同时命中两个条件的行,互斥条件避免重复计数。缺失列错误后数据摘要和连接正常。

    待解决点

    • 在保留 NULL 与重复命中语义的前提下评估跨索引访问,并继续验证不同选择率、覆盖索引和大规模条件;不能假设所有 OR 都应强制走索引。
  4. Ariznawlll commented on Nov 2, 2026

    @Ariznawlll
    CollaboratorAuthor

    Retest on main@HEAD (c6683bd, built 2026-11-02): appears fixed. WHERE k2 = 5 OR k = 7 on a 100k-row table (both columns indexed/PK) runs in 1.2 ms vs 0.3 ms for the single-predicate control — no full-scan signature. Suggest closing unless a larger/skewed repro still shows the union miss.

  5. added
    severity/s0
    and removed on Nov 3, 2026
  6. added a commit that references this issue on Nov 3, 2026
    54a6b17
  7. assigned and unassigned on Nov 3, 2026
  8. slyunnn commented on Nov 5, 2026

    @slyunnn

    Regression and extended verification for #31863 (2026-11-05)

    Verification Environment

    • Frozen origin/main at test start, 80224b0314c6008ecb4de82d1e37b019d5e355df, fix(parser): support SERIAL columns and bare table grants (#32196). The clean verification worktree matched this commit. A fresh native service build, build log, binary version and runtime git_version() all identified 80224b0314.
    • macOS arm64, Go 1.27.1, GOMAXPROCS=4. Fresh isolated topology of 2 CN / 1 TN / 1 Log service / Proxy, using the repository's launch-with-proxy configuration and local disk file service.
    • Proxy 127.0.0.1:6001, CN1 127.0.0.1:16001 and CN2 127.0.0.1:16002 were connected and version-checked. Original scale queries, direct boundary checks, the complete selected SQL BVT and binary prepared checks were executed through each endpoint.
    • Clients used PyMySQL text protocol, mo-tester JDBC, and Go database/sql with go-sql-driver/mysql and interpolateParams=false, exercising real COM_STMT_PREPARE / COM_STMT_EXECUTE.

    What Was Covered

    • OK — Original 200,000-row fixture used id=result, k=MOD(result,500), v=result and separate ik(k) / iv(v) indexes. Default k=3 OR v=10 returned 401 at every endpoint, matching an IGNORE INDEX full-scan control and the independent fixture calculation.
    • OK — Executed plans used both secondary indexes and a distinct primary-key union, with no base-table scan for COUNT(*). Actual index inputs were 400 + 1 = 401 rows over 2 index blocks. The full-scan control read 200,000 rows over 25 blocks. Automatic selection required neither FORCE INDEX nor explicit ANALYZE for this scale fixture.
    • OK — The second reported schema, with 200,000 orders, buyer=MOD(id,5000) and cat=MOD(id,20), returned 10,040 for buyer=7 OR cat=5, matching the Python and full-scan controls. Actual plans read 40 + 10,000 index rows over 3 index blocks without a base-table scan.
    • OK — Same-index OR, cross-index AND, IN, broad-selectivity predicates and overlapping branches matched independent counts. The overlap case read 401 candidate rows and returned 400 distinct base rows.
    • OK — NULL on either branch, duplicate payload values on distinct base rows, residual filters, global LIMIT/OFFSET, transaction-local update/delete followed by rollback, composite primary keys and hidden primary keys passed. Missing-column errors preserved connection and table health.
    • OK — Real binary prepared statements were reused with ordinary, absent-match and NULL bindings. A deliberate missing-column prepare error was followed by successful reuse of both already-prepared statements on the same connection at all three endpoints.
    • OK — The complete pkg/sql/plan and pkg/sql/compile package suites passed on the frozen commit. Relevant named tests verified safe arithmetic keys, disjunction eligibility, fallback, cancellation, physical hash-join selection, branch budgets, index costs and global distinct-set consumers.
    • Not covered — Live MySQL differential execution, production-hardware latency/QPS, TKE and a single query executing across both CNs were outside this run. Runtime physical evidence established workers on the selected coordinator. Both CNs were independently used as coordinators.

    Findings

    • The associated fix is 54a6b173282c1df71fcbf54fff42869a27cf4fc5, fix(planner): merge secondary indexes for OR predicates (#32086), included in the tested main commit. It cost-gates the physical-primary-key union after existing single-index alternatives, deduplicates before downstream consumers, and uses the existing index join for backfill. Fix PR
    • Actual scan counters establish the access-path improvement. The later comment's short elapsed time alone was insufficient to establish index merge. The reproducible original fixture returns 401, while the same-column k=3 OR k=7 control returns 800.
    • The optimization is bounded at 8 branches and retains safe alternatives for unsupported branches, unreliable statistics or unfavorable costs. Full planner tests passed the 7/8/9 branch boundary and cost/fallback controls. This conclusion does not require every broad OR predicate to use index merge.
    • Runtime physical plans showed both index branches, each with mcpu=1, feeding a shared global deduplication/aggregation consumer. Index backfill retains its existing single-CN policy.

    MOTR / BVT Coverage

    • Reused test/distributed/cases/optimizer/secondary_index_or_merge.sql and its committed result. All 71/71 statements passed twice through each endpoint, totaling 426 successful statement comparisons. The second Proxy run and both direct-CN runs included result metadata comparison.
    • Existing committed coverage was sufficient. No duplicate MOTR case, source commit or weekly PR change was added. MatrixOne tracked source and test files remained unchanged.
    • Isolated direct boundary cases and binary-protocol checks ran concurrently across endpoints. Scale queries ran sequentially to limit contention. BVT runs ran sequentially because the runner performs global database cleanup. This scheduling is separate from the verified engine worker parallelism.
    • Package results were terminal PASS. The planner suite reported two existing skipped subtests for HNSW cosine_similarity and interval-frame binding, neither part of these fixes. Selected SQL BVT reported zero failures, ignored statements or abnormal statements.

    Final Conclusion

    Fixed on 80224b0314c6008ecb4de82d1e37b019d5e355df for the reported cross-secondary-index OR access-path regression.

    Large-data regression was required and completed at 200,000 rows because statistics, cost selection and actual physical reads determine the behavior. Original-scale tests proved automatic two-index access and reduced scan work, including overlap and different selectivities. Further arbitrary enlargement or TKE throughput testing is unnecessary for this scoped regression.

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

Metadata

Metadata

Assignees

Labels

kind/bugperformanceseverity/s0

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions