运行说明
复合索引以 tenant_id 打头,但第一条 EXPLAIN 只按 created_at 过滤。PostgreSQL 17 起规划器可用 skip scan 在不同 tenant 前缀之间跳跃,直接用该索引服务第二列过滤;旧版本退回全索引扫描。
对照查询加上 tenant_id = 1,任何版本都走标准前缀区间。两条 EXPLAIN (ANALYZE) 并排打印所选计划——版本差异由此可见,而不是凭假设。
要点提示
- 前缀列不同值较少时 skip scan 收益最大。
- 看计划输出而不是索引定义,才知道真正怎么跑。
核心语句
WHERE created_at >= now() - interval '10 minutes'
代码示例
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
tenant_id integer NOT NULL,
kind text NOT NULL,
payload text NOT NULL,
created_at timestamptz NOT NULL
);
-- composite btree: tenant_id leads, created_at is second
CREATE INDEX events_tenant_created_idx ON events (tenant_id, created_at);
INSERT INTO events (tenant_id, kind, payload, created_at)
SELECT t.tenant_id, 'click', 'e' || g, t.created_at
FROM (
SELECT g % 4 AS tenant_id, now() - (g || ' minutes')::interval AS created_at
FROM generate_series(1, 40) AS g
) t;
-- filtering on the second column only: from PG 17, skip scan can jump over the
-- leading column; older releases fall back to a full index scan
EXPLAIN (ANALYZE, COSTS OFF)
SELECT id, tenant_id FROM events
WHERE created_at >= now() - interval '10 minutes'
ORDER BY created_at
LIMIT 10;
-- the control: with the leading column constrained, every version uses a standard prefix scan
EXPLAIN (ANALYZE, COSTS OFF)
SELECT id, tenant_id FROM events
WHERE tenant_id = 1
AND created_at >= now() - interval '10 minutes'
ORDER BY created_at
LIMIT 10;