cockroachdb / cockroachdb/cockroach

Optimizer fails to convert ABS(column) < constant to range scan, resulting in full table scan

Open
#171,603 3 comments 0 reactions 1 assignee Claimed by @BryanWangAtCRL View on GitHub
C-enhancement E-quick-win E-starter O-community T-sql-queries X-blathers-triaged
Dominant language
Go
Stars
32.5k
Forks
4.1k
PR merge metrics
PR metrics pending

Description

**Is your feature request related to a problem? Please describe.**
Hi, CockroachDB developers. I wanna recommend an optimization about ABS().
When querying with ABS(t0.c0) < 10, CockroachDB performs a full table scan even though the equivalent condition t0.c0 > -10 AND t0.c0 < 10 can be executed as a range scan. The optimizer does not transform the ABS() predicate into a range condition, preventing efficient index usage.

```sql
CREATE TABLE t0 (c0 INT PRIMARY KEY);
INSERT INTO t0 SELECT * FROM generate_series(1, 1000000);

-- positive case
EXPLAIN (VERBOSE) SELECT * FROM t0 WHERE t0.c0 > -10 AND t0.c0 < 10;;
distribution: local
vectorized: true
• scan
columns: (c0)
estimated row count: 19 (missing stats)
table: t0@t0_pkey
spans: /-9-/10
parallel

-- negative case
EXPLAIN (VERBOSE) SELECT * FROM t0 WHERE ABS(t0.c0) < 10;
distribution: local
vectorized: true
• filter
│ columns: (c0)
│ estimated row count: 333 (missing stats)
│ filter: abs(c0) < 10

└── • scan
columns: (c0)
estimated row count: 1,000 (missing stats)
table: t0@t0_pkey
spans: FULL SCAN
```
**Describe the solution you'd like**
Add a predicate transformation rule in the logical optimization phase to convert: Where `N` is a non-negative constant (literal or foldable expression), we can transform `ABS(col) < N` into `col > -N AND col < N`.

Jira issue: CRDB-64727

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.