Scan Strategy Follows Predicate Selectivity

With ANALYZE, a highly selective equality predicate plans an index scan while a half-table range predicate plans a sequential scan.

SqlData Fetching

Code

snippet
-- 规划器按选择率切换扫描策略:谓词越窄越倾向索引,越宽越倾向顺序扫描
CREATE TEMP TABLE readings (
    id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    value numeric NOT NULL
);
INSERT INTO readings (value)
SELECT (i % 100) + random()::numeric(6, 2) FROM generate_series(1, 50000) i;
CREATE INDEX idx_readings_value ON readings (value);

ANALYZE readings;

-- 高选择性(约万分之一命中):索引扫几个页面就够
EXPLAIN (COSTS OFF)
SELECT * FROM readings WHERE value = 42.00;

-- 低选择性(约一半行命中):逐行回表代价高于顺序扫描
EXPLAIN (COSTS OFF)
SELECT * FROM readings WHERE value < 50;

Scan Strategy Follows Predicate Selectivity: reading the source

What runs here is SELECT / INSERT / CREATE / EXPLAIN — readings and generate_series are the objects involved.

readings gets defined in-file as a temporary table living exactly one session — no advance DDL, automatic disappearance at the end.

Mechanically, the statements are built from: a WHERE clause selecting the rows the statement works on; 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.

Applying it

The script is its own setup: tables (readings) are created as it runs — execute the complete file on an empty database.

Statements that matter

INSERT INTO readings (value)
SELECT (i % 100) + random()::numeric(6, 2) FROM generate_series(1, 50000) i;
EXPLAIN (COSTS OFF)
SELECT * FROM readings WHERE value = 42.00;
EXPLAIN (COSTS OFF)
SELECT * FROM readings WHERE value < 50;

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
`readings`, `generate_series` — referenced directly, no join needed.