Multicolumn Index Leftmost Prefix

Query the leading column of a two-column btree index and it serves you; filter on the second column alone and the planner cannot enter the leftmost prefix.

SqlData Integrity

Code

snippet
CREATE TABLE visits (
    customer_id  int         NOT NULL,
    visited_at   timestamptz NOT NULL,
    device       text        NOT NULL
);

-- multicolumn index:按 (customer_id, visited_at) 双列排序
CREATE INDEX visits_customer_time_idx
    ON visits (customer_id, visited_at);

-- leftmost prefix 命中:前导列有条件,索引可用
EXPLAIN
SELECT * FROM visits
WHERE customer_id = 42;

-- 两列都有条件:前缀内定位更准
EXPLAIN
SELECT * FROM visits
WHERE customer_id = 42
  AND visited_at >= '2026-11-01';

-- 只带第二列:进不了前缀,只能顺序扫描全表
EXPLAIN
SELECT * FROM visits
WHERE visited_at >= '2026-11-01';

How it works

SELECT / CREATE / EXPLAIN statements share the script, touching visits.

Breaking the statements into their working parts: a WHERE clause constraining which rows the statement operates on; NOT NULL qualifiers on the required columns.

Using it

The visits table is the working surface here.

Key statements

EXPLAIN
SELECT * FROM visits
WHERE customer_id = 42
  AND visited_at >= '2026-11-01';
EXPLAIN
SELECT * FROM visits
WHERE visited_at >= '2026-11-01';
EXPLAIN
SELECT * FROM visits
WHERE customer_id = 42;

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
`visits`.