← Back to SQL, page 17

sql-0327 · Hard senior

How would you change a column's type on a large, busy table without downtime?

Use expand and contract: add a new column with the new type, write to both columns from the application, backfill old rows in small batches, switch reads to the new column, then stop writing the old one and drop it. A direct ALTER COLUMN TYPE often rewrites the whole table under a lock that blocks traffic.

Full answer

Steps for changing amount from integer dollars to integer cents, or id from int to bigint:

  1. Expand: ALTER TABLE t ADD COLUMN amount_cents bigint; (fast, no rewrite, when there is no default).
  2. Dual write: deploy code that writes both columns, or add a trigger that copies values.
  3. Backfill in batches: UPDATE t SET amount_cents = amount * 100 WHERE id BETWEEN :a AND :b AND amount_cents IS NULL; with pauses, so replicas and locks keep up.
  4. Verify: compare counts and sums between the columns.
  5. Switch reads to the new column; add NOT NULL (in PostgreSQL, add a CHECK ... NOT VALID, then VALIDATE CONSTRAINT, to avoid a long lock).
  6. Contract: stop writing the old column, then drop it in a later release.

Each step is reversible until the last one. Set a lock_timeout for DDL so a blocked ALTER fails fast instead of queuing every query behind it. These are PostgreSQL practices described from experience with its locking rules; they were not run here.

Key points

  • Expand, migrate, contract
  • Add the new column without a rewrite
  • Dual write and backfill in batches
  • Validate constraints separately to shorten locks
  • Set lock_timeout for DDL

Common mistakes

  • Running ALTER COLUMN TYPE on a huge table at peak
  • One giant backfill UPDATE

Follow-ups

  • Why does a queued ALTER block reads?
  • How would you rename a column without downtime?

Tips

  • Explain why each step is reversible