Schema Migrations

Updated · 18 min read
mediumPostgreSQL 18sqlmigrationsschema-changeszero-downtimedevopsinterview

A schema migration is a small, numbered SQL file that moves a database's structure from one version to the next. Adding a column, creating an index or renaming a table are all migrations. Instead of someone typing ALTER TABLE by hand on the production server, every change is written down once, reviewed like code, kept in version control, and applied in the same order on every database: a developer's laptop, the test server and production. In this lesson, we will build the table that remembers which migrations ran, see why PostgreSQL can run a whole migration as one transaction, rename a column without breaking the running app (expand, migrate, contract), and learn which changes are quick and which lock or rewrite a big table.

In One Minute

  • A migration is a versioned file (V3__add_currency_to_payments.sql); files run in order, each exactly once.
  • A migrations table in the database records which versions have run.
  • In PostgreSQL most schema changes are transactional: a failed migration leaves nothing behind.
  • To change something the running app depends on, use expand, migrate, contract across several releases.
  • Never edit a migration that has already run. Write a new one.

Migration Files

A migration tool keeps a folder of SQL files, applies the ones a database hasn't seen yet, in version order, and records each one. Here is what the Fee Tracker's folder might look like:

text
migrations/
  V1__create_core_tables.sql        -- cities, students, courses, enrollments, payments
  V2__add_email_unique.sql
  V3__add_currency_to_payments.sql
  V4__index_payments_paid_on.sql

The naming style above, V<version>__<description>.sql with two underscores, is Flyway's. Other popular tools work the same way with their own names: Liquibase and Flyway in Java, Alembic in Python, Prisma Migrate and Knex in Node.js, and the migrations built into Rails and Django. When the app is deployed, the tool runs every file newer than what the database has, in order.

RuleWhy
One change per file, with a clear nameReviewers see exactly what changes
Files run in version order, onceEvery database ends up identical
Applied files are never editedDatabases that already ran them would differ from new ones
Migrations live with the app codeThe code and the schema it needs ship together

The Migrations Table

The tool knows what has run because it keeps a table of applied versions inside the database itself. A minimal version, written by hand:

SQL▶ Try it
CREATE TABLE schema_migrations (
  version     INTEGER     PRIMARY KEY,
  description TEXT        NOT NULL,
  applied_on  DATE        NOT NULL
);
 
INSERT INTO schema_migrations VALUES
  (1, 'create core tables', '2025-08-01'),
  (2, 'add email unique',   '2025-08-15');
 
SELECT version, description, applied_on
FROM schema_migrations
ORDER BY version;
Output
CREATE TABLE
 
INSERT 0 2
 
 version |    description     | applied_on
---------+--------------------+------------
       1 | create core tables | 2025-08-01
       2 | add email unique   | 2025-08-15
(2 rows)

Explanation: The primary key on version makes it impossible to record the same migration twice. Before running, the tool reads max(version) (2 here) and applies only the files after it. Real tools store more, such as a checksum of each file's contents, who ran it, and how long it took. Flyway's table is called flyway_schema_history, Prisma's _prisma_migrations, and Rails calls its table schema_migrations, like ours.

One Migration, One Transaction

In PostgreSQL, statements such as CREATE TABLE, ALTER TABLE and CREATE INDEX can run inside a transaction, so a migration can be all-or-nothing. The migration and the row that records it go in together. Here is migration 3 with a typo in its last statement:

SQL▶ Try it
CREATE TABLE schema_migrations (
  version INTEGER PRIMARY KEY, description TEXT NOT NULL, applied_on DATE NOT NULL
);
 
BEGIN;
ALTER TABLE payments ADD COLUMN currency CHAR(3) NOT NULL DEFAULT 'USD';
ALTER TABLE paymnets ADD CONSTRAINT payments_currency_check CHECK (currency = 'USD');
INSERT INTO schema_migrations VALUES (3, 'add currency to payments', '2026-01-05');
COMMIT;
 
SELECT count(*) AS currency_columns
FROM information_schema.columns
WHERE table_name = 'payments' AND column_name = 'currency';
 
SELECT count(*) AS recorded FROM schema_migrations;
Output
CREATE TABLE
 
BEGIN
 
ALTER TABLE
 
ERROR:  relation "paymnets" does not exist
 
ERROR:  current transaction is aborted, commands ignored until end of transaction block
 
