Composite Index Column Order Matters
Put equality columns before range columns in a composite index; a range predicate on the first column blocks later columns from being index-scanned.
Code
-- 复合索引列顺序:等值列在前,范围列在后
-- (tenant_id, created_at):tenant 等值 + created 范围,两列都能用上索引
CREATE INDEX idx_events_tenant_time
ON events (tenant_id, created_at);
-- 命中:tenant_id 等值约束 + created_at 范围扫描
SELECT * FROM events
WHERE tenant_id = 42
AND created_at >= NOW() - INTERVAL '7 days';
-- 反序索引 (created_at, tenant_id):范围列在前会截断后续列
-- created_at 是范围条件,tenant_id 无法再走索引,只能逐行过滤
CREATE INDEX idx_events_time_tenant
ON events (created_at, tenant_id);
-- 这条查询对 idx_events_time_tenant 只能用上 created_at 一列
SELECT * FROM events
WHERE created_at >= NOW() - INTERVAL '7 days'
AND tenant_id = 42;How the snippet works
SELECT / CREATE statements share the script, touching events.
Mechanically, the statements are built from: a WHERE clause constraining which rows the statement operates on.
Applying it
The events table is the working surface here.
Statements that matter
SELECT * FROM events
WHERE tenant_id = 42
AND created_at >= NOW() - INTERVAL '7 days';
SELECT * FROM events
WHERE created_at >= NOW() - INTERVAL '7 days'
AND tenant_id = 42;
CREATE INDEX idx_events_tenant_time
ON events (tenant_id, created_at);
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.CSV Column AnalyzerProfile every CSV column with inferred types, empty-cell counts, unique values, and numeric min and max ranges.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.
FAQ
- Which relations are involved here?
- `events` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.