Full answer
Setup for the example:
CREATE TABLE clicks (id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, url text);
SELECT setval(pg_get_serial_sequence('clicks', 'id'), 2147483646);INSERT INTO clicks (url) VALUES ('/a') RETURNING id;Result:
id
------------
2147483647
(1 row)INSERT INTO clicks (url) VALUES ('/b');Output:
ERROR: nextval: reached maximum value of sequence "clicks_id_seq" (2147483647)SELECT seqrelid::regclass::text AS sequence, seqtypid::regtype::text AS type, round(100.0 * (SELECT last_value FROM clicks_id_seq) / seqmax, 2) AS pct_used FROM pg_sequence WHERE seqrelid = 'clicks_id_seq'::regclass;PostgreSQL returns:
sequence | type | pct_used
---------------+---------+----------
clicks_id_seq | integer | 100.00
(1 row)ALTER TABLE clicks ALTER COLUMN id TYPE bigint; ALTER SEQUENCE clicks_id_seq AS bigint MAXVALUE 9223372036854775807; INSERT INTO clicks (url) VALUES ('/b') RETURNING id;Result on PostgreSQL 17:
id
------------
2147483648
(1 row)The last value, 2,147,483,647, is handed out, and the next insert fails with 'nextval: reached maximum value of sequence'. The monitoring query reports 100% use; running it for every sequence and alerting at around 70% leaves months to react. On this tiny table, ALTER COLUMN TYPE bigint is instant enough, and the identity sequence must be widened as well, after which inserts continue. On a table with billions of rows, that ALTER rewrites the table under an exclusive lock for hours, so the online approach is: add id_new bigint, fill it with a trigger for new rows and batches for old ones, create a unique index concurrently, then swap columns and constraints in one short transaction. Using bigint from the start avoids all of this.
CREATE TABLE clicks (id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, url text);
SELECT setval(pg_get_serial_sequence('clicks', 'id'), 2147483646);
INSERT INTO clicks (url) VALUES ('/a') RETURNING id;
INSERT INTO clicks (url) VALUES ('/b');
SELECT seqrelid::regclass::text AS sequence, seqtypid::regtype::text AS type, round(100.0 * (SELECT last_value FROM clicks_id_seq) / seqmax, 2) AS pct_used FROM pg_sequence WHERE seqrelid = 'clicks_id_seq'::regclass;
ALTER TABLE clicks ALTER COLUMN id TYPE bigint; ALTER SEQUENCE clicks_id_seq AS bigint MAXVALUE 9223372036854775807; INSERT INTO clicks (url) VALUES ('/b') RETURNING id;Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
- int4 keys stop at about 2.1 billion
- Monitor sequence usage
- ALTER TYPE rewrites the table
- Migrate online with a new column and backfill
- Widen the sequence too
Common mistakes
- Using int for high-volume keys
- Running ALTER COLUMN TYPE on a huge table at peak
Follow-ups
- How do foreign keys referencing the id complicate the migration?
- Why might the sequence be bigint while the column is int?
Tips
- Show the monitoring query