ROLLBACK
 
 currency_columns
------------------
                0
(1 row)
 
 recorded
----------
        0
(1 row)

Explanation: The misspelled paymnets fails, which aborts the transaction. The INSERT is refused, and COMMIT is reported as ROLLBACK: PostgreSQL throws away the whole migration, including the currency column that was already added. The database is exactly as it was, with no half-applied change and no record of version 3, so the fixed file can simply run again.

Four migration files; the database has recorded versions 1 and 2, so the tool runs 3 and 4 in order, each in its own transaction

Expand, Migrate, Contract

Expand, migrate, contract changes a schema in small, backward-compatible steps, so the old and new versions of the app can both run while the change rolls out. Suppose we want to rename students.phone to mobile_phone. ALTER TABLE students RENAME COLUMN phone TO mobile_phone is instant, but the moment it runs, every running copy of the app that still says phone starts failing. Most apps deploy gradually, so for a while old and new code run side by side.

The safe way takes several steps:

StepDatabase changeApp release
1. ExpandAdd mobile_phone; a trigger keeps the two columns in syncOld app keeps using phone
2. MigrateCopy existing values into mobile_phoneNew app reads and writes mobile_phone
3. ContractDrop the trigger and the old phone columnOnly the new app runs

Step 1, expand. Add the new column and a trigger that copies whichever column a statement changed into the other one:

SQL▶ Try it
ALTER TABLE students ADD COLUMN mobile_phone VARCHAR(20);
 
CREATE FUNCTION students_sync_phone() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
  IF TG_OP = 'INSERT' THEN
    NEW.mobile_phone := COALESCE(NEW.mobile_phone, NEW.phone);
    NEW.phone        := COALESCE(NEW.phone, NEW.mobile_phone);
  ELSIF NEW.phone IS DISTINCT FROM OLD.phone THEN
    NEW.mobile_phone := NEW.phone;            -- the old app changed phone
  ELSIF NEW.mobile_phone IS DISTINCT FROM OLD.mobile_phone THEN
    NEW.phone := NEW.mobile_phone;            -- the new app changed mobile_phone
  END IF;
  RETURN NEW;
END $$;
 
CREATE TRIGGER students_sync_phone
BEFORE INSERT OR UPDATE ON students
FOR EACH ROW EXECUTE FUNCTION students_sync_phone();
 
SELECT student_id, first_name, phone, mobile_phone
FROM students
ORDER BY student_id;
Output
ALTER TABLE
 
CREATE FUNCTION
 
CREATE TRIGGER
 
 student_id | first_name |     phone      | mobile_phone
------------+------------+----------------+--------------
        101 | Srihitha   | (415) 555-0142 | NULL
        102 | Advitha    | (415) 555-0178 | NULL
        103 | Navika     | NULL           | NULL
(3 rows)

Explanation: The new column exists but is empty (NULL) for the three existing students: the trigger only acts on rows written from now on. Adding a nullable column with no default doesn't rewrite the table, so this step is quick even on a large table.

Step 2, migrate. Copy the old values across. Updating each row also fires the trigger, which is fine: it sees mobile_phone change and copies the same value back to phone. Then show that writes from both versions of the app stay in sync:

SQL▶ Try it
ALTER TABLE students ADD COLUMN mobile_phone VARCHAR(20);
 
CREATE FUNCTION students_sync_phone() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
  IF TG_OP = 'INSERT' THEN
    NEW.mobile_phone := COALESCE(NEW.mobile_phone, NEW.phone);
    NEW.phone        := COALESCE(NEW.phone, NEW.mobile_phone);
  ELSIF NEW.phone IS DISTINCT FROM OLD.phone THEN
    NEW.mobile_phone := NEW.phone;
  ELSIF NEW.mobile_phone IS DISTINCT FROM OLD.mobile_phone THEN
    NEW.phone := NEW.mobile_phone;
  END IF;
  RETURN NEW;
END $$;
 
CREATE TRIGGER students_sync_phone
BEFORE INSERT OR UPDATE ON students
FOR EACH ROW EXECUTE FUNCTION students_sync_phone();
 
-- Backfill: copy existing values
UPDATE students SET mobile_phone = phone
WHERE mobile_phone IS DISTINCT FROM phone;
 
