Full answer
Fast path (PostgreSQL 11+):
text
SET lock_timeout = '3s';
ALTER TABLE orders ADD COLUMN channel text NOT NULL DEFAULT 'web';The default is stored in the catalog, and existing rows read it until they are next updated. The lock is still ACCESS EXCLUSIVE, so a lock timeout and retry protect against waiting behind long transactions.
Slow cases:
- Volatile defaults (
DEFAULT gen_random_uuid(),clock_timestamp()) rewrite every row. - Adding NOT NULL later to an existing column requires a scan; use
ADD CONSTRAINT ... CHECK (col IS NOT NULL) NOT VALID, thenVALIDATE CONSTRAINT, and in PostgreSQL 12+SET NOT NULLcan use that validated check to skip the scan. - Changing a column's type usually rewrites.
For SQLite, ALTER TABLE ADD COLUMN with a constant default is also a quick schema change; NOT NULL requires a non-NULL default. These PostgreSQL details are stated from documentation, not run here.
Key points
- Constant defaults are metadata-only in PostgreSQL 11+
- Volatile defaults rewrite the table
- The ALTER still needs a brief exclusive lock
- NOT VALID then VALIDATE avoids long locks for NOT NULL on existing columns
Common mistakes
- Assuming every ADD COLUMN rewrites the table
- Using a volatile default on a huge table
Follow-ups
- How would you backfill a computed value instead?
- Which ALTER operations still rewrite?
Tips
- Separate constant from volatile defaults