Quick revision
The short answer
We split the change into small steps that each hold a strong lock only for milliseconds: add the column as nullable, backfill it in batches, build the index with CREATE INDEX CONCURRENTLY, add the foreign key and a NOT NULL check as NOT VALID, validate them under weaker locks, and finally SET NOT NULL, which can skip the table scan thanks to the validated check. The concurrent index build cannot run inside a transaction, so it gets its own non-transactional migration, and every step runs with a short lock_timeout.
What to remember
In this answer, we turned one dangerous migration into a sequence of safe steps on a 500 GB table. We added the column as nullable, backfilled it in small batches, built the index concurrently outside a transaction and cleaned up any invalid leftover, added the foreign key and a NOT NULL check as NOT VALID and validated them under locks that allow writes, and then used the validated check to make SET NOT NULL instant. Every step runs with a short lock_timeout, and the concurrent index lives in its own non-transactional Flyway migration.
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 the change into small steps that each hold a strong lock only for milliseconds: add the column as nullable, backfill it in batches, build the index with CREATE INDEX CONCURRENTLY, add the foreign key and a NOT NULL check as NOT VALID, validate them under weaker locks, and finally SET NOT NULL, which can skip the table scan thanks to the validated check. The concurrent index build cannot run inside a transaction, so it gets its own non-transactional migration, and every step runs with a short lock_timeout.
Why this question is asked
On a small table, adding an indexed, required foreign key column is one migration of three lines. On a 500 GB table that serves traffic all day, the same three lines would block writes for hours, because two of them scan the whole table while holding a lock that blocks writes, and the third only looks fast because it invents a value. Interviewers ask this to see whether we know which PostgreSQL operations are cheap, which are expensive, and how to turn one expensive change into a sequence of cheap ones. In this answer, we will see why the naive migration fails, then write each step with the lock it takes, and finally package the steps for Flyway, noting which ones must run outside a transaction.
1Why the Naive Migration Blocks for Hours
Here is what we would write for a small table, and what each line costs on 500 GB.
A foreign key, the rule that every customer_id must exist in customer, is checked against every existing row while holding a lock that blocks writes. A plain CREATE INDEX takes a SHARE lock that blocks every write for the whole build, perhaps an hour here. And DEFAULT 0 invents a value that violates the foreign key. Each problem has a PostgreSQL feature that avoids it.
2Add the Column as Nullable, Then Backfill in Batches
Adding a nullable column with no default is a metadata-only change: PostgreSQL records the column in its catalog and existing rows simply read as NULL. It still needs an ACCESS EXCLUSIVE lock, but only for milliseconds, so we set lock_timeout to make sure it does not queue in front of traffic if something else holds a lock on the table.
The backfill runs in batches of a few thousand rows, each its own short transaction, from a job rather than the migration, because one UPDATE of 500 GB would lock every row until commit, produce a burst of WAL (the write-ahead log replicas replay) and leave millions of dead row versions.
The application must start writing customer_id for new rows before the backfill, or it never catches up.
3Build the Index Concurrently
CREATE INDEX CONCURRENTLY builds the index while allowing inserts, updates and deletes. It takes a SHARE UPDATE EXCLUSIVE lock, which does not conflict with normal writes. The price is that it scans the table twice and waits for older transactions to finish, so it takes longer than a normal build, and it cannot run inside a transaction block, because it commits internally between its phases.
If it fails, it leaves an index marked INVALID, unused by queries but still updated on every write, so we drop it and build again.
We build this index before the foreign key because PostgreSQL does not index a referencing column automatically, and without it every delete from customer would scan big.
4Add the Foreign Key as NOT VALID, Then Validate It
A NOT VALID constraint is enforced for new and changed rows but skips existing ones, so its SHARE ROW EXCLUSIVE lock on both tables is brief. VALIDATE CONSTRAINT then checks old rows under SHARE UPDATE EXCLUSIVE on big, which allows reads and writes.
So the long scan does not block traffic. NULL values pass a foreign key check, so NOT NULL is a separate step.
5Make the Column NOT NULL Without a Long Lock
SET NOT NULL normally scans the whole table under ACCESS EXCLUSIVE to prove that no row is NULL, which would block everything. Since PostgreSQL 12, it skips that scan if a valid CHECK constraint already proves the column is not null. So we use the same NOT VALID and VALIDATE pattern with a CHECK constraint, and then SET NOT NULL becomes a quick catalog change.
| Step | Lock on big | Duration | In a transaction? |
|---|---|---|---|
| ADD COLUMN customer_id bigint | ACCESS EXCLUSIVE | milliseconds | yes |
| Backfill in batches | row locks per batch | hours, in small pieces | one per batch |
| CREATE INDEX CONCURRENTLY | SHARE UPDATE EXCLUSIVE | long, writes allowed | no, never |
| ADD FOREIGN KEY ... NOT VALID | SHARE ROW EXCLUSIVE | milliseconds | yes |
| VALIDATE CONSTRAINT (FK and CHECK) | SHARE UPDATE EXCLUSIVE | long, writes allowed | yes |
| SET NOT NULL after a valid CHECK | ACCESS EXCLUSIVE | milliseconds | yes |
PostgreSQL 18 also accepts NOT NULL constraints marked NOT VALID, removing the helper CHECK; check your version. The CHECK pattern works from version 12.
6Packaging the Steps for Flyway
Each step is its own versioned migration, so a retry starts where it stopped. Flyway wraps migrations in a transaction, where CREATE INDEX CONCURRENTLY fails, so we mark that script non-transactional with a script configuration file. Recent Flyway versions may detect this themselves; being explicit is safer.
In Liquibase the equivalent is runInTransaction="false" on the changeset. V43 and V44 combine a quick step and a long validation in one transaction; to release the brief lock before the scan, split them too. A retry of V42 should first drop any INVALID index of that name.
7Follow-up questions
How does MySQL 8 online DDL (ALGORITHM=INSTANT, INPLACE) compare?
MySQL 8 can add a column with ALGORITHM=INSTANT, a metadata-only change similar to PostgreSQL's, and since 8.0.29 at any position. Adding a secondary index uses ALGORITHM=INPLACE, LOCK=NONE, which lets reads and writes continue during the build, but it still needs a brief exclusive metadata lock at the start and end, so a long transaction can block it just as in PostgreSQL, and lock_wait_timeout should be short. MySQL has no NOT VALID; adding a foreign key in place needs foreign_key_checks=0, so we verify existing rows ourselves. For huge tables, gh-ost or pt-online-schema-change copy the table in the background.
What happens to writes during VALIDATE CONSTRAINT?
They continue. VALIDATE takes SHARE UPDATE EXCLUSIVE on the table, which conflicts only with other schema changes, VACUUM and concurrent index builds on that table. New rows were already checked from the moment the NOT VALID constraint was added, so validation only has to look at old rows.
8Conclusion
In this answer, we turned one dangerous migration into a sequence of safe steps on a 500 GB table. We added the column as nullable, backfilled it in small batches, built the index concurrently outside a transaction and cleaned up any invalid leftover, added the foreign key and a NOT NULL check as NOT VALID and validated them under locks that allow writes, and then used the validated check to make SET NOT NULL instant. Every step runs with a short lock_timeout, and the concurrent index lives in its own non-transactional Flyway migration.
Open with
On a 500 GB table I avoid any step that scans or rewrites the table while holding a lock that blocks writes. So I split it up. First, ALTER TABLE ADD COLUMN customer_id bigint, nullable with no default, which is metadata only and needs its exclusive lock for milliseconds, with lock_timeout set to a few seconds so it never queues in front of traffic.
Then, if they want more
Then the application writes the column and a job backfills old rows in small batches. Next, CREATE INDEX CONCURRENTLY on customer_id. It allows writes, but it cannot run inside a transaction block, so in Flyway it is a separate migration with executeInTransaction=false, and if it fails it leaves an invalid index that I must drop before retrying.
Then I add the foreign key with NOT VALID, which is a brief lock, and run VALIDATE CONSTRAINT, which scans under a lock that still allows reads and writes.
For NOT NULL, I add CHECK customer_id IS NOT NULL as NOT VALID, validate it, and then SET NOT NULL, which since PostgreSQL 12 uses the valid check to skip the scan, and finally drop the check. So the only non-transactional step is the concurrent index, and every step has a short lock_timeout and a retry.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- MySQL 8, 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
- PostgreSQL documentation, MySQL reference manual
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 add an index and a NOT NULL foreign key column to a 500 GB PostgreSQL table...": https://scrivio-interview-library.netlify.app/databases/database-locking/2a21579c04/