Database migration

Also known as: schema migration, DB migration, migration script, database schema migration, schema change

Updated 2026-11-104 questions

A database migration is a versioned, ordered script that changes a database's schema or data, such as adding a column, creating an index or backfilling values. Migrations live in source control next to the application code, and a migration tool applies only the ones a given database has not run yet, so every environment converges on the same schema.

How does a database migration work?

A database migration is a small, numbered change to a database, committed to the same repository as the code that depends on it. Instead of someone connecting to production and typing ALTER TABLE, the change is written once as a file (V42__add_orders_status.sql, 20261110_add_status.rb, a Prisma or Alembic revision) and applied by a tool, the same way, in every environment.

The mechanics are almost identical across tools such as Flyway, Liquibase, Alembic, Rails Active Record, Django, Prisma and golang-migrate:

  1. A history table records what has run. The tool keeps a table like flyway_schema_history or schema_migrations with the version, checksum and timestamp of each applied migration.
  2. Pending migrations are computed, not guessed. On each run the tool compares the files in the repo with the history table and selects only the ones the database has not seen yet.
  3. They apply in strict order. Version 41 always runs before 42, so a fresh laptop database and a five-year-old production database end up with the same schema.
  4. Each one is recorded once it succeeds. If a migration fails, the run stops. Engines with transactional DDL (PostgreSQL, SQL Server) roll that step back cleanly; MySQL commits most DDL implicitly, so a half-applied migration there needs manual repair.
  5. Checksums catch tampering. Editing a migration that already ran changes its checksum, and the tool refuses to continue. Applied migrations are immutable; you fix them with a new one.

In a pipeline this becomes a dedicated step: build and test the app, apply pending migrations from a single job, then deploy the code that relies on them.

Why do migrations matter for continuous delivery?

Code is easy to replace. Data is not. You can redeploy last week's binary in seconds, but you cannot un-drop a column that held customer addresses. That asymmetry is why the database is usually the slowest, scariest part of a release, and why teams that deploy many times a day treat migrations as a discipline of their own.

Versioned migrations give you three things that hand-run SQL never does. Every schema change is reviewed in a pull request like any other change. Every environment, from a developer laptop to staging to production, is built from the same ordered history, so "works on staging" means something. And the pipeline can refuse to deploy code whose migrations failed, instead of shipping an app that crashes on its first query.

They also define what a safe rollback looks like. If the previous version of the app cannot run against the new schema, rolling back the code does not restore service, it just moves the outage. That is the real reason migrations need to be backward compatible.

What is the expand-and-contract pattern?

Expand and contract (Martin Fowler calls it parallel change) is how you change a schema while old and new versions of the app are both live, which is the normal state during a rolling or blue-green deploy.

Renaming users.name to users.full_name without downtime looks like this:

Release Migration Application code
1. Expand Add nullable full_name Writes to both columns, reads name
2. Backfill Copy name into full_name in batches Unchanged
3. Switch None Reads and writes full_name only
4. Contract Drop name Unchanged

Every step is compatible with the release before it, so any single deploy can be reverted without touching data. The cost is four releases instead of one. For a rename on a hot table that trade is almost always worth it; for a column nobody reads yet, a single additive migration is fine.

A few rules fall out of this pattern and hold for most relational databases:

  • Add columns as nullable or with a constant default; never add a NOT NULL column without one on a large table.
  • Create indexes online (CREATE INDEX CONCURRENTLY in PostgreSQL, ALGORITHM=INPLACE or a tool like gh-ost in MySQL).
  • Backfill in small batches from a job, not inside the migration transaction.
  • Drop and rename only after no running code references the old shape.

How do popular CI/CD tools handle database migrations?

