• Docs
  • Talk to an expert
Blog
Blog
BlogProductCase studiesNewsInsights
Blog

What is a database migration?

datadeploymentdata cloningPostgreSQL
27 November 2026
Share

TL;DR

  • A database migration is a small, versioned script that changes a database's structure, such as adding a table or a column.
  • Migrations live in your code repository, so every environment can apply the same changes in the same order.
  • A migration tool records which migrations a database has already run, so each one runs exactly once.
  • In production, migrations run during a deployment, before the new code starts serving visitors.
  • The risky ones change or remove things the old code still uses, or lock large tables. Split those into smaller, safer steps.
  • AI agents can change databases too. Keep them working on copies of your data, route their changes through reviewed migrations, and never give them production database access.
  • On Upsun Cloud, you can test a migration against a copy of production data in a preview environment before it ships, then run it in the deploy hook.

A database migration is a script that changes a database's structure in a controlled, repeatable way. Adding a column, creating a table, renaming a field, or adding an index are all done with migrations.

Changes to a live database are some of the riskiest in software, and AI agents now make them faster than ever. This guide explains how migrations make database changes safe and repeatable, how to run them in production, and how to keep both people and AI agents from damaging real data. It covers schema migrations, the everyday developer meaning, rather than moving data between database systems.

How database migrations work

Key takeaway: migrations are numbered scripts kept with your code, and a tool runs any the database hasn't seen yet, in order.

  1. A developer writes a migration, or the framework generates one from a change to the code's data models.
  2. The migration is saved in the code repository with a version number or timestamp, next to the code that needs it.
  3. When the migration tool runs, it checks a tracking table in the database to see which migrations have already been applied.
  4. It applies any new ones, in order, and records them.

Because the migrations travel with the code, every environment, from a developer's laptop to production, ends up with the same database structure.

What a migration looks like

Key takeaway: a migration describes one change, often with a matching way to undo it.

Here's a migration in plain SQL that adds a column:

ALTER TABLE customers ADD COLUMN phone VARCHAR(30);

Frameworks usually let you write migrations in your own programming language instead. Many also include an "undo" step, which reverses the change if you need to roll back.

FrameworkMigration toolRun migrations
DjangoBuilt-in migrationspython manage.py migrate
RailsActive Record migrationsbin/rails db:migrate
LaravelBuilt-in migrationsphp artisan migrate
SymfonyDoctrine Migrationsphp bin/console doctrine:migrations:migrate
Any languageFlyway, LiquibaseTheir own command-line tools

Running migrations in production

Key takeaway: migrations run as part of the deployment, after the new code is built and before it serves visitors.

The usual order is: build the new code, run the migrations, then send traffic to the new version. The build typically can't reach the database, so migrations belong to the deploy phase. Our guide What happens during a deployment? explains the phases.

Run migrations from one place only. If several servers each try to run them at the same moment, they can collide.

Safe and risky migrations

Key takeaway: adding things is usually safe. Changing or removing things the running code depends on is where releases break.

ChangeRiskWhy
Add a new tableLowNothing uses it yet
Add a column that can be emptyLowOld code ignores it
Add a column that can't be empty, with no defaultHighOld code inserting rows without it starts failing
Rename a columnHighOld code still uses the old name
Remove a columnHighOld code still reads it
Add an index to a large tableMediumIt can lock the table while it's built, unless the database can build it without blocking
Change a column's type on a large tableHighIt may rewrite the whole table and lock it

For the risky ones, the usual approach is to split the change across several releases, often called expand and contract: add the new structure first, release code that works with both old and new, then remove the old structure later. This also matters for zero-downtime deployments, where old and new code run against the same database for a while. The post Django deployments without downtime: static files and migrations walks through a real example.

Rolling back a migration

Key takeaway: undoing a migration is possible but risky once real data has changed, so prevention beats cure.

Many tools can run a migration's undo step. But if users have added data since the migration ran, undoing it can lose that data. Removing a column throws away whatever was in it.

That's why it's worth taking a backup before a release that changes the database, and testing migrations against realistic data first. Our guide What is a deployment rollback? covers rollbacks in more depth.

Common migration mistakes

Key takeaway: many migration failures come from testing on small, tidy data that looks nothing like production.

MistakeWhat happensHow to avoid it
Testing only on an empty or tiny databaseA migration that takes a second locally takes an hour on production, or fails on messy real dataTest on a realistic copy of production data
Editing a migration that has already runEnvironments end up with different structuresNever change a migration once it's shared. Write a new one
Mixing large data updates into structure changesThe migration runs for a long time and locks tablesMove big data updates into separate, batched jobs
Running migrations from several servers at onceMigrations collide or run twiceRun them from one place during deployment
No backup before a risky changeNothing to restore if it goes wrongTake a backup first

