Quick revision
The short answer
We split it into steps that never hold a strong lock for long. Add the column as nullable, deploy code that writes it for new rows, backfill the existing 500 million rows in small batches while watching locks, WAL and replication lag, and build the index with CREATE INDEX CONCURRENTLY in a migration configured to run outside a transaction. Finally, add a CHECK (col IS NOT NULL) constraint as NOT VALID, validate it, then set NOT NULL, which can use the validated constraint instead of scanning, with lock_timeout set on every DDL statement.
What to remember
In this answer, we planned a zero-downtime change on a 500-million-row PostgreSQL table. We added the column as nullable, deployed code that writes it for new rows, backfilled existing rows in small throttled batches while watching replication lag, built the index with CREATE INDEX CONCURRENTLY in a non-transactional migration, and enforced NOT NULL through a NOT VALID check constraint, validation and SET NOT NULL, with lock_timeout on every DDL statement.
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.
We split it into steps that never hold a strong lock for long. Add the column as nullable, deploy code that writes it for new rows, backfill the existing 500 million rows in small batches while watching locks, WAL and replication lag, and build the index with CREATE INDEX CONCURRENTLY in a migration configured to run outside a transaction. Finally, add a CHECK (col IS NOT NULL) constraint as NOT VALID, validate it, then set NOT NULL, which can use the validated constraint instead of scanning, with lock_timeout set on every DDL statement.
Why this question is asked
On a small table, adding a NOT NULL column with an index is three statements in one migration. On a 500-million-row table that serves live traffic, the same three statements can lock the table for an hour, generate hundreds of gigabytes of write-ahead log and leave replicas far behind. Interviewers ask this scenario to see whether we know which operations are cheap and which are dangerous in PostgreSQL, and how to order them so the table stays available. In this answer, we will go through the plan step by step: adding the column, writing it for new rows, backfilling, creating the index concurrently, and enforcing NOT NULL without a long lock.
1Why the Simple Version Is Dangerous
Suppose the column is order_region, computed from the customer's address. The naive migration is ALTER TABLE orders ADD COLUMN order_region text NOT NULL, followed by an UPDATE to fill it and CREATE INDEX. Each statement is a problem at this size. A NOT NULL column cannot be added to a table with rows unless it has a default, because existing rows would violate it. A single UPDATE of 500 million rows holds row locks on all of them for the whole transaction, writes a new version of every row, and produces a huge amount of WAL, the write-ahead log that replicas replay. A plain CREATE INDEX blocks every insert, update and delete on the table until the index is built, which can take an hour.
So the plan is about turning each of these into an operation that either takes only a brief lock or runs gradually in the background.
2Add the Column Cheaply
Adding a nullable column without a default only changes the table's metadata, so it is instant regardless of table size. Since PostgreSQL 11, adding a column with a constant default is also instant, because the default is stored in the catalog rather than written into every row. Our value is computed per row, so no constant default is correct; we add it as nullable.
The statement still needs a brief ACCESS EXCLUSIVE lock, so lock_timeout protects the table from the lock queue problem: if a long transaction is holding the table, the migration fails after 3 seconds and is retried, instead of making every query wait behind it.
3Write the Column for New Rows
Next we deploy application code that computes and writes order_region for every new or updated order. From this moment, the set of rows with a missing value can only shrink. If other systems also write to this table, a trigger that computes the value on insert and update covers them too, at the cost of logic living in the database.
4Backfill in Small Batches
Now we fill the existing rows. We do it in batches of a few thousand rows, each in its own short transaction, walking the primary key, so no transaction holds many locks and vacuum can clean up the old row versions as we go.
- Add the column as nullablemetadata only, lock_timeout 3s
- Deploy code that writes itnew and updated rows get a value
- Backfill in batches5,000 rows at a time, watch lag
- CREATE INDEX CONCURRENTLYnon-transactional migration
- Add CHECK ... NOT VALIDbrief lock, no scan
- VALIDATE CONSTRAINTscans without blocking writes
- SET NOT NULL, drop the CHECKuses the validated constraint
7 steps in order. Play them, or step through them one at a time.
Notice the pause and the lag check. 500 million rows in batches of 5,000 is 100,000 batches; at around 150 milliseconds each, the backfill takes about four hours, which is fine for a background job. The job watches replication lag and slows down or pauses when replicas fall behind, and it can be stopped and resumed because the IS NULL condition makes every batch idempotent. Running it as a separate throttled job, not inside a Flyway migration, keeps deployments fast and lets us control the pace.
5Create the Index Concurrently
CREATE INDEX CONCURRENTLY builds the index without blocking inserts, updates and deletes. It scans the table twice and waits for ongoing transactions, so it takes longer than a normal build, but the table stays fully usable. It has one important restriction: it cannot run inside a transaction block, and migration tools normally wrap each migration in a transaction.
Flyway lets a single script run outside a transaction through a script configuration file, and Liquibase has a runInTransaction attribute on the changeSet; check the exact mechanism for your version. The migration must contain only this statement. If the build fails partway, for example because of a lock timeout or a deadlock, PostgreSQL leaves an INVALID index behind, which we drop with DROP INDEX CONCURRENTLY before retrying.
6Enforce NOT NULL Without a Long Lock
A plain ALTER COLUMN SET NOT NULL scans the whole table to check for nulls while holding ACCESS EXCLUSIVE, which for 500 million rows means minutes of blocked traffic. We avoid the long scan under the strong lock by splitting the check from the lock.
NOT VALID means the constraint applies to new writes immediately but existing rows are not checked yet, so adding it is quick. VALIDATE CONSTRAINT then checks the existing rows while holding only SHARE UPDATE EXCLUSIVE, a lock that allows reads and writes. From PostgreSQL 12, SET NOT NULL notices the validated check constraint and skips its own scan, so it needs ACCESS EXCLUSIVE only for a moment. PostgreSQL 18 can also add a NOT NULL constraint as NOT VALID directly; check your version. Each DDL statement keeps lock_timeout, because even a brief lock request can queue behind a long transaction.
7Follow-up questions
Why not add the column with a default and then update it?
A constant default is cheap since PostgreSQL 11, but it would give every existing row a wrong value until the backfill reaches it, and readers could not tell a real value from the placeholder. With a nullable column, null clearly means not yet computed. If a placeholder is acceptable to the business, a default is a valid shortcut.
How do you keep the backfill from hurting production?
Small batches in short transactions, a pause between batches, and a feedback loop on replication lag, database CPU and I/O that slows or pauses the job. Running it at off-peak hours and walking the primary key, so each batch reads a narrow index range, also helps.
Should the backfill run inside Flyway?
Usually not. A Flyway migration that runs for four hours blocks the deployment and cannot easily be paused or throttled. A separate job, started after the column exists and the code writes it, is easier to control. The final NOT NULL migration is then released only after the job reports zero remaining nulls.
8Conclusion
In this answer, we planned a zero-downtime change on a 500-million-row PostgreSQL table. We added the column as nullable, deployed code that writes it for new rows, backfilled existing rows in small throttled batches while watching replication lag, built the index with CREATE INDEX CONCURRENTLY in a non-transactional migration, and enforced NOT NULL through a NOT VALID check constraint, validation and SET NOT NULL, with lock_timeout on every DDL statement.
Open with
I would split it into steps that each take only a brief lock. First, add the column as nullable, which is a metadata change and instant even on 500 million rows; a constant default would also be instant since PostgreSQL 11, but this value is computed per row.
Then, if they want more
Every DDL statement gets lock_timeout of a few seconds so it cannot queue behind a long transaction and block the table. Second, deploy code, or a trigger if other writers exist, that fills the column for new and updated rows.
Third, backfill the existing rows with a separate throttled job, in batches of a few thousand by primary key range, each in its own short transaction, with pauses and a check on replication lag and WAL volume; it is resumable because it only touches rows where the column is null.
Fourth, create the index with CREATE INDEX CONCURRENTLY, which does not block writes but cannot run in a transaction, so that migration is configured as non-transactional, for example executeInTransaction false in Flyway, and if it fails I drop the invalid index and retry.
Finally, NOT NULL: add a CHECK column IS NOT NULL constraint as NOT VALID, validate it, which scans without blocking writes, then SET NOT NULL, which on PostgreSQL 12 and later uses the validated constraint instead of scanning, and drop the check.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- PostgreSQL 11, PostgreSQL 12, PostgreSQL 18
- 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
- Spring Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
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 "Plan a zero-downtime migration to add a NOT NULL column with a computed value to a...": https://scrivio-interview-library.netlify.app/databases/schema-migration/acdf4a76c5/