Sub topic 12
Changing, restarting and dropping identity
This chapter assumes you can create an identity column, you know the difference between GENERATED ALWAYS and GENERATED BY DEFAULT, and you know that an identity column is backed by a sequence. Here you will change an existing identity column without recreating the table.
The four kinds of change
An identity column is two things: a column property (ALWAYS or BY DEFAULT) and a hidden sequence that supplies the values. ALTER TABLE ... ALTER COLUMN can change either one.
| Command | What it changes | Existing rows | Sequence position |
|---|---|---|---|
| `SET GENERATED ALWAYS` or `SET GENERATED BY DEFAULT` | The generation mode | Untouched | Unchanged |
| `SET INCREMENT BY`, `SET START WITH`, `SET MINVALUE`, `SET MAXVALUE`, `SET CACHE`, `SET CYCLE` | The sequence's settings | Untouched | Unchanged, except that the next step uses the new increment |
| `RESTART` or `RESTART WITH n` | Where the next value comes from | Untouched | Reset |
| `DROP IDENTITY` | Removes the identity property and the sequence | Untouched | Sequence is deleted |
None of these commands rewrites or renumbers existing rows. They only affect values that are generated later. You must own the table to run them.
Switching the generation mode
SET GENERATED only flips the mode. It does not touch the sequence, so the next generated value is the same as before the change.
CREATE TABLE invoices (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
note text NOT NULL
);
INSERT INTO invoices (note) VALUES ('a'), ('b'), ('c'); -- ids 1, 2, 3
ALTER TABLE invoices ALTER COLUMN id SET GENERATED BY DEFAULT;
INSERT INTO invoices (id, note) VALUES (50, 'explicit'); -- accepted now
INSERT INTO invoices (note) VALUES ('d') RETURNING id; -- 4The last insert returns 4, not 51. A sequence knows nothing about values you supply yourself. This is the same effect that makes a resync necessary after a bulk load.
Switching to ALWAYS does not check existing rows. Rows that were inserted with explicit IDs stay as they are.
Inspecting the current settings
Before you change anything, look at what is there. The information_schema view shows the column's settings, and pg_sequences shows the sequence's state.
SELECT column_name, identity_generation, identity_start, identity_increment
FROM information_schema.columns
WHERE table_name = 'invoices' AND is_identity = 'YES';
SELECT sequencename, start_value, increment_by, last_value
FROM pg_sequences
WHERE sequencename = 'invoices_id_seq';last_value is NULL until the sequence has been used. Once it has been used, last_value is the most recently handed-out number. The name invoices_id_seq follows the usual pattern <table>_<column>_seq. You can also get it from pg_get_serial_sequence('invoices', 'id'), which works for identity columns.
Changing sequence options
Each sequence option has its own SET form. These forms change settings only, so they do not move the sequence.
ALTER TABLE invoices ALTER COLUMN id SET INCREMENT BY 10;
ALTER TABLE invoices ALTER COLUMN id SET MAXVALUE 1000000;
ALTER TABLE invoices ALTER COLUMN id SET NO CYCLE;
ALTER TABLE invoices ALTER COLUMN id SET CACHE 20;SET INCREMENT BY 10 applies from the next call. If the last value handed out was 4, the next value is 14. SET START WITH is different from the others. It changes only the stored start value, which later RESTART commands use. It does not move the current position.
Restarting the sequence
RESTART sets the value that the next insert will receive.
ALTER TABLE invoices ALTER COLUMN id RESTART WITH 1000;
INSERT INTO invoices (note) VALUES ('e') RETURNING id; -- 1000
ALTER TABLE invoices ALTER COLUMN id SET START WITH 2000;
ALTER TABLE invoices ALTER COLUMN id RESTART; -- uses the stored start value
INSERT INTO invoices (note) VALUES ('f') RETURNING id; -- 2000A bare RESTART goes back to the stored start value, which is 1 unless you set another one when you created the column or changed it with SET START WITH.
Restarting below existing IDs
The sequence does not check the table. If you restart at a number that rows already use, the sequence will eventually produce a duplicate.
ALTER TABLE invoices ALTER COLUMN id RESTART WITH 1;
INSERT INTO invoices (note) VALUES ('g');
-- ERROR: duplicate key value violates unique constraint "invoices_pkey"
-- DETAIL: Key (id)=(1) already exists.The primary key constraint is what catches the problem. Without one, the duplicates would be inserted silently. That is why identity alone does not guarantee uniqueness. Every RESTART below the current maximum needs a reason, such as an emptied table.
Emptying a table and restarting in one step
For test fixtures and similar cases you usually want to delete all rows and restart numbering. TRUNCATE can do both:
TRUNCATE invoices RESTART IDENTITY;This restarts every sequence owned by the table's columns, including identity sequences. It removes all rows, so use it only when that is what you want.
Dropping identity
DROP IDENTITY converts the column into a plain column. The data and the type stay. The identity property and the sequence are removed.
ALTER TABLE invoices ALTER COLUMN id DROP IDENTITY;
INSERT INTO invoices (note) VALUES ('h');
-- ERROR: null value in column "id" of relation "invoices" violates not-null constraintThe insert fails because the column no longer generates values, but it is still NOT NULL. Dropping identity does not remove the NOT NULL constraint, and it does not remove the primary key. If you run the statement on a column that is not an identity column, PostgreSQL raises an error. Use DROP IDENTITY IF EXISTS to turn that error into a notice, which is useful in migration scripts that may run more than once.
You cannot get the same result by running DROP SEQUENCE invoices_id_seq. The sequence belongs to the column, and PostgreSQL rejects that command. To remove the sequence, drop the identity or the column.
Adding identity to an existing column
The reverse operation is ADD GENERATED. The column must be NOT NULL, must not already be an identity column, and must have no default value.
-- Choose a start above the current maximum: SELECT max(id) FROM invoices;
ALTER TABLE invoices
ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY (START WITH 5000);A new sequence begins at 1 unless you say otherwise. If the table already holds rows, set START WITH above the highest ID, as shown. Otherwise the first inserts will collide with existing rows. This is the same step used when migrating a serial column.
Common mistakes
- Restarting without checking the table. Compare the restart value with
max(id)first. - Expecting
SET GENERATEDto move the sequence. It only changes the mode. - Expecting
START WITHto move the sequence. UseRESTART WITHfor that. - Dropping the sequence directly. Use
DROP IDENTITYinstead. - Forgetting the lock.
ALTER TABLEtakes a lock on the table, so on a busy system run these commands in a quiet period or with a short lock timeout.
Exercise
A table tickets has an identity column id with rows up to id 840. Someone ran ALTER TABLE tickets ALTER COLUMN id RESTART WITH 500; and inserts now fail with a duplicate key error. Which command fixes it, and why did the error happen?
Show answer
Run ALTER TABLE tickets ALTER COLUMN id RESTART WITH 841;, or any value above max(id). The sequence never looks at the table, so after the restart it handed out 500, 501 and so on, which are IDs that existing rows already use. The primary key constraint rejected each of those values.
Exercise
You run ALTER TABLE invoices ALTER COLUMN id DROP IDENTITY; and then INSERT INTO invoices (note) VALUES ('x');. What happens, and what single command lets that insert work again?
Show answer
The insert fails with a not-null violation, because the column keeps its NOT NULL constraint but no longer generates values. Running ALTER TABLE invoices ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY (START WITH n);, with n above the current max(id), makes the insert work again.