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.

SqlData Integrity

Code

snippet
-- 声明式分区:按月 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

FAQ

Which relations are involved here?
`events`.