How to Migrate a Database Schema Safely
A practical guide to changing a live database schema safely using versioned migrations, backward-compatible steps, backups and rollback plans.
On this page
Application code can be rolled back in seconds by deploying the previous version. A database is different. It holds real data that cannot simply be swapped out, and a careless change to its structure can lock tables, break running code or destroy information.
A schema migration is a controlled change to the structure of a database: adding a column, renaming a table, creating an index. Done carefully, migrations are routine. This guide covers the habits that keep them safe.
Treat Migrations as Code
The first principle is that every schema change is written down in a file, stored in version control and applied by a tool, never typed by hand into a production console.
A migration file usually has two parts: an "up" step that applies the change and a "down" step that reverses it. Tools for this exist in nearly every ecosystem, such as Alembic for Python, Flyway and Liquibase for Java and Rails migrations for Ruby. They keep a table in the database recording which migrations have run, so each one is applied exactly once and in order.
Benefits follow naturally. Every environment can be built from scratch by running the same files. Changes are reviewed like other code. The history of the schema is documented.
Test Before Production
Run migrations in a staging environment that mirrors production. Ideally it holds a realistic copy of the data, with sensitive fields scrubbed. Timing matters: a statement that finishes instantly on a hundred test rows might hold a lock for many minutes on a table with hundreds of millions.
Check, too, that the application works both before and after the change, and that the down step actually restores the old structure.
Always Have a Backup and a Plan
Before touching a production database, confirm that a recent backup exists and that you know how to restore it. A backup you have never restored is only a hope.
Write the rollback plan down before you start. Decide who will watch the deployment, what signals mean trouble and the point at which you will stop and revert.
Make Changes Backward Compatible
During a deployment, the old and new versions of your application often run at the same time, and the database must serve both. A change that breaks the old code will cause errors while the rollout is in progress.
The solution is to split risky changes into several small, compatible steps, often called the expand and contract pattern.
- Expand: add the new structure without removing the old. Add a nullable column or a new table.
- Migrate: deploy code that writes to both old and new, and backfill existing rows.
- Switch: deploy code that reads from the new structure.
- Contract: after confirming everything works, remove the old column or table in a later migration.
Example: Renaming a Column
A direct rename looks harmless but breaks any running code still using the old name. The safe version spreads over several releases.
- Add the new column
full_namealongsidename. - Update the application to write to both columns.
- Copy existing values from
nameintofull_namein small batches. - Switch reads to
full_name. - Stop writing to
name, then drop it in a later release.
It takes longer than a one-line rename, but nobody sees an error.
Watch Out for Locks and Long Operations
Some changes block other queries while they run. Adding an index on a large table, altering a column type or adding a column with a default can lock the table in some databases and versions.
Know what your database does for each operation. Many offer safer variants, such as building an index without blocking writes. For large backfills, process rows in small batches with brief pauses instead of one giant update, so you avoid long transactions and replication lag.
Set a timeout for locks, so a migration that cannot get its lock fails quickly instead of queuing behind other work and stalling everything that follows.
Be Careful With Destructive Changes
Dropping a column or table, or shrinking a column's type, destroys data. Treat these as separate, deliberate steps.
- Remove code references first and deploy.
- Wait long enough to be sure nothing uses the structure.
- Take a backup or export of the data to be removed.
- Run the drop in its own migration.
When adding constraints such as NOT NULL or foreign keys to existing tables, make sure existing data already satisfies them, or the migration will fail partway.
Run Migrations in the Deployment Process
Decide when migrations run: before the new code, during deployment or as a separate manual step. For backward-compatible changes, running them just before releasing the new code works well. Make sure only one process runs migrations at a time, so two servers starting together do not collide. Most tools handle this with a lock.
After the Change
Verify the result. Check that the schema matches expectations, that key queries still perform well and that error rates look normal. Update documentation and diagrams, and remove temporary compatibility code once it is no longer needed.
Frequently Asked Questions
Should every migration have a down step?
It is good practice, because it documents how to reverse a change. Be aware that some changes cannot truly be undone, such as dropping data, so for those the real safety net is a backup and a careful expand and contract approach.
Can I edit a migration that has already been applied?
Avoid it. Other environments have already run the original version, so editing it causes them to disagree. Create a new migration that makes the correction instead.
How do I migrate without downtime?
Break changes into small backward-compatible steps, avoid operations that lock large tables for long periods, backfill data in batches and deploy application changes in between. This lets old and new code run safely together.