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.
Code
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
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.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What objects does the SQL involve?
- `visits`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.