Skip to content
Visual explainer 2h to learn 4 steps

Schema migrations

Evolve a schema safely with versioned migrations and zero-downtime patterns.

By Invicly Tech, , in SQL & PostgreSQL. About 11 minutes to read.

Topic 16 of 30

In short

Migrations are versioned scripts that change the schema step by step, stored in Git and applied the same way everywhere. Zero-downtime changes split risky edits into small, backward-compatible steps.

Explained simply

A migration is a small script that changes your database structure, such as adding a table or a column. Each one gets a version number and lives in Git next to your code, so every laptop, test server and production database can be brought to exactly the same shape.

A migration tool runs the scripts in order and records which ones have already run in a special table. When you deploy, it applies only the new ones. You never change the production schema by hand, because then nobody knows what the real schema is.

The hard part is changing a busy database without stopping the app. Some changes lock a table while they work, and every query waits behind them. Big updates can run for minutes. So risky changes are split into small, safe steps.

The golden rule: at every moment, the database must work with both the old and the new version of your code, because during a deploy both versions are running at once.

Press Play on a diagram to walk through it one step at a time.

FlowExpand and contract: rename a column safely
  1. 1
    Add new column

    Nullable, so the change is instant

  2. 2
    Write both

    Deploy code that writes old and new

  3. 3
    Backfill in batches

    Copy old values a few thousand rows at a time

  4. 4
    Read the new column

    Switch code; add NOT NULL when filled

  5. 5
    Drop old column

    Only after nothing uses it

CompareHow expensive is this ALTER?
Instant (metadata only)
  • ADD COLUMN, nullable
  • ADD COLUMN DEFAULT 0 (PG 11+)
  • DROP COLUMN
  • ADD CONSTRAINT ... NOT VALID
Scans under a strong lock
  • SET NOT NULL without a valid CHECK
  • ADD CHECK without NOT VALID
  • ADD FOREIGN KEY without NOT VALID
Rewrites the table
  • integer to bigint
  • Volatile default, e.g. clock_timestamp()
  • VACUUM FULL or CLUSTER

In depth

How migration tools work

Every tool follows the same idea. Migrations are files with an order, such as V3__add_orders.sql (Flyway), 0003_add_orders.up.sql and .down.sql (golang-migrate), or Python files with upgrade() and downgrade() functions (Alembic). The tool creates a history table in your database, for example flyway_schema_history, alembic_version or schema_migrations, and records each migration it applies.

On deploy, the tool compares the files with the history table and runs only the missing ones, in order. Some tools also store a checksum and refuse to run if an applied file was edited later.

Postgres has transactional DDL: most CREATE and ALTER statements can run inside a transaction, so a failed migration rolls back cleanly instead of leaving half a change. A few commands, like CREATE INDEX CONCURRENTLY, cannot run in a transaction, and tools let you mark those migrations specially.

  • Flyway, Liquibase: SQL or XML, any language
  • Alembic (Python), Prisma Migrate, Django and Rails migrations
  • golang-migrate, dbmate, sqitch: plain SQL files
  • Never edit a migration that already ran; add a new one
SequenceA deploy that applies one new migration
CI deploy
Migration tool
PostgreSQL
  1. 1migrate up
    CI deploy to Migration tool: migrate up
  2. 2Read history table
    Migration tool to PostgreSQL: Read history table
  3. 3Applied: 1, 2, 3
    PostgreSQL to Migration tool: Applied: 1, 2, 3
  4. 4BEGIN; run 0004; COMMIT
    Migration tool to PostgreSQL: BEGIN; run 0004; COMMIT
  5. 5Insert 0004 into history
    Migration tool to PostgreSQL: Insert 0004 into history
  6. 6Done, start new app version
    Migration tool to CI deploy: Done, start new app version

Locks: why a tiny ALTER can freeze the app

Most ALTER TABLE forms take an ACCESS EXCLUSIVE lock, which blocks even plain SELECTs. If the change itself is instant, like adding a nullable column, the lock lasts only milliseconds. The danger is the wait before it.

Suppose a long report query holds a lock on the table. Your ALTER waits for it. Every new query on that table now queues behind your waiting ALTER, because Postgres grants locks in order. In seconds, all app connections are stuck and the site looks down.

The fix is to give DDL a short patience. Run SET lock_timeout = '5s' at the start of the migration. If the lock is not granted in time, the ALTER fails instead of blocking everyone, and you retry later. Many teams also set statement_timeout for migrations, and check pg_stat_activity for long-running transactions before deploying.

FlowThe lock queue pile-up
  1. 1
    Long query running

    Holds a shared lock on orders

  2. 2
    ALTER TABLE waits

    Needs ACCESS EXCLUSIVE

  3. 3
    New SELECTs queue

    They wait behind the ALTER

  4. 4
    Connections run out

    The app times out

  5. 5
    Fix

    lock_timeout makes the ALTER give up and retry

Which changes are safe, and how to do the risky ones

Fast and safe: adding a nullable column; adding a column with a constant default (instant since PostgreSQL 11, no table rewrite); dropping a column (only marks it hidden); making a varchar longer.

Rewrites the whole table under a full lock: changing most column types, such as integer to bigint, and adding a column with a volatile default like clock_timestamp().

Scans the whole table while holding a strong lock: SET NOT NULL and adding a CHECK (both block reads and writes), or a foreign key (blocks writes). The safe pattern is to add the constraint with NOT VALID (instant, applies to new rows only), then run VALIDATE CONSTRAINT, which checks old rows under a lighter lock that allows reads and writes. Since PostgreSQL 12, SET NOT NULL skips its scan if a valid CHECK (col IS NOT NULL) already exists.

