Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 120/ 160
06. Database Design, Normalization & Semi-Structured SQL

Schema Evolution & Zero-Downtime Column Migrations

Evolve schemas with expand/contract migrations that avoid long locks.

AdvancedExpand/Contract · Online DDL3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Change the database in small safe steps: add the new thing, move everything over to it, and remove the old thing last.

Think of it like…

Replacing a bridge while traffic keeps flowing: build the new lanes next to the old ones, move traffic across lane by lane, and only demolish the old bridge when nobody is on it.

Where you’ve seen it

Renaming orders.amount to total_amount: (1) add total_amount; (2) deploy code that writes both columns; (3) backfill total_amount in batches; (4) deploy code that reads total_amount; (5) stop writing amount; (6) drop amount. At no point does a running app version find a column missing.

Words you’ll hear

Expand and contract
Add the new structure, migrate to it, then remove the old one.
Backward-compatible migration
A schema change the currently running code still works with.
Backfill
Filling a new column for existing rows, done in batches.
lock_timeout
Makes a migration give up quickly if it can't get its lock.

Visual diagram

Loading interactive diagram

Theory & example queries

Changes that are safe, and ones that aren't

Additive changes are usually safe: new tables, new nullable columns, columns with a constant default (instant in PostgreSQL 11+), and new indexes built with CREATE INDEX CONCURRENTLY. Old code simply ignores what it doesn't know about.

Breaking changes need expand-and-contract: renaming or dropping columns that running code reads, changing a column's type, splitting a table, or adding NOT NULL to a column that old code leaves empty. Also watch for locking: altering a column type rewrites the table under an exclusive lock, adding a foreign key or CHECK validates every row, and any ALTER queued behind a long-running query blocks all traffic behind it.

Adding constraints without long locks (PostgreSQL)Query example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SET2  lock_timeout = '5s';34ALTER TABLE orders5ADD CONSTRAINT orders_customer_fk FOREIGN KEY (customer_id) REFERENCES customers (id) NOT VALID;67ALTER TABLE orders VALIDATE CONSTRAINT orders_customer_fk;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/7
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative PostgreSQL responses
SET ALTER TABLE ALTER TABLE

Note: Success responses omit client timing; lock duration and whether validation finds invalid rows are workload-dependent.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Additive changes are safe; anything removing or reshaping needs steps.

Running a multi-step migration

Order matters: the database must support both the current and the next code version before you deploy. Expand the schema, deploy code that writes to both old and new structures (or uses a database trigger to sync them), backfill existing rows in batches with short transactions, verify the data matches, switch reads to the new structure, stop writing the old one, and drop it in a later release.

Keep each migration small and reversible, set lock_timeout and retry rather than letting a migration queue behind a long query, and monitor locks while it runs. Feature flags help switch reads gradually. Tools such as gh-ost and pt-online-schema-change (MySQL) and pgroll or pg_repack (PostgreSQL) automate parts of the process for large tables.

A batched backfillQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1UPDATE orders2SET3  total_amount = amount4WHERE5  id IN (6    SELECT7      id8    FROM9      orders10    WHERE11      total_amount IS NULL12    LIMIT13      1000014  );
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/14
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative backfill progress4 sample rows
Representative backfill progress
batchaffected rows
110000
210000
31840
40

Note: Assumes 21,840 rows initially need backfilling; stop when a batch affects 0 rows.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

repeated until it updates 0 rows, with a short pause between batches.

Key takeaway: Expand, dual-write, backfill, switch reads, contract, one deploy at a time.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Migration

Expand the schema

Add the new column, table or index in a way the currently deployed code doesn't notice.

SQL at this step
1ALTER TABLE orders2ADD COLUMN total_amount numeric(12, 2)
What to watch at this step
Old code
unaffected
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

Zero-downtime schema changes alter a live database without stopping the application. The core idea is expand and contract: first make an additive change that both the old and new code can live with (add a column, a table, an index), deploy code that uses it, backfill data in batches, and only when nothing uses the old structure, remove it. Each step is small, reversible and avoids long locks.

Why it matters: Applications deploy many times a day, while old and new versions of the code run side by side during a rollout. A migration that renames a column or rewrites a big table in one step either breaks the running version or locks the table for minutes. Senior backend and DevOps interviews ask how you'd change a schema safely.

When to reach for it

  • Renaming or retyping columns on production tables
  • Adding constraints and indexes to big tables
  • Any migration during continuous deployment

When to avoid or be careful

  • Renaming or dropping columns that running code still uses
  • ALTERs without lock_timeout on busy tables
  • Backfilling millions of rows in a single UPDATE

Ways to change a live schema

One-step ALTER
Best for: Additive, metadata-only changes

Strengths: Simple and immediate.

Watch out: Breaking or rewriting changes cause errors or long locks.

Expand and contract
Best for: Renames, type changes, splits on live systems

Strengths: No downtime; each step reversible.

Watch out: Several deploys and a backfill to coordinate.

Online schema-change tools
Best for: Rewriting very large tables (especially MySQL)

Strengths: Copy and swap tables in the background.

Watch out: Extra tooling, disk space and operational risk.

Interview signals & numbers to know

When this topic comes up

  • “How do you rename a column without downtime?”
  • “A migration locked the table during deploy”
  • Continuous deployment with database changes
  • Rolling deploys
  • Backfills

Benchmarks & rules of thumb

6 -
steps for a safe rename
10,000 -
a typical backfill batch size
CONCURRENTLY -
index builds without blocking writes

Common mistakes & follow-ups

Common interview mistakes

  • Renaming a column in one migration, so pods still running the old code start failing immediately.
  • Adding a foreign key to a huge table without NOT VALID and blocking writes while it validates.
  • Dropping the old column in the same release that switched reads, leaving no rollback path.

Likely interviewer follow-ups

  • Walk me through renaming a heavily used column with zero downtime.
  • Why must migrations be compatible with both the old and new code?
  • How would you add an index to a 500-million-row table safely?
Interview tip: Walk through the rename example step by step and mention lock_timeout and CONCURRENTLY. It shows you've shipped migrations to production, not just written them.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Schema Evolution & Zero-Downtime Column Migrations with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Temporal Tables & System-Versioned History Tracking
Next topic
How Databases Store Data on Disk (Pages, Blocks, Heap, B-Trees)