-- The old app gives Navika a phone number
UPDATE students SET phone = '(214) 555-0163' WHERE student_id = 103;
 
-- The new app changes Advitha's number
UPDATE students SET mobile_phone = '(415) 555-0190' WHERE student_id = 102;
 
SELECT student_id, first_name, phone, mobile_phone
FROM students
ORDER BY student_id;
Output
ALTER TABLE
 
CREATE FUNCTION
 
CREATE TRIGGER
 
UPDATE 2
 
UPDATE 1
 
UPDATE 1
 
 student_id | first_name |     phone      |  mobile_phone
------------+------------+----------------+----------------
        101 | Srihitha   | (415) 555-0142 | (415) 555-0142
        102 | Advitha    | (415) 555-0190 | (415) 555-0190
        103 | Navika     | (214) 555-0163 | (214) 555-0163
(3 rows)

Explanation: The backfill updated the two students who had a phone; Navika's NULL already matched, since IS DISTINCT FROM treats two NULLs as equal. After that, a change made through either column shows up in both, so old and new app servers see the same data. On a table with millions of rows, run the backfill in batches (for example 10,000 rows per UPDATE, by key range) so no single transaction locks rows or grows the log for minutes.

Step 3, contract. Once no running code uses phone, remove it and the trigger:

SQL▶ Try it
ALTER TABLE students ADD COLUMN mobile_phone VARCHAR(20);
UPDATE students SET mobile_phone = phone;
 
-- The contract migration, released after every app server uses mobile_phone
ALTER TABLE students DROP COLUMN phone;
 
SELECT student_id, first_name, mobile_phone
FROM students
ORDER BY student_id;
Output
ALTER TABLE
 
UPDATE 3
 
ALTER TABLE
 
 student_id | first_name |  mobile_phone
------------+------------+----------------
        101 | Srihitha   | (415) 555-0142
        102 | Advitha    | (415) 555-0178
        103 | Navika     | NULL
(3 rows)

Explanation: This example starts from a copied mobile_phone so it can run on its own; in the real sequence the contract migration would also run DROP TRIGGER students_sync_phone ON students and DROP FUNCTION students_sync_phone() before dropping the column. Dropping a column is quick in PostgreSQL: the column is marked as gone and its space is reclaimed later. The rename took three migrations and at least two app releases, but at no point did running code look for a column that wasn't there.

Renaming phone to mobile_phone in three steps, with the real column values after each one

Quick Changes and Slow Changes

Some schema changes finish in milliseconds; others lock the table or rewrite every row, which can stop a busy app for minutes. It depends on the change and the database version. A real check in PostgreSQL: each table is stored in a file, and pg_relation_filenode() shows which one. A change that rewrites the table moves it to a new file.

SQL▶ Try it
CREATE TEMP TABLE file_before AS
SELECT pg_relation_filenode('payments') AS n;
 
-- A constant default: stored once, no rewrite (PostgreSQL 11 and later)
ALTER TABLE payments ADD COLUMN currency CHAR(3) NOT NULL DEFAULT 'USD';
SELECT n = pg_relation_filenode('payments') AS same_file FROM file_before;
 
-- A volatile default: every row needs its own value, so the table is rewritten
ALTER TABLE payments ADD COLUMN receipt_code TEXT NOT NULL DEFAULT md5(random()::text);
SELECT n = pg_relation_filenode('payments') AS same_file FROM file_before;
Output
SELECT 1
 
ALTER TABLE
 
 same_file
-----------
 t
(1 row)
 
ALTER TABLE
 
 same_file
-----------
 f
(1 row)

Explanation: CREATE TEMP TABLE ... AS reports SELECT 1, the number of rows it stored. Adding currency with a constant default kept the same file: PostgreSQL stores the default once and returns it for old rows, so the change is instant even on a huge table. A default that calls random() must compute a different value for every row, so PostgreSQL rewrote the whole table into a new file, holding a lock that blocks reads and writes until it finishes. Changing a column's type to a different kind of value (for example VARCHAR(10) to INTEGER) also rewrites the table. Widening is the exception: making a VARCHAR longer, changing VARCHAR to TEXT, or raising a NUMERIC column's precision keeps the same file, because every stored value is already valid.

Adding a NOT NULL column with no default fails outright when the table has rows:

