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.

SqlData Fetching

Code

snippet
-- 范围列的 && (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

FAQ

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