No mainstream CI/CD server ships its own migration engine. They all call Flyway, Liquibase, Alembic or your framework's migrator from a job. What differs is where that job sits relative to the deploy, and how easy it is to put a gate in front of the irreversible part.

  • GitHub Actions handles the test side well: a services: container gives each job a throwaway PostgreSQL or MySQL to apply migrations against. For production, environments with required reviewers let you hold a migrate job until someone approves it.
  • GitLab CI offers the same services: pattern plus protected environments and deployment approvals, and its resource_group keyword stops two pipelines from migrating the same database at once, which is exactly the concurrency guard migrations need.
  • Jenkins can model any sequence you like with input steps and lock() from the Lockable Resources plugin. That flexibility suits unusual setups, such as a DBA sign-off stage, at the cost of maintaining the Groovy yourself.
  • Argo CD runs migrations as a Kubernetes Job annotated as a PreSync resource hook, so the schema change happens before the new Deployment is applied, inside the same sync. If your app already ships to Kubernetes through Argo CD (or Helm's pre-upgrade hooks), that is the better fit: the migration travels with the manifests and you do not need a separate CI step at all.
  • Platform release phases (Heroku's release phase, Render's pre-deploy command) run a migration command once per deploy before traffic moves. If you are on one of those platforms, use the built-in hook before reaching for pipeline logic.

Buddy is one of the options we recommend when you want the dry run, the human approval and the apply step to sit in one readable pipeline file, separate from the app deploy. Each is its own action, so you can review the pending SQL, approve it with a WAIT_FOR_APPLY gate restricted to the people who own the database, and only then migrate and ship. Credentials stay in encrypted pipeline variables rather than in the repo. It is a good fit for teams deploying VMs, containers or static frontends outside a GitOps setup.

Example

The pipeline below is the "expand" half of a release. It tests the migrations against a scratch database, prints what would run in production, waits for a database owner to approve, applies the migration from a single job, and only then deploys the code that uses the new column.

# .buddy/pipeline.yml - gated, forward-only schema migration before deploy
- pipeline: "migrate-and-deploy"
  events:
  - type: "PUSH"
    refs:
    - "refs/heads/main"
  actions:
  - action: "Test migrations and app"
    type: "BUILD"
    docker_image_name: "node"
    docker_image_tag: "20"
    commands: |-
      npm ci
      npm run db:migrate:test
      npm test
      npm run build

  - action: "Show pending production migrations"
    type: "BUILD"
    docker_image_name: "flyway/flyway"
    docker_image_tag: "10"
    commands: |-
      flyway -url="$PROD_DB_URL" -user="$PROD_DB_USER" -password="$PROD_DB_PASSWORD" -locations=filesystem:./db/migrations validate
      flyway -url="$PROD_DB_URL" -user="$PROD_DB_USER" -password="$PROD_DB_PASSWORD" -locations=filesystem:./db/migrations info

  - action: "Approve schema change"
    type: "WAIT_FOR_APPLY"
    trigger_time: "ON_EVERY_EXECUTION"
    comment: "Apply pending migrations from ${BUDDY_RUN_COMMIT} to production? Check the 'info' output first."
    prevent_self_approval: true
    timeout: 3600
    permissions:
      others: "DENIED"
      groups:
        db-owners: "ALLOWED"

  - action: "Apply migrations"
    type: "BUILD"
    docker_image_name: "flyway/flyway"
    docker_image_tag: "10"
    commands: |-
      flyway -url="$PROD_DB_URL" -user="$PROD_DB_USER" -password="$PROD_DB_PASSWORD" -locations=filesystem:./db/migrations migrate

  - action: "Deploy app"
    type: "BUILD"
    docker_image_name: "ubuntu"
    docker_image_tag: "22.04"
    commands: |-
      bdy artifact publish web-app:$BUDDY_RUN_COMMIT_SHORT ./dist --create
      bdy distro route update prod-distro --domain=example.com --target=artifact=web-app:$BUDDY_RUN_COMMIT_SHORT

  - action: "Post-deploy health check"
    type: "HTTP"
    method: "GET"
    notification_url: "https://example.com/healthz"
    retry_count: 6
    retry_interval: 10

The ordering carries the safety. validate fails the run if anyone edited an already-applied migration, and info puts the exact pending versions in the log the approver reads. Migrations run from one action, never from app containers on boot, so there is no race between replicas. Because the migration is additive and lands before the deploy, the old version keeps working if the health check fails and you roll the code back. The "contract" migration that drops the old column ships in a later release, through this same pipeline.

Frequently asked questions

Should database migrations run before or after the application deploy?

Additive changes (new tables, new nullable columns, new indexes) run before the deploy, so the new code finds the shape it expects. Destructive changes (dropping or renaming a column) run after every running instance has stopped reading the old shape, usually one or more releases later. Splitting a change this way is the expand-and-contract pattern.

Can you roll back a database migration?

Sometimes. Many tools let you write a "down" script, but a down migration that drops a column also drops whatever data was written to it since the deploy. In production most teams treat migrations as forward-only and fix a bad one with a new, compensating migration rather than reversing it.

Why do migrations need a lock or a single runner?

If two deploy jobs or several app replicas try to apply the same pending migration at once, you get duplicate DDL, half-applied changes or a deadlock. Migration tools record applied versions in a history table and take a lock on it, and pipelines should run migrations from exactly one job rather than from every container on startup.

How do I test a migration before it hits production?

Apply it in CI against a disposable database built from the previous schema, then run the test suite against the result. For risky changes, also run it against a recent, anonymised copy of production data in staging: that is where you discover the ALTER that locks a 200-million-row table for twenty minutes.

Missing a term? Spotted a mistake?

Suggest a new word or an edit to an existing one. Every submission is reviewed before it goes live.