Full answer
Steps for changing amount from integer dollars to integer cents, or id from int to bigint:
- Expand:
ALTER TABLE t ADD COLUMN amount_cents bigint;(fast, no rewrite, when there is no default). - Dual write: deploy code that writes both columns, or add a trigger that copies values.
- 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. - Verify: compare counts and sums between the columns.
- Switch reads to the new column; add NOT NULL (in PostgreSQL, add a
CHECK ... NOT VALID, thenVALIDATE CONSTRAINT, to avoid a long lock). - 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