Video in progress

How does declarative partitioning work in PostgreSQL, and when does it really pay off?

The parent table is only logical, and the data lives in child tables split by a key (range, list or hash). The main benefits are instantly removing old data with DROP/DETACH, and partition pruning when a query filters on the key. If a query doesn't include the key, partitioning can even slow things down.

📖 Answer

CREATE TABLE event (
    id         bigint GENERATED ALWAYS AS IDENTITY, -- PG17+; in older versions bigserial or DEFAULT nextval(...)
    created_at timestamptz NOT NULL,
    payload    jsonb,
    PRIMARY KEY (id, created_at)          -- the partition key must be part of the PK
) PARTITION BY RANGE (created_at);

CREATE TABLE event_2026_11 PARTITION OF event
    FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');

When it helps:

  • retention. "Delete logs older than 90 days": a DELETE means millions of dead rows and hours of VACUUM, while DROP TABLE event_2026_07 is instant;
  • pruning. WHERE created_at >= now() - interval '1 day' reads only one partition. The other partitions don't even appear in the plan;
  • small indexes: each partition's index fits in memory, and VACUUM also works partition by partition.

When it's useless or harmful:

  • queries arrive without the partition key (WHERE user_id = ?): the database scans all the partitions;
  • there are too many partitions (thousands): planning time goes up;
  • the table isn't even 50 GB: a regular index and proper VACUUM are enough.

Limitations: unique and primary keys must include the partition key, so the database doesn't guarantee global uniqueness of id. Partitions have to be created in advance, otherwise an insert fails; pg_partman or a scheduled job does that. A DEFAULT partition prevents the error, but then adding a new partition becomes more expensive.

Converting an existing big table to a partitioned one is a project of its own: a new table, writing to both, copying the data over.