Partitioned Unique Needs Partition Key
A unique index on a partitioned table must include every partition key column, because per-partition enforcement alone cannot guarantee global uniqueness.
Code
-- A monthly range-partitioned table: primary keys and unique constraints must include the partition key
CREATE TABLE events (
event_id bigint NOT NULL,
tenant_id integer NOT NULL,
happened_at timestamptz NOT NULL
) PARTITION BY RANGE (happened_at);
CREATE TABLE events_2026_11 PARTITION OF events
FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
-- A unique index without the partition key is rejected outright:
-- CREATE UNIQUE INDEX ON events (event_id);
-- Error: unique constraints and indexes must include all partition key columns
-- Including happened_at in the index key makes it valid
CREATE UNIQUE INDEX ON events (event_id, happened_at);How it works
The file runs CREATE statements.
The pieces that do the work: NOT NULL qualifiers on the required columns; UNIQUE constraints that keep duplicate values out.
events is declared PARTITION BY RANGE (happened_at) with three columns, and events_2026_11 attaches the November 2026 range as its partition. The commented-out CREATE UNIQUE INDEX ON events (event_id) is rejected outright — a unique constraint on a partitioned table must include every partition key column, because per-partition enforcement alone cannot rule out duplicates across partitions. Including happened_at makes the index valid: CREATE UNIQUE INDEX ON events (event_id, happened_at).
Core lines
CREATE TABLE events (
event_id bigint NOT NULL,
tenant_id integer NOT NULL,
happened_at timestamptz NOT NULL
) PARTITION BY RANGE (happened_at);
CREATE TABLE events_2026_11 PARTITION OF events
FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
CREATE UNIQUE INDEX ON events (event_id, happened_at);
Interactive Tools for This Topic
Report a problem with this exampleOpens a pre-filled issue on GitHub.