SQL▶ Try it
ALTER TABLE students ADD COLUMN preferred_name VARCHAR(40) NOT NULL;
Output
ERROR:  column "preferred_name" of relation "students" contains null values

Explanation: The existing rows would have NULL in a column that forbids it. Either give a default, or use the expand pattern: add the column as nullable, backfill it, then add NOT NULL in a later migration.

New constraints have a gentler form too. NOT VALID adds a CHECK or foreign key that applies to new rows at once, without scanning the old ones; VALIDATE CONSTRAINT checks the old rows later with a lighter lock that lets reads and writes continue:

SQL▶ Try it
ALTER TABLE payments
  ADD CONSTRAINT payments_paid_after_2025 CHECK (paid_on >= '2025-01-01') NOT VALID;
ALTER TABLE payments VALIDATE CONSTRAINT payments_paid_after_2025;
 
ALTER TABLE payments
  ADD CONSTRAINT payments_paid_in_2026 CHECK (paid_on >= '2026-01-01') NOT VALID;
ALTER TABLE payments VALIDATE CONSTRAINT payments_paid_in_2026;
Output
ALTER TABLE
 
ALTER TABLE
 
ALTER TABLE
 
ERROR:  check constraint "payments_paid_in_2026" of relation "payments" is violated by some row

Explanation: The first constraint holds for every existing payment, so validation succeeds. The second is false for payments made in 2025, so VALIDATE reports the problem; the constraint stays in place, still marked not valid, and keeps checking new rows. Fix the old rows, then validate again.

Indexes have a similar option. CREATE INDEX CONCURRENTLY builds an index without blocking writes, but takes longer and can't run inside a transaction, so it needs a migration of its own that the tool runs outside a transaction:

SQL▶ Try it
BEGIN;
CREATE INDEX CONCURRENTLY payments_paid_on_idx ON payments (paid_on);
ROLLBACK;
 
CREATE INDEX CONCURRENTLY payments_paid_on_idx ON payments (paid_on);
Output
BEGIN
 
ERROR:  CREATE INDEX CONCURRENTLY cannot run inside a transaction block
 
ROLLBACK
 
CREATE INDEX
Change (PostgreSQL 18)Speed on a big tableSafer form
Add a nullable column, no defaultInstant
Add a column with a constant defaultInstant (since version 11)
Add a column with a volatile defaultRewrites the tableAdd nullable, backfill in batches
Change a column's typeRewrites the table, except widening (longer VARCHAR, TEXT, more NUMERIC precision)New column, expand and contract
Add NOT NULL to an existing columnScans the table under a lockPostgreSQL 18: ADD CONSTRAINT ... NOT NULL col NOT VALID, then validate. Earlier: a CHECK (col IS NOT NULL) NOT VALID, validate, then SET NOT NULL
Add a CHECK or foreign keyScans under a lockNOT VALID, then VALIDATE CONSTRAINT
Create an indexBlocks writes while it buildsCREATE INDEX CONCURRENTLY
Rename a column or tableInstant, but breaks running codeExpand, migrate, contract
Drop a columnInstant, but breaks running codeContract only after the app stops using it
Real results: a constant default keeps the same file, a volatile default rewrites the table, and NOT NULL without a default fails

Even an "instant" change needs a brief exclusive lock on the table. If a long query is holding the table, the ALTER waits, and every new query queues behind the waiting ALTER. Setting a lock timeout first makes the migration give up quickly instead of freezing the app:

SQL
SET lock_timeout = '5s';
ALTER TABLE payments ADD COLUMN currency CHAR(3) NOT NULL DEFAULT 'USD';

If it times out, the migration fails cleanly and can be retried at a quieter moment.

Never Edit an Applied Migration

Once a migration has run anywhere other than your own laptop, treat its file as frozen. Production ran the old version of the file; a new database would run the edited version; from then on the two schemas quietly differ. Most tools store a checksum of each applied file and refuse to continue when a file changes (Flyway reports a checksum mismatch, for example). To fix or undo a change, write a new migration, such as V5__drop_receipt_code.sql.

Common Mistakes

Editing a migration that already ran. Environments drift apart. Add a new migration instead.

Renaming or dropping in one step. The running app breaks the moment the old name disappears. Expand first, contract later.

One huge UPDATE for a backfill. It holds locks for a long time and bloats the table. Update in batches.

