Btree Skip Scan Serves Second Column

A btree index on (tenant_id, created_at) can serve created_at-only filters through skip scan on PostgreSQL 17, instead of scanning every leading-column range.

SqlData Integrity

Code

snippet
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;

What the demo explains

The composite index leads with tenant_id, yet the first EXPLAIN filters only on created_at. On PostgreSQL 17 the planner can use skip scan to jump between distinct tenant prefixes and serve the second-column filter from the same index; older releases fall back to a full index scan.

The control query adds tenant_id = 1, and any version then walks the standard prefix range. Two EXPLAIN (ANALYZE) runs print the chosen plans side by side, which is how the version difference becomes visible rather than assumed.

Practical notes

  • Skip scan pays off when the leading column has few distinct values.
  • Check the plan output, not the index definition, for what actually runs.

Interactive Tools for This Topic

FAQ

Why did older PostgreSQL scan the whole index?
Without skip scan, a query that never constrains the leading column cannot use prefix seeks; the planner had to scan all tenant ranges, as the fallback plan shows.