Zero-Downtime Migrations in SQL
Expand-contract: compatible steps, tested rollbacks
Versioned migration files (up/down), expand-then-contract for compatibility (add nullable → backfill → constrain → drop old), backward-compatible steps for zero-downtime deploys, tested rollbacks, CI running migrations on copies. App and schema deploy in lockstep-safe order: expand first, contract after clients move. Renames via view/alias shims.
Version everything
One up/down file per change — reviewable, runnable, revertible.
Expand compatibly
Nullable adds, NOT VALID constraints — old + new code coexist.
Backfill + validate
Batched fills, then VALIDATE/SET NOT NULL — no long locks.
Contract after clients
Drop old only when readers moved; renames via shims; CI on copies.
1-- expand:2ALTER TABLE users ADD COLUMN email_v2 CITEXT;3-- contract (after clients move):4-- ALTER TABLE users DROP COLUMN email;
| phase | rule |
|---|---|
| expand | nullable adds first |
| contract | old drops after clients move |
Old code writes email, new code reads email_v2 via shim — both live during rollout. Big-bang renames break half the fleet; staged compatibility never does.
Zero-downtime rename
Shim bridges old and new names.
1-- expand: ADD email_v2 + shim view/trigger2-- migrate clients3-- contract: DROP old email
| phase | state |
|---|---|
| expand | both names live |
| contract | old drops last |
CI on copies
Up + down proven before prod.
1-- CI: migrate up → seed → assert → migrate down → assert empty
| direction | proof |
|---|---|
| up | proven |
| down | proven |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.