Indexes: use CREATE INDEX CONCURRENTLY. If it fails, it leaves an INVALID index that you must drop and recreate.

  • Instant: nullable column, constant default, DROP COLUMN
  • Rewrite: most type changes
  • Constraint: ADD ... NOT VALID, then VALIDATE CONSTRAINT
  • Index: CREATE INDEX CONCURRENTLY, outside a transaction

Backfills and rolling back

A single UPDATE of 50 million rows holds row locks for its whole run, creates 50 million dead row versions at once, can fill the disk with WAL (the write-ahead log) and makes replicas fall behind. Instead, update in batches of a few thousand rows, each in its own short transaction, walking through the table by id range. Pause briefly between batches and watch replication lag.

Down migrations are useful in development, but in production they can destroy data: the down for "add column" drops the column and everything written to it. Many teams prefer to roll forward: fix a mistake with a new migration. Whatever you choose, test the migration on a copy of production-sized data first, because a change that is instant on 1,000 rows can take an hour on 100 million.

Learn it in 4 short steps

About 30m each. Track them with a timer in your plan.

  1. 1
    Set up a migration tool~30m
  2. 2
    Write up and down migrations~30m
  3. 3
    Add columns without downtime~30m
  4. 4
    Backfill data in batches~30m

Key points

  • Every schema change is a numbered migration file, never a manual edit.
  • Write a down migration, or a clear rollback plan, for each change.
  • CREATE INDEX CONCURRENTLY builds an index without blocking writes.
  • Big UPDATEs lock many rows; backfill in batches instead.

Key terms

Tap a card to flip it. 0/5 known

Examples

sql
-- 0007_add_full_name.up.sql
ALTER TABLE users ADD COLUMN full_name text;

-- backfill in batches (repeat until 0 rows updated)
UPDATE users SET full_name = first_name || ' ' || last_name
WHERE id IN (
  SELECT id FROM users WHERE full_name IS NULL LIMIT 5000
);

CREATE INDEX CONCURRENTLY users_full_name_idx ON users (full_name);

-- 0007_add_full_name.down.sql
ALTER TABLE users DROP COLUMN full_name;

Making a column NOT NULL on a big table

orders.customer_id has been nullable for years, and you now want NOT NULL on a 40 million row table without blocking traffic. Step 1: add a CHECK with NOT VALID, which is instant. Step 2: VALIDATE it; this scans the table but allows reads and writes. Step 3: SET NOT NULL, which uses the valid CHECK and skips its own scan (PostgreSQL 12+). Step 4: drop the now redundant CHECK. A short lock_timeout protects each step.

sql
SET lock_timeout = '5s';

ALTER TABLE orders
  ADD CONSTRAINT orders_customer_id_not_null
  CHECK (customer_id IS NOT NULL) NOT VALID;

ALTER TABLE orders VALIDATE CONSTRAINT orders_customer_id_not_null;

ALTER TABLE orders ALTER COLUMN customer_id SET NOT NULL;
ALTER TABLE orders DROP CONSTRAINT orders_customer_id_not_null;

Backfilling in batches from a script

A new column orders.total_cents must be filled from total for 30 million rows. Step 1: loop over id ranges of 10,000. Step 2: each UPDATE commits on its own, so locks are short and autovacuum can clean up as you go. Step 3: sleep a little between batches. Step 4: stop when the range passes the max id. psql runs each statement in its own transaction by default, so a simple shell loop works.

bash
max=$(psql -tAc "SELECT max(id) FROM orders")
step=10000
for ((start=1; start<=max; start+=step)); do
  psql -q -c "UPDATE orders
    SET total_cents = (total * 100)::bigint
    WHERE id >= $start AND id < $start + $step
      AND total_cents IS NULL;"
  sleep 0.2
done

Quick reference

  • SET lock_timeout = '5s'; at the top of every migration on a busy database
  • ADD COLUMN with a constant DEFAULT is instant since PostgreSQL 11
  • ADD CONSTRAINT ... NOT VALID, then ALTER TABLE ... VALIDATE CONSTRAINT ...
  • CREATE INDEX CONCURRENTLY cannot run inside BEGIN ... COMMIT
  • Failed concurrent build leaves an INVALID index: DROP INDEX CONCURRENTLY and retry
  • Backfill by id range in small committed batches, not one giant UPDATE
  • Never edit an applied migration; write a new one
  • Test migrations on production-sized data before deploying

Common mistakes

  • Editing a migration that has already run in production.
  • Renaming or dropping a column that running code still reads.
  • Running CREATE INDEX CONCURRENTLY inside a transaction block, which fails.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1An ALTER TABLE that should take 1 ms has frozen the whole app. What is the most likely cause?

Question 2

2Which change rewrites the whole table?

Question 3

3What does adding a foreign key with NOT VALID do?

Question 4

4Why do many teams prefer rolling forward over running down migrations in production?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write an up and a down migration that add a nullable text column phone to customers.

  2. Exercise 2medium

    Add a foreign key from orders.customer_id to customers(id) on a large, busy table without a long blocking scan.

  3. Exercise 3hard

    Plan the zero-downtime rename of users.name to users.full_name as a list of migrations and deploys, in order.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Can I just use ALTER TABLE RENAME COLUMN?
It is instant, but every running app instance that still uses the old name breaks immediately. It is only safe if you can stop the app or if a view or code change covers both names during the deploy.
Should migrations run automatically when the app starts?
It is simple for small apps, but with many instances they may race. Many teams run migrations as a separate deploy step before starting the new app version.
Do ORMs handle zero-downtime migrations for me?
No. ORMs generate the SQL, but they do not know your table sizes or traffic. You still need to split risky changes and use patterns like NOT VALID and CONCURRENTLY.
ShareXLinkedInWhatsApp