Sargable Range Rewrite Keeps Index
Keep a plain index usable by moving interval math to the constant side: a function wrapped around the indexed column blocks the index scan.
Code
-- 函数包住索引列会让普通索引失效:不是 bug,而是谓词形态问题
CREATE TABLE shipments (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
ship_at timestamptz NOT NULL
);
CREATE INDEX shipments_ship_at_idx ON shipments (ship_at);
-- 非 sargable 写法:ship_at 参与运算,planner 无法把条件映射到索引区间
EXPLAIN (ANALYZE, COSTS OFF)
SELECT count(*)
FROM shipments
WHERE ship_at + interval '2 hours' <= now();
-- sargable 改写:把运算移到常量一侧,语义等价,索引区间扫描可用
EXPLAIN (ANALYZE, COSTS OFF)
SELECT count(*)
FROM shipments
WHERE ship_at <= now() - interval '2 hours';Inside the snippet
Several statements share this file — SELECT / CREATE / EXPLAIN, with shipments among the objects involved.
In terms of clauses, the statements use: a WHERE clause narrowing which rows one statement affects; COUNT aggregation; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Putting it to use
The shipments table is the working surface here.
Core lines
EXPLAIN (ANALYZE, COSTS OFF)
SELECT count(*)
FROM shipments
WHERE ship_at + interval '2 hours' <= now();
EXPLAIN (ANALYZE, COSTS OFF)
SELECT count(*)
FROM shipments
WHERE ship_at <= now() - interval '2 hours';
CREATE TABLE shipments (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
ship_at timestamptz NOT NULL
);
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SemVer Range CheckerCheck whether a semantic version satisfies an npm-style range such as caret, tilde, comparison sets, wildcards, or hyphen ranges.
FAQ
- Which tables does the SQL touch?
- `shipments` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.