Scrivio Interview library
CodingIntermediate7 min read · updated 12 November 2026

You must add an index and a NOT NULL foreign key column to a 500 GB PostgreSQL table that serves traffic around the clock. Write the migration steps that avoid long blocking locks, and note which steps cannot run inside a transaction.

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.

SQL
ALTER TABLE big ADD COLUMN customer_id bigint NOT NULL DEFAULT 0; -- fast metadata change, but 0 is a fake value
ALTER TABLE big ADD CONSTRAINT big_customer_fk
FOREIGN KEY (customer_id) REFERENCES customer (id); -- scans 500 GB to check every row, blocks writes
CREATE INDEX big_customer_idx ON big (customer_id); -- reads 500 GB, blocks all writes until done

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.

SQL
SET lock_timeout = '3s';
ALTER TABLE big ADD COLUMN customer_id bigint; -- milliseconds once the lock is granted
-- Backfill job, repeated until it updates 0 rows; each run is its own transaction
UPDATE big b SET customer_id = o.customer_id
FROM legacy_owner o
WHERE b.id = o.big_id
AND b.id IN (SELECT id FROM big
WHERE customer_id IS NULL AND id > :last_id
ORDER BY id LIMIT 5000); -- UPDATE 5000
-- the job remembers the highest id it processed as :last_id, pauses briefly, and repeats

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.

SQL
SET lock_timeout = '3s';
CREATE INDEX CONCURRENTLY IF NOT EXISTS big_customer_idx ON big (customer_id);
-- may take an hour on 500 GB; writes continue meanwhile
-- After a failure, find and remove the leftover:
SELECT c.relname FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid
WHERE NOT i.indisvalid; -- big_customer_idx
DROP INDEX CONCURRENTLY big_customer_idx; -- also outside a transaction

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.

SQL
SET lock_timeout = '3s';
ALTER TABLE big ADD CONSTRAINT big_customer_fk
FOREIGN KEY (customer_id) REFERENCES customer (id) NOT VALID; -- milliseconds
ALTER TABLE big VALIDATE CONSTRAINT big_customer_fk; -- scans the table, writes keep running
-- ERROR here means some backfilled value is wrong: fix the rows, run VALIDATE again

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.

SQL
SET lock_timeout = '3s';
ALTER TABLE big ADD CONSTRAINT big_customer_nn
CHECK (customer_id IS NOT NULL) NOT VALID; -- milliseconds
ALTER TABLE big VALIDATE CONSTRAINT big_customer_nn; -- scans, writes keep running
ALTER TABLE big ALTER COLUMN customer_id SET NOT NULL; -- brief lock, no scan: the check proves it
ALTER TABLE big DROP CONSTRAINT big_customer_nn; -- the check is now redundant
Each step and the lock it holds
StepLock on bigDurationIn a transaction?
ADD COLUMN customer_id bigintACCESS EXCLUSIVEmillisecondsyes
Backfill in batchesrow locks per batchhours, in small piecesone per batch
CREATE INDEX CONCURRENTLYSHARE UPDATE EXCLUSIVElong, writes allowedno, never
ADD FOREIGN KEY ... NOT VALIDSHARE ROW EXCLUSIVEmillisecondsyes
VALIDATE CONSTRAINT (FK and CHECK)SHARE UPDATE EXCLUSIVElong, writes allowedyes
SET NOT NULL after a valid CHECKACCESS EXCLUSIVEmillisecondsyes
Only the long steps scan the table, and those hold locks that let traffic continue.

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.

Java
V41__add_customer_id.sql SET lock_timeout = '3s'; ALTER TABLE big ADD COLUMN customer_id bigint;
(deploy code that writes customer_id, run the backfill job to completion)
V42__index_customer_id.sql SET lock_timeout = '3s'; CREATE INDEX CONCURRENTLY IF NOT EXISTS ...
V42__index_customer_id.sql.conf executeInTransaction=false
V43__customer_fk.sql ADD CONSTRAINT ... NOT VALID; VALIDATE CONSTRAINT ...
V44__customer_not_null.sql ADD CHECK ... NOT VALID; VALIDATE; SET NOT NULL; DROP CONSTRAINT

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.

What to say in the interviewAbout 80 seconds aloud

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.
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/