Sub topic 9
Primary keys and unique constraints must include the partition key
This chapter covers why PostgreSQL requires every primary key and unique constraint on a partitioned table to include the partition key columns. It also covers what you can do when your natural key does not fit that rule. It assumes you can write CREATE TABLE statements, know what a primary key and a unique constraint guarantee, and have read the earlier chapters on range, list and hash partitioning.
The rule
On a partitioned table, every unique constraint, including a primary key, must contain all of the partition key columns. The constraint may contain additional columns. It cannot omit any partition key column.
Take a table partitioned by placed_at:
CREATE TABLE orders (
order_id bigint NOT NULL,
placed_at date NOT NULL,
total numeric,
PRIMARY KEY (order_id, placed_at)
) PARTITION BY RANGE (placed_at);
-- Fails: the unique constraint does not include the partition key placed_at
-- CREATE TABLE orders_bad (order_id bigint PRIMARY KEY, placed_at date)
-- PARTITION BY RANGE (placed_at);The first statement works because the key (order_id, placed_at) contains placed_at. The commented-out statement fails. PostgreSQL reports an error saying the unique constraint on the partitioned table must include all partitioning columns.
The rule also applies when the key is added later:
ALTER TABLE orders ADD CONSTRAINT orders_order_id_key UNIQUE (order_id);This statement is rejected for the same reason.
Why the rule exists
A partitioned table stores no rows itself. Each partition is a separate physical table with its own indexes. A unique constraint on the parent is implemented as one unique index per partition.
A unique index only compares rows inside its own table. PostgreSQL has no index that spans several partitions. If the constraint were only order_id, the same order_id could be inserted into two partitions, because each partition's index would see only its own rows. Nothing would detect the duplicate.
Including the partition key closes that gap. The partition key decides which partition a row lands in. Two rows with equal values in every key column also have equal partition key values, so they are routed to the same partition. That partition's unique index sees both rows and rejects the second one.
The diagram below shows the routing.
What the constraint actually guarantees
The composite key (order_id, placed_at) guarantees that the pair is unique. It does not guarantee that order_id alone is unique across the table. This insert succeeds:
CREATE TABLE orders_2026_01 PARTITION OF orders
FOR VALUES FROM ('2026-01-01') TO ('2026-02-01');
CREATE TABLE orders_2026_02 PARTITION OF orders
FOR VALUES FROM ('2026-02-01') TO ('2026-03-01');
INSERT INTO orders VALUES (7, '2026-01-15', 10.00);
INSERT INTO orders VALUES (7, '2026-02-03', 25.00); -- allowedTwo different orders now share order_id = 7. If your application treats order_id as an identifier, this is a data integrity problem that the database will not catch.
Expression and column details
- The rule applies to columns of the partition key. If the partition key is an expression, such as
PARTITION BY RANGE (date_trunc('month', placed_at)), a unique constraint cannot be created at all. A unique index can only cover plain columns for this check, and PostgreSQL rejects constraints it cannot match to an expression key. - If the key has several columns, for example
PARTITION BY RANGE (region, placed_at), the unique constraint must include both. - The partition key columns inside a primary key must be
NOT NULL, which a primary key enforces anyway. - For hash partitioning on a single column, the primary key on that column alone is valid, because that column is the whole partition key. The
accountsexample from the hash chapter relies on this.
CREATE TABLE accounts (
account_id bigint NOT NULL PRIMARY KEY,
owner text
) PARTITION BY HASH (account_id);The same applies to a list-partitioned table where the key is the list column:
CREATE TABLE customers (
customer_id bigint NOT NULL,
region text NOT NULL,
name text,
PRIMARY KEY (customer_id, region)
) PARTITION BY LIST (region);Here customer_id alone cannot be the primary key, so the key is (customer_id, region).
Working within the rule
You have a few options when the business key is something like order_id that does not include the partition key.
- Choose the partition key so that it is already part of the identity. If the identifier is the natural partition key, as with
account_idunder hash partitioning, no extra column is needed. - Accept a composite key. Keep
(order_id, placed_at)as the primary key. This is the usual choice for time-series tables. Make sure the application generatesorder_idfrom a sequence or another source that does not repeat, so uniqueness oforder_idcomes from how it is generated, not from the constraint. - Use a sequence or identity column and rely on it. A single global sequence never issues the same value twice, so the composite key is unique in practice even though only the pair is enforced.
- Enforce uniqueness outside the table. If
order_idmust be provably unique, keep a small unpartitioned table of identifiers with a primary key onorder_id, and have the application or a trigger insert into it first. This adds a write and a lookup, so use it only when the guarantee matters.
CREATE TABLE order_ids (
order_id bigint PRIMARY KEY
);Foreign keys
Foreign keys that reference a partitioned table must reference its primary key or a unique constraint, so they inherit the rule. A child table that points at orders has to store both order_id and placed_at:
CREATE TABLE order_items (
order_id bigint NOT NULL,
placed_at date NOT NULL,
line_no int NOT NULL,
sku text,
PRIMARY KEY (order_id, placed_at, line_no),
FOREIGN KEY (order_id, placed_at) REFERENCES orders (order_id, placed_at)
);This is a real cost of the rule. The partition key spreads into every table that references the partitioned table. Foreign keys from a partitioned table to a normal table work without extra columns.
Partitions and their own constraints
A constraint declared on the parent is created on every partition automatically, and you cannot drop it from a single partition. You can add extra constraints on one partition. However, a unique constraint added on only one partition applies to that partition alone and says nothing about other partitions.
When you attach an existing table as a partition, PostgreSQL requires it to have a matching unique index. If the standalone table lacks one, ATTACH PARTITION builds the index while holding a lock, which can be slow on a large table. Create the unique index on the standalone table first.
ON CONFLICT and upserts
INSERT ... ON CONFLICT needs a unique index to infer the conflict target. On a partitioned table the target must match the constraint, so it must list the partition key too:
INSERT INTO orders (order_id, placed_at, total)
VALUES (7, '2026-01-15', 12.00)
ON CONFLICT (order_id, placed_at)
DO UPDATE SET total = EXCLUDED.total;ON CONFLICT (order_id) fails, because no unique index exists on that column alone.
Common errors
| Mistake | Result | Fix |
|---|---|---|
| `PRIMARY KEY (order_id)` on a table partitioned by `placed_at` | Error: unique constraint must include all partitioning columns | Use `PRIMARY KEY (order_id, placed_at)` |
| Assuming `order_id` is unique after using a composite key | Duplicate `order_id` values in different partitions | Generate ids from one sequence, or keep a separate id table |
| `ON CONFLICT (order_id)` | Error: no matching unique constraint | List the full constraint columns |
| Referencing `orders (order_id)` from another table | Error: no unique constraint matching the referenced columns | Reference `(order_id, placed_at)` |
| Unique constraint with an expression partition key | Constraint cannot be created | Partition by plain columns if you need unique keys |
Exercise
A table readings is partitioned with PARTITION BY RANGE (recorded_at). A teammate writes PRIMARY KEY (reading_id). What happens, why, and what is a valid definition? Also, after the fix, can two rows share the same reading_id?
Show answer
PostgreSQL rejects the table because the primary key does not include the partition key recorded_at. A partitioned table has no index spanning partitions, so uniqueness can only be checked inside one partition, and that works only if equal keys always land in the same partition. A valid definition is PRIMARY KEY (reading_id, recorded_at). After the fix, two rows can share the same reading_id if their recorded_at values differ, because only the pair is unique. To prevent repeats, generate reading_id from a single sequence or keep a separate table with a primary key on reading_id.
Exercise
You have orders with PRIMARY KEY (order_id, placed_at). Write an upsert for a row with order_id = 9 and placed_at = '2026-02-01' that updates total when the row exists, and name the table columns a child table needs to reference this row with a foreign key.
Show answer
INSERT INTO orders (order_id, placed_at, total) VALUES (9, '2026-02-01', 5.00) ON CONFLICT (order_id, placed_at) DO UPDATE SET total = EXCLUDED.total; The conflict target must list both key columns. A child table needs both order_id and placed_at columns, with FOREIGN KEY (order_id, placed_at) REFERENCES orders (order_id, placed_at).