When AI agents change your database

Key takeaway: telling an AI agent not to touch production isn't a safeguard. Keeping production out of its reach is.

In July 2025, SaaStr founder Jason Lemkin was running a public 12-day experiment building an app with Replit's AI coding agent. According to his posts, the agent ran commands against the live database during a code freeze, despite instructions not to make changes without permission, and deleted records on roughly 1,200 executives and 1,200 companies. Replit's CEO called it unacceptable and promised to automatically separate development and production databases.

The lesson isn't that one tool failed. It's that instructions alone don't protect data. The agent had access to the production database, so a misjudgment became a disaster. The safeguards that work are the same ones that protect against human mistakes, applied deliberately:

SafeguardHow it protects you
Separate environments, with separate databasesAgents work on a copy of the data, so a destructive command damages nothing real
No production credentials for agentsAn agent can't run commands against a database it can't connect to
Changes as migration files, not direct commandsEvery change to the database's structure is written down, reviewed, and run by the deployment process, not by the agent
Human approval before productionA person approves changes before they reach real data. Our guide What is human-in-the-loop in AI software development? covers approval gates
Read-only access for investigatingWhen an agent needs to look at production data to debug, give it a read-only account
Recent backups, and tested restoresIf something does go wrong, you can get the data back. Our guide What is a deployment rollback? explains your options
Isolated workspacesRunning agents in a sandbox limits what they can reach. Our guide What is an AI agent sandbox? explains how

Instructions still help as a second layer. A line in your AGENTS.md file, such as "Never run commands against production. Database changes must be migrations", tells an agent what's expected. Our guide AGENTS.md vs CLAUDE.md vs .cursorrules explains how. But treat instructions as guidance, and the separation as the protection.

Testing migrations on Upsun Cloud

Key takeaway: on Upsun Cloud, each preview environment can start with a copy of production data, so a migration runs against realistic data before it ships.

On Upsun Cloud, branching an environment copies its databases and files along with the code by default, and with the GitHub integration, each pull request gets an environment with its parent's data by default. That gives you a production-sized database to test a migration against before it reaches real users.

A typical flow:

  1. Open a pull request with the migration. Upsun Cloud creates a preview environment, by default with a copy of production data.
  2. The migration runs in that environment's deploy hook, exactly as it will in production.
  3. Check how long it took in the deploy log, and test the app against the changed data.
  4. Before merging, take a backup of production with upsun backup:create.
  5. Merge, and the same migration runs on production.

Here's the hook that runs Django migrations on every deployment:

applications:
  myapp:
    type: "python:3.14"
    hooks:
      deploy: |
        set -e
        python manage.py migrate --noinput

A few details from the Upsun docs: the deploy hook has access to the database and runs before the app accepts requests, and only the web app runs it, not workers. Remove or mask personal data in preview environments first. The docs include guides to sanitizing databases for Drupal, Django, and Symfony. Our guide What is a preview environment? explains how preview environments get their data.

The same setup keeps AI agents away from production data. Each preview environment has its own copy of the database, with its own connection details, so an agent working on a branch is working on a copy. Its migrations reach production only by being merged and deployed, through the deploy hook, after review. And if you connect AI assistants to Upsun Cloud through the Upsun Cloud MCP server, it's read-only unless you explicitly turn on write access.

You can deploy on Upsun Cloud free for 15 days, with no card needed, or see how Git-driven automation gives every pull request its own environment.

Frequently asked questions

Can an AI agent delete my production database?

Yes, if it can connect to it. In a widely reported 2025 incident, an AI coding agent deleted a live database despite instructions not to make changes. Keep agents working on copies of your data in separate environments, never give them production credentials, and make database changes through reviewed migrations.

What is the difference between a schema migration and a data migration?

A schema migration changes the database's structure, such as its tables and columns. A data migration changes or moves the data itself. "Database migration" can also mean moving to a different database system entirely.

Where are migrations stored?

In your code repository, usually in a folder named migrations, so they're versioned and reviewed with the code that needs them.

When should migrations run?

During deployment, after the new code is built and before it starts serving visitors.

Can you undo a database migration?

Often, if the migration includes an undo step. But undoing it after real data has changed can lose that data, so test first and take a backup before risky changes.

Why did my migration lock the database?

Some changes, such as altering a column's type or adding an index on a large table, lock the table while they run. Use your database's non-blocking options where they exist, and split large changes into smaller steps.

Do I need migrations for a small project?

Yes. Even small projects end up with several environments, and migrations are the reliable way to keep their databases in step.

Stay updated

Subscribe to our monthly newsletter for the latest updates and news.

Deploy possibility.
Try Upsun for free.

Build with DispatchDeploy on Cloud