Skip to content

[Performance]: BETWEEN min/max selectivity never checks range intersection #32046

Closed

Description

@Ariznawlll

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

  1. added
    kind/bug
    on Nov 3, 2026
  2. added this to the MO-202611 milestone on Nov 3, 2026
  3. added theissue type on Nov 3, 2026
  4. added
    severity/s0
    and removed on Nov 5, 2026
  5. added a commit that references this issue on Nov 5, 2026
    3820136
  6. assigned and unassigned on Nov 5, 2026
  7. slyunnn commented on Nov 6, 2026

    @slyunnn

    Regression and extended verification for #32046 (2026-11-06)

    Verification Environment

    • Frozen latest origin/main at 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 runtime git_version() identified b6c57d315c.
    • macOS arm64, Go 1.27.1, fresh local disk deployment with 2 CN / 1 TN / 1 Log service / Proxy, service GOMAXPROCS=4.
    • 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 SQL, direct extensions and the selected BVT below actually executed through each endpoint.
    • Clients used PyMySQL text protocol and mo-tester JDBC. Binary pagination checks used Go database/sql + go-sql-driver/mysql, interpolateParams=false, real COM_STMT_PREPARE / COM_STMT_EXECUTE.

    What Was Covered

    • OK — Executed the original million-row table shape with k2 covering [0,999], its secondary index, flush and full ANALYZE. The exact original negative BETWEEN -500 AND -100 query returned zero matches on every endpoint. Its current automatically chosen plan is described separately below.
    • OK — An explicit IGNORE INDEX(idx_k2) control reached the target base-column min/max estimator for the same range. Its estimated output was about 0.01 rows on the million-row table, displayed selectivity=0.0000, and actual count was 0 at every endpoint. The former phantom estimate near 401,401 rows was absent from this targeted path.
    • OK — Integer, Decimal64 and Decimal128 fixtures directly checked negative disjoint ranges, partial intersection and full coverage. For column domain [0,100], query [-20,19] estimated 0.2000; query [-20,120] estimated 1.0000; negative disjoint ranges estimated 0.0000. Independent exact row-ID/count oracles passed.
    • OK — Right-disjoint and reversed bounds returned empty results; singleton domains and NULL controls returned the expected rows. Full planner tests covered numeric/decimal estimator boundaries, literal scaling and parse/bind/build reachability.
    • OK — Original comparison control k2>2000 returned zero. Missing-column error 1054 preserved connection health and the million-row source count, followed by cleanup.
    • Not covered — The separate fixed-selectivity/histogram behavior tracked in [Performance]: selectivity assumes uniform distribution: 900x off on hot values #31994, production optimizer quality across skew distributions, TKE and live MySQL differential execution. This acceptance concerns the min/max intersection estimator.

    Findings

    • PR fix(plan): intersect BETWEEN selectivity with column domain #32224 merged as 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 PR
    • The exact original indexed SQL now selects an Index Table Scan with prefix_between and fixed selectivity=0.0010, estimating 1,000 rows despite actual 0. 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.
    • This residual fixed estimate is distinct from the clipped min/max calculation and remains within the separately tracked estimation scope. Neither that fixed estimate nor broader histogram support is claimed resolved by fix(plan): intersect BETWEEN selectivity with column domain #32224. Adjacent issue #31994

    MOTR / BVT Coverage

    • Reused test/distributed/cases/optimizer/between_selectivity.sql and its committed result. All 22/22 statements passed twice through each endpoint, totaling 132 successful comparisons including metadata, plan-selectivity regex assertions and actual rows. No statements were ignored or abnormal.
    • Full pkg/sql/plan and pkg/sql/compile suites 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.
    • Existing maintained regressions were sufficient. No duplicate MOTR case/source commit or weekly PR update was added. MatrixOne tracked files remained clean.
    • Preparation and independent package checks used bounded parallelism. Scale queries ran sequentially. BVT ran sequentially because the runner performs global database cleanup. Actual engine worker evidence is reported separately from runner scheduling.

    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 deterministic 4-row and typed unit witnesses. Additional large-scale/TKE testing is unnecessary for this scoped estimator correction.

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

Metadata

Metadata

Assignees

Labels

kind/bugseverity/s0

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions