Renaming a Database Column Without Downtime
My earlier posts kept saying "expand and contract" without ever showing it end to end. This one does. I'll rename users.fullname to users.display_name on a live PostgreSQL database, one safe step at a time. The sequence works on any database, but the SQL and locking details below are PostgreSQL. TL;DR: never rename in one step. Add the new column, dual-write, backfill in batches, verify, switch…
This guide outlines a method for renaming a database column on a live PostgreSQL database without causing any downtime. The key steps are:
1. Add the new column (display_name) to the table with a nullable type. This is done during a migration, without modifying existing data.
2. Dual-write all writes to both the old fullname column and the new display_name column. This ensures data consistency during the transition period.
3. Backfill the display_name column by updating rows where display_name is null, using the existing fullname values. This is done in batches to avoid locking the entire table for too long.
4. Verify that every row now has a value in the display_name column, matching the original fullname values. This is done by running a verification query.
5. Switch reads to use the new display_name column. The old app code continues to write to both columns.
6. Stop writing to the old fullname column and only write to display_name. The old column can be dropped in a separate migration step.
7. Drop the old fullname column. This step is only performed after all other steps have been completed successfully. It requires a lock timeout to prevent blocking other queries.
The guide emphasizes the importance of testing each step carefully, rolling back if necessary, and ensuring that background jobs, cron scripts and other processes are updated to work with the new column name. By incrementally implementing the rename, it's possible to avoid long periods of downtime and maintain data integrity during the transition.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to