A migration that took 40 ms in staging held an ACCESS EXCLUSIVE lock for 25 minutes in production, because the table was 300 GB and the statement rewrote it. Before a DDL statement runs against a large, busy table, answer three questions. Does it rewrite the table? Does it scan the table while holding a strong lock? Can it wait in the lock queue and block everyone behind it? This checklist answers them for the changes teams run most often.
Pre-flight on every migration
- Set
lock_timeoutin the migration session. Nearly everyALTER TABLEform takesACCESS EXCLUSIVE. A short timeout means the DDL gives up rather than queueing behind a long transaction and blocking every reader. - Set
statement_timeoutto a ceiling you are willing to accept. - Check for long transactions first. Any open transaction that touched the table will make your DDL wait.
- Know the table size. A rewrite writes the whole table and every index again, and produces the same amount of WAL. That is disk space on the primary plus lag on every replica.
- Test the exact statement on a production-sized copy and check whether the file node changed (see below).
-- Long transactions that will block DDL
SELECT pid, usename, state, now() - xact_start AS xact_age, left(query, 80) AS query
FROM pg_stat_activity
WHERE xact_start < now() - interval '1 minute'
ORDER BY xact_start;
-- Table + index size
SELECT pg_size_pretty(pg_total_relation_size('public.orders'));
Detect a rewrite before production does
A rewrite gives the table a new file node. Compare the value before and after on a staging copy:
SELECT pg_relation_filenode('public.orders'); -- before
ALTER TABLE public.orders ALTER COLUMN note TYPE text;
SELECT pg_relation_filenode('public.orders'); -- after: changed = rewrite
What each change costs
| Change | Rewrite? | Full scan under strong lock? | Safe pattern |
|---|---|---|---|
ADD COLUMN nullable, no default | No | No | Run as is with lock_timeout |
ADD COLUMN ... DEFAULT <constant> (PG 11+) | No | No | Run as is |
ADD COLUMN ... DEFAULT <volatile> (clock_timestamp(), random(), gen_random_uuid()) | Yes | — | Add nullable, set default, backfill in batches |
ADD COLUMN ... GENERATED ALWAYS AS (...) STORED | Yes | — | Plain column plus trigger, or a virtual generated column on PG 18 |
ALTER COLUMN SET DEFAULT / DROP DEFAULT | No | No | Run as is |
ALTER COLUMN TYPE varchar(n) to larger n or to text | No | No | Run as is |
ALTER COLUMN TYPE int to bigint | Yes, plus index rebuilds | — | New column, trigger, backfill, swap |
ALTER COLUMN SET NOT NULL | No | Yes | CHECK ... NOT VALID, validate, then set (PG 12+) |
ADD CONSTRAINT CHECK | No | Yes | NOT VALID then VALIDATE CONSTRAINT |
ADD FOREIGN KEY | No | Yes, on the referencing table | NOT VALID then VALIDATE CONSTRAINT |
ADD PRIMARY KEY / UNIQUE | No | Builds the index under lock | CREATE UNIQUE INDEX CONCURRENTLY then USING INDEX |
CREATE INDEX | No | Blocks writes for the build | CREATE INDEX CONCURRENTLY |
DROP COLUMN | No (space reclaimed later) | No | Remove from app code first |
RENAME COLUMN / RENAME TABLE | No | No | Expand/contract with a view or both names |
ATTACH PARTITION | No | Scans the new partition | Add a matching CHECK constraint first |
DETACH PARTITION | No | No | DETACH PARTITION ... CONCURRENTLY (PG 14+) |
Safe patterns
NOT NULL without the long scan
On PostgreSQL 12 and later, SET NOT NULL skips the scan if a valid CHECK (col IS NOT NULL) constraint already proves it.
SET lock_timeout = '3s';
ALTER TABLE orders ADD CONSTRAINT orders_customer_nn CHECK (customer_id IS NOT NULL) NOT VALID;
-- Scans, but only takes SHARE UPDATE EXCLUSIVE: reads and writes continue
ALTER TABLE orders VALIDATE CONSTRAINT orders_customer_nn;
ALTER TABLE orders ALTER COLUMN customer_id SET NOT NULL; -- metadata only now
ALTER TABLE orders DROP CONSTRAINT orders_customer_nn;
PostgreSQL 18 also accepts ALTER TABLE orders ADD CONSTRAINT orders_customer_nn NOT NULL customer_id NOT VALID; followed by VALIDATE CONSTRAINT. Use the CHECK method if any environment is still on 17 or earlier.
Foreign keys and check constraints
SET lock_timeout = '3s';
ALTER TABLE orders
ADD CONSTRAINT orders_customer_fk FOREIGN KEY (customer_id)
REFERENCES customers (id) NOT VALID; -- brief lock on both tables
ALTER TABLE orders VALIDATE CONSTRAINT orders_customer_fk;
NOT VALID still enforces the constraint for new and updated rows. Only the check of existing rows is postponed. Validation takes SHARE UPDATE EXCLUSIVE on orders and ROW SHARE on customers, so normal DML continues. Index orders.customer_id before you add the foreign key. Otherwise every delete on customers scans orders.
Primary key or unique constraint
CREATE UNIQUE INDEX CONCURRENTLY orders_ref_uq ON orders (order_ref);
-- Check it is valid before using it
SELECT indisvalid FROM pg_index WHERE indexrelid = 'orders_ref_uq'::regclass;
SET lock_timeout = '3s';
ALTER TABLE orders ADD CONSTRAINT orders_ref_key UNIQUE USING INDEX orders_ref_uq;
For PRIMARY KEY USING INDEX, every key column must already be NOT NULL. If it isn't, the statement runs the SET NOT NULL scan under ACCESS EXCLUSIVE, so use the NOT NULL pattern above first.
Warning
CREATE INDEX CONCURRENTLYandDETACH PARTITION ... CONCURRENTLYcannot run inside a transaction block. Many migration tools wrap each file in a transaction. Turn that off for these files, or the migration fails. If a concurrent build fails, it leaves anINVALIDindex that you must drop.
Changing a column type on a large table
For int to bigint and similar changes that rewrite:
- Add the new column, nullable, with no default.
- Add a trigger that copies the old value into the new column on
INSERTandUPDATE. - Backfill in batches of 5,000–50,000 rows, committing each batch and pausing if replica lag grows.
- Add
NOT NULLwith theCHECK ... NOT VALIDpattern, and build indexesCONCURRENTLY. - In one short transaction with
lock_timeout, rename the columns and drop the trigger.
-- Batched backfill; run repeatedly until it updates 0 rows
UPDATE orders SET id_new = id
WHERE ctid = ANY (ARRAY(SELECT ctid FROM orders WHERE id_new IS NULL LIMIT 10000));
Attaching a partition without a scan
ALTER TABLE orders_2026_12 ADD CONSTRAINT p_chk
CHECK (created_at >= '2026-12-01' AND created_at < '2027-01-01') NOT VALID;
ALTER TABLE orders_2026_12 VALIDATE CONSTRAINT p_chk;
ALTER TABLE orders ATTACH PARTITION orders_2026_12
FOR VALUES FROM ('2026-12-01') TO ('2027-01-01'); -- uses p_chk, no scan
ALTER TABLE orders_2026_12 DROP CONSTRAINT p_chk;
Retry instead of queueing
With a short lock_timeout, the DDL fails fast when it is blocked. Wrap it in a retry loop rather than raising the timeout:
for i in $(seq 1 20); do
psql "$PGURL" -v ON_ERROR_STOP=1 -c "SET lock_timeout = '2s'; ALTER TABLE orders ALTER COLUMN status SET DEFAULT 'new';" && break
echo "attempt $i blocked, retrying"; sleep 5
done
Caution
Don't run
pg_terminate_backendagainst whatever blocks your migration unless you know what the session is doing. Terminating a session rolls back its transaction, and that can be a batch job that has run for hours or a payment in progress.
Watch it while it runs
-- Index builds, including CONCURRENTLY
SELECT pid, phase, blocks_done, blocks_total, tuples_done, tuples_total
FROM pg_stat_progress_create_index;
-- Who is waiting behind your DDL
SELECT pid, pg_blocking_pids(pid) AS blocked_by, wait_event_type, left(query, 60)
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0;
Watch replica lag and free WAL disk space during validation, backfills and anything that rewrites.
Prevent it next time
- Have your migration framework set
lock_timeoutandstatement_timeoutby default. - Add a CI check that rejects
ADD COLUMN ... DEFAULTwith a volatile default,SET NOT NULL,ADD FOREIGN KEYwithoutNOT VALID, and non-concurrentCREATE INDEXon tables above a size threshold. - Keep this table with your migration guidelines and record the PostgreSQL major version each rule depends on.
- Set
idle_in_transaction_session_timeoutfor application roles so a forgotten transaction can't block DDL for hours.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get