Full answer
Why not just rename: ALTER TABLE ... RENAME COLUMN takes a brief exclusive lock and is instant, but during a rolling deploy, old application instances still query user_name and fail until they are replaced.
Steps (illustrative SQL, not run here):
- Expand:
ALTER TABLE users ADD COLUMN username text;(instant, nullable, no default). - Dual write: a trigger copies user_name to username on insert and update, or the new application version writes both.
- Backfill in batches:
UPDATE users SET username = user_name WHERE id BETWEEN ... AND username IS NULL;with pauses, watching replication lag. - Constraints and indexes:
CREATE UNIQUE INDEX CONCURRENTLY ... (username), and NOT NULL via a CHECK (username IS NOT NULL) NOT VALID, VALIDATE, then SET NOT NULL, which can use the validated check to avoid a full scan. - Switch reads: deploy the version that reads username.
- Contract: stop writing user_name, drop the trigger, and finally drop the column in a later release.
Alternative for small teams: create a view or a generated column alias during the transition. Whatever the method, set lock_timeout on every DDL step, run each step as its own deploy, and keep each one reversible until the final drop.
Key points
- Direct renames break running app versions
- Expand, dual-write, backfill, switch, contract
- Backfill in batches
- Build indexes concurrently and validate constraints separately
- Keep steps reversible
Common mistakes
- Renaming during a rolling deploy
- Backfilling in one huge UPDATE
Follow-ups
- How does SET NOT NULL use a validated CHECK constraint?
- How would you handle a column type change the same way?
Tips
- List the phases