Repository navigation
Description
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 ALLof 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 MySQLmain @ c6683bd; five-shape census table above, all from the same session, medians where timed.
Activity
Ariznawlll commentedon Oct 30, 2026
结论
测试不通过。当前 main 的跨二级索引 OR 仍走表扫描;本轮检查未发现结果错误。
关键证据
main@d39d8a40343ccd40bf665036388df7a40ee867f8,隔离双 CN / 单 TN。按本 issue 的建表和原查询,在 3 个新库各生成 200,000 行;跨索引 OR 的 Table Scan 每次输入 200,000 行、输出 401 行。单索引 OR 的对照走索引并输出 800 行。INSERT INTO f SELECT result,MOD(result,500),result FROM generate_series(200000) g;,再运行 issue 中的 OR 查询及EXPLAIN ANALYZE。bucket=43 OR score=10,MO 走表扫描,MySQL 在所测数据上选择两个索引的index_merge;使用互斥分支的 UNION ALL 对照时,180 次结果对比均一致。两组数据包含同时命中两个条件的行,互斥条件避免重复计数。缺失列错误后数据摘要和连接正常。待解决点
Ariznawlll commentedon Nov 2, 2026
Retest on main@HEAD (c6683bd, built 2026-11-02): appears fixed.
WHERE k2 = 5 OR k = 7on 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.fix(planner): merge secondary indexes for OR predicates (#32086)
fix(plan): hash safe arithmetic and OR EXISTS predicates (#32087)
slyunnn commentedon Nov 5, 2026
Regression and extended verification for #31863 (2026-11-05)
Verification Environment
origin/mainat 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 runtimegit_version()all identified80224b0314.arm64, Go1.27.1,GOMAXPROCS=4. Fresh isolated topology of2 CN / 1 TN / 1 Log service / Proxy, using the repository'slaunch-with-proxyconfiguration and local disk file service.127.0.0.1:6001, CN1127.0.0.1:16001and CN2127.0.0.1:16002were connected and version-checked. Original scale queries, direct boundary checks, the complete selected SQL BVT and binary prepared checks were executed through each endpoint.database/sqlwithgo-sql-driver/mysqlandinterpolateParams=false, exercising realCOM_STMT_PREPARE/COM_STMT_EXECUTE.What Was Covered
200,000-row fixture usedid=result,k=MOD(result,500),v=resultand separateik(k)/iv(v)indexes. Defaultk=3 OR v=10returned401at every endpoint, matching anIGNORE INDEXfull-scan control and the independent fixture calculation.COUNT(*). Actual index inputs were400 + 1 = 401rows over2index blocks. The full-scan control read200,000rows over25blocks. Automatic selection required neitherFORCE INDEXnor explicitANALYZEfor this scale fixture.200,000orders,buyer=MOD(id,5000)andcat=MOD(id,20), returned10,040forbuyer=7 OR cat=5, matching the Python and full-scan controls. Actual plans read40 + 10,000index rows over3index blocks without a base-table scan.OR, cross-indexAND,IN, broad-selectivity predicates and overlapping branches matched independent counts. The overlap case read401candidate rows and returned400distinct base rows.NULLon either branch, duplicate payload values on distinct base rows, residual filters, globalLIMIT/OFFSET, transaction-local update/delete followed by rollback, composite primary keys and hidden primary keys passed. Missing-column errors preserved connection and table health.NULLbindings. A deliberate missing-column prepare error was followed by successful reuse of both already-prepared statements on the same connection at all three endpoints.pkg/sql/planandpkg/sql/compilepackage 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.Findings
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 PR401, while the same-columnk=3 OR k=7control returns800.8branches and retains safe alternatives for unsupported branches, unreliable statistics or unfavorable costs. Full planner tests passed the7/8/9branch boundary and cost/fallback controls. This conclusion does not require every broadORpredicate to use index merge.mcpu=1, feeding a shared global deduplication/aggregation consumer. Index backfill retains its existing single-CN policy.MOTR / BVT Coverage
test/distributed/cases/optimizer/secondary_index_or_merge.sqland its committed result. All71/71statements passed twice through each endpoint, totaling426successful statement comparisons. The second Proxy run and both direct-CN runs included result metadata comparison.PASS. The planner suite reported two existing skipped subtests for HNSWcosine_similarityand interval-frame binding, neither part of these fixes. Selected SQL BVT reported zero failures, ignored statements or abnormal statements.Final Conclusion
Fixed on
80224b0314c6008ecb4de82d1e37b019d5e355dffor the reported cross-secondary-indexORaccess-path regression.Large-data regression was required and completed at
200,000rows 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.