Sub topic 8
Adding a primary key: identity alone is not unique
This chapter assumes you can write CREATE TABLE, INSERT and SELECT. It also assumes you know what a primary key is and have read the earlier chapters on GENERATED ALWAYS and GENERATED BY DEFAULT, and on OVERRIDING SYSTEM VALUE.
What identity does and does not promise
An identity column attaches a sequence to a column and fills the column with the sequence's next value when you omit it. PostgreSQL also marks an identity column NOT NULL automatically. It promises nothing else about the values in the column.
Identity does not create an index, so nothing checks that the values are distinct. Duplicates can get in through several routes:
- An explicit value in a
GENERATED BY DEFAULTcolumn. OVERRIDING SYSTEM VALUEon aGENERATED ALWAYScolumn.- A sequence restarted or moved backwards with
ALTER ... RESTARTorsetval. - A sequence created with
CYCLE, which wraps around after reaching its limit. - Rows copied in from another table or system.
Uniqueness comes from a constraint. For a table's main key, that constraint is PRIMARY KEY.
Seeing duplicates happen
This table has an identity column and no key:
CREATE TABLE events (
id bigint GENERATED BY DEFAULT AS IDENTITY,
note text NOT NULL
);
INSERT INTO events (id, note) VALUES (1, 'explicit');
INSERT INTO events (note) VALUES ('generated');
SELECT id, note FROM events ORDER BY note;Both rows have id = 1. The sequence had never been used, so its first value was 1. The explicit insert did not touch the sequence, so the generated row received 1 as well. PostgreSQL reports no error, because nothing told it that id must be unique.
GENERATED ALWAYS does not close this gap. Anyone who writes OVERRIDING SYSTEM VALUE can still insert a duplicate. GENERATED ALWAYS only blocks accidental explicit values, and the primary key is what blocks wrong ones.
What a primary key adds
PRIMARY KEY on a column is a shorthand for two guarantees plus an index:
| Property | Identity | `PRIMARY KEY` | `UNIQUE` |
|---|---|---|---|
| Generates values automatically | Yes | No | No |
| Rejects `NULL` | Yes | Yes | No (many `NULL`s are allowed) |
| Rejects duplicate values | No | Yes | Yes |
| Creates an index | No | Yes (unique B-tree) | Yes (unique B-tree) |
| Can be the target of a foreign key | No | Yes | Yes |
| Allowed once per table | Any number of identity columns | Once | Any number |
Identity and PRIMARY KEY do separate jobs, and you normally declare both on the same column:
CREATE TABLE invoices (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
number text NOT NULL UNIQUE
);The second line shows UNIQUE on a different column. A table has only one primary key, but it can have as many unique constraints as it needs, for example on a business identifier such as an invoice number.
Adding a primary key to an existing table
Back to the events table, which now holds two rows with id = 1. Adding the key fails:
ALTER TABLE events ADD PRIMARY KEY (id);
-- ERROR: could not create unique index "events_pkey"
-- DETAIL: Key (id)=(1) is duplicated.PostgreSQL builds a unique index to back the constraint, and the build stops at the first duplicate. Find all the offending values first:
SELECT id, count(*)
FROM events
GROUP BY id
HAVING count(*) > 1;How you repair them depends on the data. If the rows are true copies, delete all but one. If they are different rows that collided, give one of them a fresh ID. Here the generated row gets a new value from the sequence, which has already handed out 1, so the next value is 2:
UPDATE events SET id = DEFAULT WHERE note = 'generated';
ALTER TABLE events ADD PRIMARY KEY (id);SET id = DEFAULT is allowed on an identity column in both modes, because it asks the sequence for a value instead of supplying one. After the repair, the constraint is in place.
Naming the constraint
Without a name, PostgreSQL calls the constraint events_pkey. A name makes error messages and later migrations easier to read:
ALTER TABLE events
ADD CONSTRAINT events_pk PRIMARY KEY (id);Use this form instead of the one above, not as well as it, since a table can have only one primary key.
Adding the key to a large table
ADD PRIMARY KEY builds the index while holding a lock that blocks writes. On a big table, build the index without blocking writers first, then attach it:
CREATE UNIQUE INDEX CONCURRENTLY events_id_idx ON events (id);
ALTER TABLE events
ADD CONSTRAINT events_pk PRIMARY KEY USING INDEX events_id_idx;The second statement is quick because the index already exists. USING INDEX requires the column to be NOT NULL already, and an identity column is. The index is renamed to match the constraint. CREATE INDEX CONCURRENTLY cannot run inside a transaction block, and if it fails it leaves an invalid index that you must drop before retrying.
How the key reports a collision
With the key in place, the earlier problem stops being silent. Suppose the sequence's last value is 2 and someone inserts an explicit ID that the sequence has not reached yet:
INSERT INTO events (id, note) VALUES (3, 'imported');
INSERT INTO events (note) VALUES ('generated later');
-- ERROR: duplicate key value violates unique constraint "events_pk"
-- DETAIL: Key (id)=(3) already exists.The sequence returns 3, and the key rejects it because the imported row holds 3. The failed insert still consumed that sequence value. If you run the generated insert again, it receives 4 and succeeds.
This is the typical symptom after loading data with explicit IDs. The key stops bad data, but the sequence is still behind the table. The fix is to move the sequence past the maximum ID, as covered in the chapter on resynchronizing after bulk loads.
Related points
- Foreign keys need a unique target. A foreign key can only reference columns covered by a primary key or unique constraint. Referencing a bare identity column fails with an error saying there is no unique constraint matching the given keys.
- Composite keys. Sometimes the primary key is several columns, such as
(order_id, line_no). An identity column can still live in the table as a separate unique column, but then it needs its ownUNIQUEconstraint. Identity does not become a key by being there. - Partitioned tables. A unique or primary key constraint on a partitioned table must include every partition key column. An ID alone is then unique only together with the partition key unless the table is partitioned by
id. Check this before choosing a partitioning scheme. CYCLEsequences. A sequence that wraps around reuses old numbers. Without a key, the table silently holds duplicates. With a key, the wrap-around produces errors once old rows still exist. In most designs, avoidCYCLEon a key column.- Dropping identity keeps the key.
ALTER COLUMN id DROP IDENTITYremoves the generator only. The primary key and its index stay, and the column remainsNOT NULL.
Checking what a table enforces
You can inspect the constraints on a table with psql's \d events, or with a catalog query:
SELECT conname, contype, pg_get_constraintdef(oid) AS definition
FROM pg_constraint
WHERE conrelid = 'events'::regclass;contype is p for a primary key, u for unique and f for foreign key. If your identity table returns no p row, nothing prevents duplicate IDs.
Exercise
A table is defined as CREATE TABLE tags (id integer GENERATED ALWAYS AS IDENTITY, label text NOT NULL);. A colleague says that because the column is GENERATED ALWAYS, two rows can never share an id. Is that right? What would you run to make the guarantee real, and what must you check first if the table already has data?
Show answer
The colleague is wrong. GENERATED ALWAYS only stops ordinary inserts from supplying a value. A row can still get a duplicate through OVERRIDING SYSTEM VALUE, a restarted or moved-back sequence, or a CYCLE sequence, and identity creates no index. Add a primary key with ALTER TABLE tags ADD CONSTRAINT tags_pk PRIMARY KEY (id);. If the table already has rows, first run SELECT id, count(*) FROM tags GROUP BY id HAVING count(*) > 1; and fix any duplicates, because the index build fails on the first duplicate. On a large table, build CREATE UNIQUE INDEX CONCURRENTLY first and attach it with ADD CONSTRAINT ... PRIMARY KEY USING INDEX.
Exercise
After a bulk load of rows with explicit IDs 1 to 500 into a GENERATED BY DEFAULT table that has a primary key, ordinary inserts fail with "duplicate key value violates unique constraint". The sequence is still at its start. Why does the error appear, and does the failed insert use up a sequence value?
Show answer
The sequence still returns 1, 2, 3 and so on, and those IDs already exist in the table, so the primary key rejects each new row. Yes, every failed insert consumes a sequence value, since sequence values are never rolled back. Repeated retries eventually pass 500 and succeed, but the proper fix is to set the sequence to the table's maximum ID with setval.