Testing on a tiny table. A migration that takes 2 milliseconds on 7 payments may rewrite 50 million rows in production. Check whether the change rewrites, scans or locks before you run it.

Changing production by hand. A quick fix typed into a console never reaches the migration files, so the next fresh database is different.

Interview Corner

What is a schema migration, and how does a tool know which ones to run?

A versioned file that changes the schema. The tool records each applied version in a table inside the database and runs only the newer files, in order.

How do you rename a column without downtime?

Expand, migrate, contract: add the new column and keep both in sync, backfill and switch the app to the new column, then drop the old column after no code uses it.

Why shouldn't you edit a migration after it has run?

Databases that already ran the old version won't run it again, so they'd differ from new databases that run the edited one. Write a new migration instead.

Which schema changes are risky on a large PostgreSQL table?

Anything that rewrites the table (a volatile default, most type changes) or scans it under a strong lock (adding NOT NULL, a CHECK or foreign key without NOT VALID, a non-concurrent index). Use the safer forms and a lock_timeout.

Practice

Challenge (module checkpoint, part 2): Write migration 5, which adds a late_fee_usd column to payments: a number with two decimal places that must never be NULL or negative and starts at 0.00 for every existing payment. Make it all-or-nothing, record it in schema_migrations, and check that the table didn't need a rewrite.

Show solution
SQL▶ Try it
CREATE TABLE schema_migrations (
  version INTEGER PRIMARY KEY, description TEXT NOT NULL, applied_on DATE NOT NULL
);
 
CREATE TEMP TABLE file_before AS
SELECT pg_relation_filenode('payments') AS n;
 
BEGIN;
SET LOCAL lock_timeout = '5s';
ALTER TABLE payments
  ADD COLUMN late_fee_usd NUMERIC(8,2) NOT NULL DEFAULT 0.00;
ALTER TABLE payments
  ADD CONSTRAINT payments_late_fee_check CHECK (late_fee_usd >= 0) NOT VALID;
INSERT INTO schema_migrations VALUES (5, 'add late fee to payments', '2026-01-05');
COMMIT;
 
ALTER TABLE payments VALIDATE CONSTRAINT payments_late_fee_check;
 
SELECT n = pg_relation_filenode('payments') AS same_file FROM file_before;
 
SELECT payment_id, amount_usd, late_fee_usd
FROM payments
ORDER BY payment_id
LIMIT 3;
 
UPDATE payments SET late_fee_usd = -5 WHERE payment_id = 7;
Output
CREATE TABLE
 
SELECT 1
 
BEGIN
 
SET
 
ALTER TABLE
 
ALTER TABLE
 
INSERT 0 1
 
COMMIT
 
ALTER TABLE
 
 same_file
-----------
 t
(1 row)
 
 payment_id | amount_usd | late_fee_usd
------------+------------+--------------
          1 |     450.00 |         0.00
          2 |     250.00 |         0.00
          3 |     250.00 |         0.00
(3 rows)
 
ERROR:  new row for relation "payments" violates check constraint "payments_late_fee_check"
DETAIL:  Failing row contains (7, 103, 5, 225.00, 2025-12-15, 2025-12-19, check, -5.00).

The constant default filled every existing payment with 0.00 without rewriting the table, the migration and its record committed together, and the CHECK refuses a negative late fee. SET LOCAL keeps the lock timeout for this transaction only. Validating in a separate step keeps the scan out of the migration's lock (in a real tool it would be the next migration file).

Quick check: Schema migrations

4 questions
1What stops a migration tool from running version 3 twice?
2A PostgreSQL migration in BEGIN ... COMMIT fails on its second ALTER TABLE. What remains?
3What's the safe way to rename a column the running app uses?
4Which change rewrites a big PostgreSQL table?

Key Takeaways

You want toUse
Record applied versionsA schema_migrations table keyed by version
Make a migration all-or-nothingBEGIN ... COMMIT (PostgreSQL, SQL Server, SQLite)
Add a column to a big tableA nullable column, or one with a constant default
Add a constraint without a long lockADD CONSTRAINT ... NOT VALID, then VALIDATE CONSTRAINT
Add an index without blocking writesCREATE INDEX CONCURRENTLY (outside a transaction)
Avoid freezing the app on a busy tableSET lock_timeout = '5s' before the ALTER

Was this tutorial helpful?

Lesson 97 of 115