Repository navigation
Description
Summary
The min/max-based selectivity estimator for BETWEEN never checks whether the query range intersects the column's [min, max] at all. A BETWEEN that matches zero rows can be estimated as covering 40% of the table, while the sibling comparison operators (>, <) correctly return ~0 via sign checks.
Reproduction (main@HEAD, c6683bd)
CREATE TABLE big1m (k INT PRIMARY KEY, k2 INT, KEY idx_k2 (k2));
-- 1,000,000 rows, k2 ∈ [0, 999]; FLUSH + ANALYZE
EXPLAIN VERBOSE SELECT * FROM big1m WHERE k2 BETWEEN -500 AND -100;
-- Table Scan ... outcnt=401401.00 selectivity=0.401400 ← 40% phantom
SELECT COUNT(*) FROM big1m WHERE k2 BETWEEN -500 AND -100;
-- 0 ← actual
-- controls (same column, correct behavior):
EXPLAIN VERBOSE SELECT * FROM big1m WHERE k2 > 2000; -- outcnt≈0 ✓
EXPLAIN VERBOSE SELECT * FROM big1m WHERE k2 BETWEEN 100 AND 199; -- matches formula ✓Note this defect is only reachable when the min/max path is actually used for BETWEEN (here: negative literals); positive literals on this build hit the magic 0.001 constant tracked in #31994. The two are distinct defects in adjacent code.
Root cause
pkg/sql/plan/stats.go:836 calcSelectivityByMinMax:
case "between", "in_range":
if val1, ok = getFloat64Value(typ, vals[0]); ok {
if val2, ok = getFloat64Value(typ, vals[1]); ok {
ret = (val2 - val1 + 1) / (max - min)
}
}For k2 BETWEEN -500 AND -100 on [0, 999]: ret = (-100 - (-500) + 1) / 999 = 401/999 = 0.4014 — a range that shares no value with the column is scored by its width, not its intersection. The >/< cases escape this only accidentally: an out-of-range literal makes the numerator negative, and ret < 0 → 1e-8 catches it. BETWEEN below the column range produces a positive numerator, so nothing catches it. (Above-range BETWEEN also computes a bogus positive value; when the width exceeds max - min it degrades to the ret > 1 → 0.1 fallback, which is still 0.1 for zero rows.)
The decimal variant (calcSelectivityByMinMaxForDecimal, same file, :788-804) has the same formula shape; its ret > 1 clamp returns 1.0 instead of 0.1, so the same wide-out-of-range input would be scored as a full table match if reached (the two variants are also inconsistent with each other).
Fix direction
Clamp the query range to the column domain before applying the formula:
lo := math.Max(val1, min)
hi := math.Min(val2, max)
if hi < lo {
return 0.00000001 // no intersection
}
ret = (hi - lo + 1) / (max - min)Impact
Out-of-range BETWEEN predicates — routine against time-partitioned or append-only data (WHERE ts BETWEEN <last year> on a table holding only this year) — are costed as highly selective-but-large scans. The inflated outcnt feeds join build/probe side choice and index-vs-scan decisions (see #32015/#32017 for how hard these are to recover from downstream).
Activity
fix(plan): intersect BETWEEN selectivity with column domain (#32224)
slyunnn commentedon Nov 6, 2026
Regression and extended verification for #32046 (2026-11-06)
Verification Environment
origin/mainat test start,b6c57d315c8d1df2aca40ab19dee72136e6f2f81,fix(disttae): preserve optimistic RC write dependencies across snapshot advances (#32174). The clean verification worktree matched this commit. Rebuilt the native service; build log, binary version and runtimegit_version()identifiedb6c57d315c.arm64, Go1.27.1, fresh local disk deployment with2 CN / 1 TN / 1 Log service / Proxy, serviceGOMAXPROCS=4.127.0.0.1:6001, CN1127.0.0.1:16001and CN2127.0.0.1:16002were connected and version-checked. Original SQL, direct extensions and the selected BVT below actually executed through each endpoint.database/sql+go-sql-driver/mysql,interpolateParams=false, realCOM_STMT_PREPARE/COM_STMT_EXECUTE.What Was Covered
k2covering[0,999], its secondary index, flush and full ANALYZE. The exact original negativeBETWEEN -500 AND -100query returned zero matches on every endpoint. Its current automatically chosen plan is described separately below.IGNORE INDEX(idx_k2)control reached the target base-column min/max estimator for the same range. Its estimated output was about0.01rows on the million-row table, displayedselectivity=0.0000, and actual count was0at every endpoint. The former phantom estimate near401,401rows was absent from this targeted path.[0,100], query[-20,19]estimated0.2000; query[-20,120]estimated1.0000; negative disjoint ranges estimated0.0000. Independent exact row-ID/count oracles passed.k2>2000returned zero. Missing-column error1054preserved connection health and the million-row source count, followed by cleanup.Findings
3820136ff2bdeb0b7f3136fd4a66a00b8d571f55,fix(plan): intersect BETWEEN selectivity with column domain, included in the tested main. It reuses the interval estimator to intersect query bounds with the observed domain in both numeric and decimal paths. Fix PRIndex Table Scanwithprefix_betweenand fixedselectivity=0.0010, estimating1,000rows despite actual0. It therefore no longer exercises the target min/max path. The initial probe incorrectly expected min/max behavior from this automatically selected path; its failure and plan were retained. The explicit scan control then verified the intended estimator independently.MOTR / BVT Coverage
test/distributed/cases/optimizer/between_selectivity.sqland its committed result. All22/22statements passed twice through each endpoint, totaling132successful comparisons including metadata, plan-selectivity regex assertions and actual rows. No statements were ignored or abnormal.pkg/sql/planandpkg/sql/compilesuites passed with-count=1. Relevant named tests covered public planning, rewrite boundaries, parameter reuse, physical consumers and interval-estimation domains. Two existing unrelated planner subtests were skipped for HNSW cosine similarity and interval-frame binding.Final Conclusion
Fixed for the numeric and decimal min/max range-intersection estimator on
b6c57d315c8d1df2aca40ab19dee72136e6f2f81. The exact indexed query's separate fixed-selectivity estimate remains as disclosed above.Large-data regression was completed using the shared original
1,000,000-row fixture to verify the reported phantom-cardinality scale and selected access path. The estimator's intersection boundaries also have deterministic4-row and typed unit witnesses. Additional large-scale/TKE testing is unnecessary for this scoped estimator correction.