← Back to PostgreSQL, page 5

postgresql-0099 · Hard senior

Plan a zero-downtime rename of a heavily used column from user_name to username.

Use expand and contract: add the new column, write to both (trigger or application), backfill old rows in batches, switch reads to the new column, stop writing the old one, then drop it. Each step is backward compatible with the application versions running at that moment. A direct RENAME is instant in the database but breaks every running application instance that still uses the old name.

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):

  1. Expand: ALTER TABLE users ADD COLUMN username text; (instant, nullable, no default).
  2. Dual write: a trigger copies user_name to username on insert and update, or the new application version writes both.
  3. Backfill in batches: UPDATE users SET username = user_name WHERE id BETWEEN ... AND username IS NULL; with pauses, watching replication lag.
  4. 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.
  5. Switch reads: deploy the version that reads username.
  6. 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