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.

SqlData Fetching

Code

snippet
-- 函数包住索引列会让普通索引失效:不是 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

FAQ

Which tables does the SQL touch?
`shipments` — referenced directly, no join needed.