Quick revision
The short answer
In PostgreSQL, ALTER TABLE ... ALTER COLUMN id TYPE bigint rewrites all 1.5 billion rows under an ACCESS EXCLUSIVE lock, which means hours of downtime, so we do it in stages instead. We add a new bigint column, keep it in sync with a trigger, backfill old rows in small batches while watching replication lag and WAL volume, build a unique index CONCURRENTLY, then swap the primary key in one short transaction with ADD CONSTRAINT ... PRIMARY KEY USING INDEX and rename the columns. Along the way we convert the sequence, every referencing foreign key column, the JPA mappings to Long and every downstream consumer; in MySQL we would use online DDL or gh-ost or pt-online-schema-change.
What to remember
In this answer, we saw that changing the column type directly rewrites 1.5 billion rows under an ACCESS EXCLUSIVE lock, so we migrate in stages: a new bigint column kept in sync by a trigger, a batched backfill, a unique index built concurrently, a validated NOT NULL check, and a short transaction that swaps the primary key using the index. Sequences, referencing foreign keys, Java mappings and downstream consumers all need the same change, and we monitor replication lag and WAL throughout, using gh-ost or pt-online-schema-change on MySQL.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
In PostgreSQL, ALTER TABLE ... ALTER COLUMN id TYPE bigint rewrites all 1.5 billion rows under an ACCESS EXCLUSIVE lock, which means hours of downtime, so we do it in stages instead. We add a new bigint column, keep it in sync with a trigger, backfill old rows in small batches while watching replication lag and WAL volume, build a unique index CONCURRENTLY, then swap the primary key in one short transaction with ADD CONSTRAINT ... PRIMARY KEY USING INDEX and rename the columns. Along the way we convert the sequence, every referencing foreign key column, the JPA mappings to Long and every downstream consumer; in MySQL we would use online DDL or gh-ost or pt-online-schema-change.
Why this question is asked
An int primary key overflowing is one of those incidents that is entirely predictable and still catches teams by surprise. A 32-bit signed int stops at 2,147,483,647; when the sequence passes it, every insert fails and the business stops taking orders. We have four months, which is enough to do it safely, but not enough to waste. Interviewers ask this scenario because the naive one-line fix would itself cause an outage, and because the safe path touches the database, the application and the data pipeline. In this answer, we will see why the simple ALTER is dangerous, walk through the staged migration, deal with sequences and foreign keys, update the application, monitor the backfill, and look at the MySQL equivalent.
1Why the One-Line ALTER Is Dangerous
Changing a column from int (4 bytes) to bigint (8 bytes) changes the physical size of every row, so PostgreSQL cannot do it in place. ALTER TABLE orders ALTER COLUMN id TYPE bigint rewrites the whole table and rebuilds every index on it, all while holding an ACCESS EXCLUSIVE lock, the strongest lock, which blocks even plain SELECTs. On 1.5 billion rows with heavy writes, that is hours of total downtime, plus double the disk space during the rewrite and a burst of WAL that replicas must replay.
So the plan is to do the expensive work, copying values and building indexes, in the background with weak locks, and to keep the moment of strong locking down to a sub-second metadata change.
2The Staged Migration Step by Step
Here is the order of operations. Each step is safe to pause, and until the swap, everything is reversible by dropping the new column.
- Add column id_new bigintmetadata only, instant
- Trigger copies id to id_newcovers every new or updated row
- Backfill old rows in batches10,000 rows, pause, watch lag
- Build unique index CONCURRENTLYno write lock, takes hours
- Make id_new NOT NULL via validated CHECKavoids a locked full scan
- Short transaction: swap PK and namesseconds, with lock_timeout
- Clean updrop old column and trigger later
7 steps in order. Play them, or step through them one at a time.
The trigger guarantees that once it exists, no new row is ever left behind, so the backfill only has to chase rows that existed before it. Batching keeps each transaction short, which avoids long row locks, keeps vacuum able to clean up, and lets us pause if replicas fall behind. Building the index CONCURRENTLY takes longer than a normal build, but it allows inserts and updates to continue.
3Swapping the Primary Key in One Short Transaction
Now id_new holds every value, is unique and is known to be not null. The swap is a handful of metadata changes. We set a lock_timeout so that if the ACCESS EXCLUSIVE lock cannot be taken quickly, for example because a long query is running, the transaction gives up instead of making every other query wait behind it, and we simply retry.
Two details deserve attention. First, the sequence: a sequence created for an int column has the type int and its own maximum, so even with a bigint column, nextval would fail at 2,147,483,647 unless we change the sequence type too. If the column was created as an identity column, the steps differ slightly, so check your version and test the exact script on a copy. Second, CASCADE drops the foreign key constraints that reference orders_pkey, which leads to the next problem.
4Foreign Keys and Referencing Tables
Every table that references orders.id, such as order_items.order_id, payments.order_id and shipments.order_id, also has an int column that will overflow as soon as an order id above the int range is inserted. Each of those columns needs the same staged treatment: new bigint column, trigger, batched backfill, index CONCURRENTLY, swap. This is why the four months matter; on large child tables, this can be most of the work.
After the swap, we recreate the foreign keys without a long lock: ALTER TABLE order_items ADD CONSTRAINT ... FOREIGN KEY (order_id) REFERENCES orders(id) NOT VALID, followed by VALIDATE CONSTRAINT, which checks existing rows without blocking writes. Between the CASCADE and the re-creation, the database is not enforcing those references, so we keep that window short and do it in a quiet period.
5Updating the Application and Downstream Consumers
The application changes first, before the database swap. Any Java code that holds the id as an int or Integer will break as soon as a value exceeds 2,147,483,647, so entities use Long, DTOs and APIs use long or a string, and we search the code for casts such as (int) id or Integer.parseInt on ids.
Outside the service, every consumer of the id needs checking: CDC connectors and their Avro or JSON schemas, the data warehouse tables, search indexes, caches keyed by id, and reports. I would list every consumer and get an explicit sign-off from each owner.
6Monitoring the Backfill and the MySQL Equivalent
The backfill writes a new version of 1.5 billion rows, which produces a lot of WAL. I would watch replication lag (pg_stat_replication), WAL generation rate, disk space and table bloat, and have the batch job slow down automatically when lag passes, say, 10 seconds.
In MySQL, ALTER TABLE ... MODIFY id BIGINT is a table copy too, and the INPLACE algorithm does not support a data type change of this kind, so online tools are the usual path. gh-ost and pt-online-schema-change create a shadow table with the new definition, copy rows in chunks, apply ongoing changes through the binary log or triggers, and swap the tables with a quick rename at the end. The principles are the same: copy in the background, throttle on replica lag, and keep the final switch short.
7Follow-up questions
How would you detect the next column close to overflow?
I would run a scheduled check that compares each sequence's last value with its type's maximum, using pg_sequences in PostgreSQL, which shows last_value and max_value, and alert when any sequence passes, say, 50 percent of its range. For columns not fed by sequences, a periodic max(col) on integer key columns does the same. In MySQL, information_schema.TABLES has AUTO_INCREMENT values to compare with the column type. The alert should fire years, not months, before overflow.
8Conclusion
In this answer, we saw that changing the column type directly rewrites 1.5 billion rows under an ACCESS EXCLUSIVE lock, so we migrate in stages: a new bigint column kept in sync by a trigger, a batched backfill, a unique index built concurrently, a validated NOT NULL check, and a short transaction that swaps the primary key using the index. Sequences, referencing foreign keys, Java mappings and downstream consumers all need the same change, and we monitor replication lag and WAL throughout, using gh-ost or pt-online-schema-change on MySQL.
Open with
Running ALTER COLUMN id TYPE bigint directly would rewrite all 1.5 billion rows and rebuild the indexes under an ACCESS EXCLUSIVE lock, which blocks even reads for hours, so I'd do it in stages.
Then, if they want more
First I'd change the application and JPA mappings to Long everywhere and check all consumers like CDC, the warehouse and caches. Then I add an id_new bigint column, which is instant, plus a trigger that copies id into it for new and updated rows.
A background job backfills old rows in batches of maybe 10,000, throttling on replication lag and WAL volume. Then I build a unique index on id_new CONCURRENTLY, and add a CHECK id_new IS NOT NULL as NOT VALID and validate it, so SET NOT NULL later doesn't need a locked scan.
The swap is one short transaction with a lock_timeout: set NOT NULL, drop the old primary key, add the new one with PRIMARY KEY USING INDEX, rename the columns and move the sequence, making sure the sequence itself is converted to bigint.
Every referencing foreign key column needs the same treatment, and the constraints are recreated NOT VALID and then validated. On MySQL I'd use gh-ost or pt-online-schema-change. And I'd add monitoring of sequence headroom so the next one isn't a surprise.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, The SQL Language
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "You must change an orders.id column from int to bigint because it will overflow in about...": https://scrivio-interview-library.netlify.app/databases/sql-fundamentals/48cf017ef1/