Video in progress

When does partition pruning work in declarative partitioning, and what limitations will you run into?

Pruning is the planner or executor not reading unneeded partitions based on the query condition. It works only when there's a condition on the partition key. The main limitations: the primary key and unique indexes must include the partition key, and there is no global unique across partitions.

📖 Answer

CREATE TABLE event (
    id         bigint GENERATED ALWAYS AS IDENTITY,
    created_at timestamptz NOT NULL,
    payload    jsonb,
    PRIMARY KEY (id, created_at)          -- created_at is required
) PARTITION BY RANGE (created_at);

CREATE TABLE event_2026_11 PARTITION OF event
    FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
EXPLAIN SELECT * FROM event WHERE created_at >= '2026-11-10';
-- only event_2026_11 (and later ones) are scanned

Pruning happens in two places: at planning time (literal values) and at execution time (parameters, PG11+). In EXPLAIN ANALYZE you see Subplans Removed: N.

Cases where pruning doesn't work:

  • the condition isn't on the partition key (WHERE id = 5 looks at all partitions);
  • the key is inside a function: WHERE date(created_at) = ...;
  • there are thousands of partitions: planning time grows.

Limitations:

  • there's no global uniqueness on id, only on the (id, created_at) pair;
  • an FK from another table to this one is possible since PG12, but the FK must also include the partition key;
  • without a default partition, a row that falls outside the ranges fails on insert. You have to create new partitions in advance (pg_partman or a scheduled job).

The main win is usually not query speed but dropping old data instantly with DROP TABLE event_2025_01.