← Back to SQL, page 24

sql-0469 · Hard senior

You must add a NOT NULL column with a default value to a 200-million-row PostgreSQL table. Is that dangerous?

Since PostgreSQL 11, adding a column with a constant (non-volatile) default is a fast metadata change: existing rows return the default without being rewritten, so ADD COLUMN ... NOT NULL DEFAULT 'x' is quick apart from the brief exclusive lock. A volatile default such as random() or clock_timestamp() forces a full table rewrite. Older versions rewrite in all cases.

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, then VALIDATE CONSTRAINT, and in PostgreSQL 12+ SET NOT NULL can 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