Add a column without locking the table

Sql

On Postgres 11 and later a nullable column with a default is a metadata-only change. Adding NOT NULL afterwards is the part that needs care.

ALTER TABLE orders ADD COLUMN status text DEFAULT 'pending';

-- Backfill in batches, then:
ALTER TABLE orders ADD CONSTRAINT orders_status_not_null
  CHECK (status IS NOT NULL) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT orders_status_not_null;

More in Databases

Random picks