Sub topic 14
Migrating a serial column to identity
This chapter assumes you know the following:
- How
serialandGENERATED AS IDENTITYcolumns work, from the earlier chapters. - Basic transactions.
- How to read a PostgreSQL error message.
It covers how to convert an existing serial column to an identity column without losing the counter position. It also covers what can go wrong.
Why migrate at all
A serial column looks like an auto-incrementing column, but it is a shortcut for three separate objects:
- An integer column.
- A sequence, which is a counter object, usually named
table_column_seq. - A
DEFAULT nextval('table_column_seq')on the column, plus an ownership link so the sequence is dropped with the column.
The column is also marked NOT NULL.
An identity column keeps the counter inside the column definition. The practical gains are these:
- Standard syntax.
GENERATED ... AS IDENTITYis part of the SQL standard. - Protection from accidental overrides. With
GENERATED ALWAYS, an explicit ID is rejected unless the statement saysOVERRIDING SYSTEM VALUE. - Simpler permissions. Inserting into a table with an identity column needs no separate privilege on the sequence.
- No orphaned sequence. The sequence cannot be dropped or altered independently of the column.
There is no urgent reason to migrate a working system. Do it when you want these properties, or when you are cleaning up a schema anyway.
What the migration has to do
You cannot attach an existing sequence to an identity column. PostgreSQL always creates a new internal sequence. So the migration has three jobs:
- Remove the old default so the column is no longer fed by the old sequence.
- Drop the old sequence.
- Add the identity property, starting the new sequence after the highest ID already used.
The order matters. ADD GENERATED fails if the column still has a default. The new sequence also gets a name derived from the table and column. If the old sequence is still there, the new one gets a different name, such as legacy_id_seq1. Dropping the old sequence first keeps the conventional name.
A minimal migration
Here is the example from the plan. It assumes the current maximum ID is 1000 and the column is already NOT NULL, as serial columns are.
ALTER TABLE legacy ALTER COLUMN id DROP DEFAULT;
DROP SEQUENCE legacy_id_seq;
ALTER TABLE legacy ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY (START WITH 1001);Each statement does one job:
DROP DEFAULTremoves thenextval(...)default. The sequence still exists, but nothing uses it.DROP SEQUENCEsucceeds only because nothing depends on the sequence any more. Do not addCASCADE. If the statement fails with a dependency error, something else uses the sequence. That something needs a decision from you, not a silent deletion.ADD GENERATED BY DEFAULT AS IDENTITYcreates the new sequence with the start value you give it.
BY DEFAULT is the safer first choice. Existing application code may insert explicit IDs, as it could with serial. BY DEFAULT keeps that working. You can tighten the column later with ALTER TABLE ... ALTER COLUMN id SET GENERATED ALWAYS once you know nothing inserts IDs by hand.
Choosing the start value
The minimal example hard-codes 1001. In real work, compute the value instead. There are two candidates:
max(id) + 1. This is always safe against duplicates, but it can reuse IDs from deleted rows at the top of the range.- The old sequence's position. This continues exactly where the counter left off, so IDs of deleted rows are not reused. That matters if those IDs appear in logs, emails, or other systems.
Taking the larger of the two is the safest choice. The old sequence can be behind the table if someone loaded rows with explicit IDs. The table can be behind the sequence if rows were deleted or inserts rolled back.
START WITH accepts only a literal number, not a subquery. So you build the statement dynamically in a DO block. This version is self-contained: it creates a sample table, then migrates it.
CREATE TABLE invoices (
id serial PRIMARY KEY,
amount numeric NOT NULL
);
INSERT INTO invoices (amount)
SELECT g FROM generate_series(1, 50) AS g;
DELETE FROM invoices WHERE id > 45;
DO $$
DECLARE
next_id bigint;
BEGIN
LOCK TABLE invoices IN ACCESS EXCLUSIVE MODE;
SELECT greatest(
(SELECT CASE WHEN is_called THEN last_value + 1 ELSE last_value END
FROM invoices_id_seq),
(SELECT coalesce(max(id), 0) + 1 FROM invoices)
)
INTO next_id;
ALTER TABLE invoices ALTER COLUMN id DROP DEFAULT;
DROP SEQUENCE invoices_id_seq;
EXECUTE format(
'ALTER TABLE invoices ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY (START WITH %s)',
next_id
);
END
$$;
INSERT INTO invoices (amount) VALUES (99) RETURNING id;The final insert returns 51. The table's maximum is 45, but the old sequence had already handed out 50, so the new identity continues after 50 and does not reuse 46 to 50.
A DO block runs as a single transaction, so you do not need BEGIN and COMMIT around it. The LOCK TABLE line takes the lock before reading the counter. That blocks concurrent inserts until the migration commits, so no row can take an ID between your calculation and the switch.
A shorter alternative: add identity, then setval
If you prefer not to build SQL dynamically, add the identity with default options and then move the sequence to the right position, as the earlier chapter on resynchronizing showed:
BEGIN;
ALTER TABLE legacy ALTER COLUMN id DROP DEFAULT;
DROP SEQUENCE legacy_id_seq;
ALTER TABLE legacy ALTER COLUMN id ADD GENERATED BY DEFAULT AS IDENTITY;
SELECT setval(pg_get_serial_sequence('legacy', 'id'), max(id)) FROM legacy;
COMMIT;This is shorter but only considers max(id). It also leaves a window between ADD GENERATED and setval where the new sequence sits at 1. The open transaction holds an exclusive lock on the table, so no other session can insert in that window. If the table is empty, max(id) is null, setval does nothing, and the sequence correctly starts at 1.
Things that break
Errors during the migration
| Error or symptom | Cause | Fix |
|---|---|---|
| `column "id" of relation "legacy" already has a default value` | `DROP DEFAULT` was skipped | Drop the default first |
| `column "id" of relation "legacy" must be declared NOT NULL before identity can be added` | The column came from `integer DEFAULT nextval(...)`, not from `serial` | Run `ALTER COLUMN id SET NOT NULL` first |
| `cannot drop sequence legacy_id_seq because other objects depend on it` | Another column default, a view, or a function references it | Find and update the dependent object. Do not use `CASCADE` blindly |
| `column "id" of relation "legacy" is already an identity column` | The migration already ran | Check `attidentity` (see below) |
Application code that names the sequence
Code that calls nextval('legacy_id_seq') directly will fail after the migration, because that sequence no longer exists. Search your application, ORM configuration, and stored functions for the sequence name before you run this in production. Code that inserts without naming the ID column, or that uses RETURNING id, needs no change.
Permissions
With serial, a role needed USAGE on the sequence as well as INSERT on the table. With identity, INSERT on the table is enough. Old GRANT ... ON SEQUENCE statements disappear with the old sequence. Remove them from any provisioning scripts, because they will now fail.
Locking
DROP DEFAULT and ADD GENERATED both take an ACCESS EXCLUSIVE lock on the table, and the lock lasts until the transaction ends. These operations only change catalog entries and do not rewrite the table, so they are fast. Even so, the lock queues behind long-running queries. In a busy system, set a short lock_timeout so the migration fails quickly, not blocking everything behind it:
SET lock_timeout = '5s';Column type
Migrating the property does not change the column type. A serial column is integer, so the new identity column is also integer. If the table is large enough to approach 2.1 billion rows, change the type to bigint as a separate step. That step rewrites the table, so plan it as its own maintenance window.
Verifying the result
Check that the column is now an identity column and that the old sequence is gone:
SELECT attname, attidentity
FROM pg_attribute
WHERE attrelid = 'invoices'::regclass
AND attname = 'id';
SELECT sequencename, last_value
FROM pg_sequences
WHERE sequencename LIKE 'invoices%';In attidentity, d means GENERATED BY DEFAULT, a means GENERATED ALWAYS, and an empty value means the column is not an identity column. After the migration you should see exactly one sequence for the table, and its last_value is null until the first insert uses it.
Summary of the procedure
- Find the real sequence name with
pg_get_serial_sequence. - Search application code and the database for direct uses of that sequence.
- In one transaction, lock the table and compute the start value from the old sequence and
max(id). - Drop the default, drop the sequence without
CASCADE, and add the identity with that start value. - Verify with
pg_attributeand test an insert withRETURNING id. - Later, decide whether to switch to
GENERATED ALWAYSand whether to widen the type tobigint.
Exercise
A table events has id serial PRIMARY KEY. Its sequence events_id_seq has handed out values up to 700, but the highest ID in the table is 650 because the newest rows were deleted. You migrate with START WITH 651. Why might that be a problem, and what start value avoids it?
Show answer
IDs 651 to 700 were already issued by the old sequence and may be referenced outside the table, for example in logs, emails, or other systems. Starting at 651 reuses them for new rows. Use the larger of max(id) + 1 and the old sequence's next value, which here is 701. Read the old position with SELECT CASE WHEN is_called THEN last_value + 1 ELSE last_value END FROM events_id_seq before dropping the sequence.
Exercise
Why must ALTER COLUMN id DROP DEFAULT run before ADD GENERATED ... AS IDENTITY, and why should DROP SEQUENCE not use CASCADE?
Show answer
ADD GENERATED fails with "already has a default value" if the nextval(...) default is still on the column. DROP SEQUENCE without CASCADE succeeds only if nothing depends on the sequence. If it fails, another object such as a view, function, or second column default uses the sequence. CASCADE would silently remove that dependency and break it.