Skip to content
BENIBIX Learn

Database Migration

Development🗃️ DatabasesDatabases in Code

Also known as Schema Migration, Migration, Migration File

A small file that makes one change to a database's shape. It lives with the code.

Think of it like

Think of it like a list of steps to rearrange a room. Anyone can follow it and end up with the same room.

Example

Jack adds a phone field to his app. He writes a migration, and when he deploys, the live database gets the new column too.

Why it matters

Without migrations, each copy of the database drifts. Then code that works on your laptop breaks on the server.

Definition

A database migration is a small file that changes the schema. Each one makes a single change, like adding a column. Each migration is saved in Git with the code that needs it. A tool runs the ones a database has not had yet, in order. That way, every laptop, test server and live server ends up with the same schema. Most migrations also say how to undo the change.

Example code

sql
-- 0007_add_phone.sql
ALTER TABLE customers ADD COLUMN phone TEXT;
The file adds one column called phone.

Common mistake

Editing a migration that has run on the live server. Write a new one, or the copies will not match.

Key takeaways

  1. 1
    One step each. Small changes, in order.
  2. 2
    Kept in Git. Next to the code that needs them.
  3. 3
    Never edit old ones. Add a new step instead.