Btree Index Serves Is Null Lookups
A btree index stores NULLs at its end, so a selective IS NULL predicate is pushed down as an Index Cond instead of a whole-table scan.
Code
-- btree index serves IS NULL lookups:NULL 一起排序进索引(ASC 默认 NULLS LAST,落在索引末端)
CREATE TEMP TABLE alerts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
acknowledged_at timestamptz
);
CREATE INDEX idx_alerts_acknowledged
ON alerts USING btree (acknowledged_at);
-- 绝大多数已确认、少数未确认:IS NULL 高选择性,计划会走索引
INSERT INTO alerts (acknowledged_at)
SELECT now() - (n || ' hours')::interval FROM generate_series(1, 5000);
INSERT INTO alerts (acknowledged_at) VALUES (NULL), (NULL);
ANALYZE alerts;
-- EXPLAIN 里表现为 Index Cond: (acknowledged_at IS NULL)
EXPLAIN (COSTS OFF)
SELECT id FROM alerts WHERE acknowledged_at IS NULL;How the snippet works
SELECT / INSERT / CREATE / EXPLAIN statements share the script, touching alerts and generate_series.
alerts comes into being inside this very file as a session-local temp table — no setup required, and the session’s end takes it away.
Concretely, the SQL combines: a WHERE clause that keeps only the rows a statement is meant to touch; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Applying it
Nothing outside the file is needed: the session-local tables it touches (alerts) are created by the file itself — point it at a scratch database and run the whole thing.
Statements that carry the logic
INSERT INTO alerts (acknowledged_at)
SELECT now() - (n || ' hours')::interval FROM generate_series(1, 5000);
EXPLAIN (COSTS OFF)
SELECT id FROM alerts WHERE acknowledged_at IS NULL;
CREATE TEMP TABLE alerts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
acknowledged_at timestamptz
);
Interactive Tools for This Topic
FAQ
- Which tables does the SQL touch?
- `alerts`, `generate_series`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.