Range Partitioning With Pruning
Declare range partitions so inserts route to the right child and queries with the partition key prune every other partition in the plan.
Code
-- 声明式分区:按月 RANGE 分区;唯一约束必须包含分区键
CREATE TABLE events (
id bigserial,
occurred_at timestamptz NOT NULL,
kind text NOT NULL,
PRIMARY KEY (id, occurred_at)
) PARTITION BY RANGE (occurred_at);
CREATE TABLE events_2026_11 PARTITION OF events
FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
INSERT INTO events (occurred_at, kind) VALUES ('2026-11-08', 'login');
-- 分区裁剪:WHERE 带分区键时计划只扫目标分区
EXPLAIN SELECT count(*) FROM events WHERE occurred_at >= '2026-11-01';
-- 缺分区键的谓词会退化为全分区扫描(append)
EXPLAIN SELECT count(*) FROM events WHERE kind = 'login';What the code does
Several statements share this file — SELECT / INSERT / CREATE / EXPLAIN, with events among the objects involved.
In terms of clauses, the statements use: a WHERE clause narrowing which rows one statement affects; COUNT aggregation; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Applying it
The events table is the working surface here.
Statements that matter
CREATE TABLE events (
id bigserial,
occurred_at timestamptz NOT NULL,
kind text NOT NULL,
PRIMARY KEY (id, occurred_at)
) PARTITION BY RANGE (occurred_at);
CREATE TABLE events_2026_11 PARTITION OF events
FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
EXPLAIN SELECT count(*) FROM events WHERE occurred_at >= '2026-11-01';
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.SemVer Range CheckerCheck whether a semantic version satisfies an npm-style range such as caret, tilde, comparison sets, wildcards, or hyphen ranges.
FAQ
- Which relations are involved here?
- `events`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.