Recursive CTE Emulates Loose Index Scan
Walk a btree by value with a recursive CTE so a low-cardinality DISTINCT seeks each value instead of scanning every index entry.
Code
-- 低基数字段取 DISTINCT:普通 DISTINCT 要把整棵索引扫一遍;
-- 递归 CTE 沿 btree 跳跃(loose index scan 模拟):每个值只做一次定位
CREATE TEMP TABLE events (
id bigserial,
kind text NOT NULL,
PRIMARY KEY (id)
);
CREATE INDEX idx_events_kind ON events (kind);
INSERT INTO events (kind)
SELECT (ARRAY['click', 'view', 'buy'])[1 + (i % 3)]
FROM generate_series(1, 100000) i;
WITH RECURSIVE kinds AS (
(SELECT kind FROM events ORDER BY kind LIMIT 1) -- 锚点:最小的值
UNION ALL
SELECT (SELECT kind FROM events
WHERE kind > kinds.kind
ORDER BY kind LIMIT 1) -- 跳到下一个更大的值
FROM kinds
WHERE kinds.kind IS NOT NULL
)
SELECT kind FROM kinds WHERE kind IS NOT NULL ORDER BY kind;How the snippet works
What runs here is SELECT / INSERT / CREATE — events, generate_series and kinds are the objects involved.
events is a session-local temp table born from this file’s own statements — nothing pre-exists, and the session’s end retires it.
Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause filtering the rows one statement applies to; an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size; a UNION folding the result sets of two queries into one; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Applying it
Setup is internal: the session-local tables it queries (events) are made by the file, so a single complete run against a scratch database suffices.
Statements worth quoting
INSERT INTO events (kind)
SELECT (ARRAY['click', 'view', 'buy'])[1 + (i % 3)]
FROM generate_series(1, 100000) i;
CREATE TEMP TABLE events (
id bigserial,
kind text NOT NULL,
PRIMARY KEY (id)
);
CREATE INDEX idx_events_kind ON events (kind);
Interactive Tools for This Topic
FAQ
- Name the tables involved in this file.
- `events`, `generate_series`, `kinds` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.