PostgreSQL interview question · Most asked
Which schema changes take heavy locks in PostgreSQL, and how do you avoid outages during migrations?
Summary
Many ALTER TABLE forms take an ACCESS EXCLUSIVE lock, which blocks reads and writes. Even a fast DDL statement can cause an outage if it waits behind a long query, because every new query then queues behind the waiting DDL. Set lock_timeout, retry, and use lock-friendly variants.
Longer Answer
Safe patterns:
SET lock_timeout = '2s';before DDL, and retry on timeout.CREATE INDEX CONCURRENTLYinstead ofCREATE INDEX.- Adding a column with a constant default is instant since PostgreSQL 11 (no table rewrite).
- Adding
NOT NULLor a foreign key: first add aCHECK (col IS NOT NULL) NOT VALIDor the FKNOT VALID(fast), thenVALIDATE CONSTRAINT(takes a weaker lock while scanning). - Changing a column type usually rewrites the table; use expand-and-contract (new column, backfill, switch).
Tools such as squawk lint migrations for these problems.
Key Points
- ACCESS EXCLUSIVE blocks everything.
- Lock queueing turns a waiting DDL into an outage.
- lock_timeout + retry.
- CONCURRENTLY, NOT VALID + VALIDATE, instant defaults.
Explanation
What interviewers look for
Understanding lock queueing. Many outages come from a 'fast' ALTER waiting behind one slow query.
More most-asked PostgreSQL questions
- JSON or JSONB in PostgreSQL, and how do you index JSONB?
- Why do PostgreSQL deployments need connection pooling, and how do PgBouncer's modes differ?
- How does MVCC work in PostgreSQL?
- How do you read EXPLAIN ANALYZE output in PostgreSQL?
- What isolation levels does PostgreSQL provide, and how do they behave?
- What index types does PostgreSQL support, and when do you use each?
- What does VACUUM do, and how does autovacuum work?
- How do you build a job queue on PostgreSQL with SELECT ... FOR UPDATE SKIP LOCKED?