GiST Index Serves Range Overlap
Accelerate overlap queries on range columns with a GiST index, because B-tree indexes cannot serve the && operator that range types rely on.
Code
-- 范围列的 && (overlap) 查询走不了 B-tree:GiST 索引才支持 range 类型运算
CREATE TABLE delivery_slots (
truck_id int PRIMARY KEY,
slot tstzrange NOT NULL
);
CREATE INDEX delivery_slots_overlap
ON delivery_slots USING gist (slot);
-- 数据量上去后,这个查询的计划会从 Seq Scan 切到 GiST 索引扫描
SELECT truck_id
FROM delivery_slots
WHERE slot && tstzrange('2026-11-14 08:00', '2026-11-14 12:00')
ORDER BY truck_id;
-- 负向探针:不相交的区间 && 为假,同样能走 GiST 剪枝
SELECT count(*)
FROM delivery_slots
WHERE slot && tstzrange('2026-11-15 08:00', '2026-11-15 12:00');How the snippet works
What runs here is SELECT / CREATE — delivery_slots are the objects involved.
Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; COUNT aggregation; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Applying it
The delivery_slots table is the working surface here.
Statements that matter
SELECT truck_id
FROM delivery_slots
WHERE slot && tstzrange('2026-11-14 08:00', '2026-11-14 12:00')
ORDER BY truck_id;
SELECT count(*)
FROM delivery_slots
WHERE slot && tstzrange('2026-11-15 08:00', '2026-11-15 12:00');
CREATE TABLE delivery_slots (
truck_id int PRIMARY KEY,
slot tstzrange 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 objects does the SQL touch?
- `delivery_slots` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.