Skip to the workspace
Pebellslearn by building
Relational Databases  ›  Capstone Project

Migrations — Changing a Schema Safely

Migrations 15 minA migration is a small, numbered, version-controlled script that moves a database schema from one version to the next, applied in order and never edited after it has run.

backend / Migrations — Changing a Schema Safely

Explore each scene at your own pace.

01 · The rule

The rule

Migrations — Changing a Schema Safely

The bookshop's books table already holds 5,000 books, and now every book needs an ISBN. You could log in to the production database and type an ALTER TABLE. Then your laptop, your teammate's laptop, the test server and production would each have a slightly different schema, and nobody would be sure which. Migrations prevent that.

The rule

Change the schema only through numbered scripts, in order, never rewritten.

A migration is a small file that moves the database from one version of the schema to the next. Migrations are:

  • numbered or timestamped, so they run in a fixed order
  • committed to Git with the code that needs them
  • recorded by the migration tool in a table inside the database, so each one runs exactly once per database
  • often reversible: an "up" step applies the change and a "down" step undoes it
migrations/
  0001_create_authors.sql
  0002_create_books.sql
  0003_add_reviews.sql
-- 0004_add_isbn_to_books.sql
ALTER TABLE books ADD COLUMN isbn TEXT;

Tools such as Alembic (Python), Flyway (Java), Prisma Migrate or Knex (JavaScript) and the migration commands built into Rails and Django all follow this pattern. You run one command, and the tool applies every migration the database has not seen yet.

Two rules keep this reliable:

  1. Never edit a migration that has already run somewhere shared. That database will not run it again, so the edit silently diverges. Write a new migration instead.
  2. Change in steps the running code can survive. While you deploy, old and new code may both be running against the same database.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.