Learn SQL
-- security.migrations_expand_contract

Zero-Downtime Migrations in SQL

Expand-contract: compatible steps, tested rollbacks

--concept

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.

--how it works
1

Version everything

One up/down file per change — reviewable, runnable, revertible.

2

Expand compatibly

Nullable adds, NOT VALID constraints — old + new code coexist.

3

Backfill + validate

Batched fills, then VALIDATE/SET NOT NULL — no long locks.

4

Contract after clients

Drop old only when readers moved; renames via shims; CI on copies.

--visualization
EXPANDBACKFILLCONTRACT
Stage 1 / 3
Expand: ADD nullable / NOT VALID — old + new code coexist.
--example
query.sql
1-- expand:
2ALTER TABLE users ADD COLUMN email_v2 CITEXT;
3-- contract (after clients move):
4-- ALTER TABLE users DROP COLUMN email;
Result
phaserule
expandnullable adds first
contractold 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.

--variants

Zero-downtime rename

Shim bridges old and new names.

query.sql
1-- expand: ADD email_v2 + shim view/trigger
2-- migrate clients
3-- contract: DROP old email
Result
phasestate
expandboth names live
contractold drops last
1Dual-write shim keeps versions compatible.
2Client rollout advances independently.
3Contract is a cleanup, not a flag day.

CI on copies

Up + down proven before prod.

query.sql
1-- CI: migrate up → seed → assert → migrate down → assert empty
Result
directionproof
upproven
downproven
1Dirty-data failures surface on copies.
2Down path rehearsed, not hoped.
3Off-peak scheduled for rewrites.
--key facts
Expand-contractzero-downtime mantra
Versionedevery change a file, up+down
CI on copiesmigrations proven before prod
--use cases
Live renames/type changes without flag days
Dirty-table constraint adoption
--under the hood
NOT VALID + VALIDATE splits catalog lock from validating scan — the low-lock pattern.
Backfill in keyset batches to keep replicas close during expands.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Take the queries you just visualized and see the data structures that power real databases.