Full answer
Schema and sample rows:
CREATE TABLE products (id int PRIMARY KEY, name text);
INSERT INTO products VALUES (1, 'pen');BEGIN; SELECT name FROM products WHERE id = 1;PostgreSQL returns:
name
------
pen
(1 row)In a second session:
SET lock_timeout = '200ms'; ALTER TABLE products ADD COLUMN price int;Result on PostgreSQL 17:
ERROR: canceling statement due to lock timeoutCOMMIT;Result:
COMMITIn a second session:
SET lock_timeout = '200ms'; ALTER TABLE products ADD COLUMN price int; SELECT column_name FROM information_schema.columns WHERE table_name = 'products' ORDER BY ordinal_position;Output:
column_name
-------------
id
name
price
(3 rows)Session A's open transaction holds an ACCESS SHARE lock from its SELECT. The ALTER in session B waits for it, and after 200 ms fails with 'canceling statement due to lock timeout' instead of hanging; without the timeout, every later query on products would have queued behind the ALTER. Once A commits, the same ALTER succeeds instantly, because adding a nullable column only updates the catalog. Migration tooling should set lock_timeout and retry with backoff, and idle_in_transaction_session_timeout helps end forgotten transactions.
CREATE TABLE products (id int PRIMARY KEY, name text);
INSERT INTO products VALUES (1, 'pen');
BEGIN; SELECT name FROM products WHERE id = 1;
-- session B
SET lock_timeout = '200ms'; ALTER TABLE products ADD COLUMN price int;
COMMIT;
-- session B
SET lock_timeout = '200ms'; ALTER TABLE products ADD COLUMN price int; SELECT column_name FROM information_schema.columns WHERE table_name = 'products' ORDER BY ordinal_position;Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
- ALTER TABLE takes an exclusive lock
- It waits behind open transactions
- Queued DDL blocks later queries
- lock_timeout makes migrations fail fast
- Retry with backoff
Common mistakes
- Running migrations without lock_timeout
- Leaving transactions idle in application code
Follow-ups
- Which ALTER TABLE forms take weaker locks?
- How would you find the blocking session?
Tips
- Explain the lock queue