Database Migrations
Small, versioned scripts that change a schema over time, so every environment gets the same structure in the same order.
What is it?
A live app's schema keeps changing: new columns, new tables, renames. Doing this by hand (logging into production and typing ALTER TABLE) is risky. It's easy to forget a step, apply changes in the wrong order, or let your development database drift from production.
A migration is a small script describing one schema change, like "add a phone_number column to users." It's saved as a file, checked into version control with your code, and numbered or timestamped so migrations always run in a known order. A migration tool tracks which migrations a database has already applied, so it only runs the new ones.
Explain like I'm 10
Editing a live schema by hand is like renovating a house without writing down what you changed; nobody can reproduce it. Migrations are numbered blueprints: 1 adds the garage, 2 adds a window. Any house (your laptop, staging, production) built from them in order ends up identical.
Examples
A migration file adding a column
-- migrations/0007_add_phone_number_to_users.sql
ALTER TABLE users
ADD COLUMN phone_number TEXT;One file, one schema change. The filename encodes the order (0007), so the tool runs it after 0006 and before 0008.
A migration with an explicit rollback (using an ORM's migration tool, conceptually)
// migrations/0008_create_reviews_table.js
exports.up = function (schema) {
schema.createTable("reviews", (t) => {
t.integer("id").primaryKey();
t.integer("product_id").references("products.id");
t.text("body");
});
};
exports.down = function (schema) {
schema.dropTable("reviews");
};Many migration tools pair each change (up) with its exact opposite (down), so a migration can be cleanly rolled back.
The same idea with Alembic (SQLAlchemy's migration tool)
# migrations/versions/a1b2c3_add_phone_number.py
def upgrade():
op.add_column("users", sa.Column("phone_number", sa.String()))
def downgrade():
op.drop_column("users", "phone_number")Alembic is the migration tool most often paired with SQLAlchemy/FastAPI. upgrade() and downgrade() are the same up/down pair as the JavaScript example, in Python. Running alembic upgrade head applies every migration not yet recorded, in order.
How it works
A migration tool keeps a small table in the database (often called schema_migrations) listing which migration files have run. Each time you run the tool, it compares that list with the files that exist and applies only the missing ones, in order.
Because migrations are files in version control, every developer and every environment (development, staging, production) runs the same sequence and gets an identical schema, instead of drifting apart through manual changes.
Why does it exist?
Manual schema changes only work for one person on one database. Once there are several developers, several environments, or schema changes that must ship with code, changes need to be recorded, ordered, and re-runnable. That's what migrations provide.
When to use it
Use migrations for nearly every schema change in any app with more than one environment or contributor: adding columns, creating tables, changing constraints, backfilling data as part of a schema change.
When not to use it
For a throwaway local prototype with one developer and no shared environments, formal migration files may not be worth it yet. Adopt them as soon as the project is shared or deployed anywhere.
Common mistakes
Editing a migration that's already been applied elsewhere instead of writing a new one. Environments that ran the old version fall out of sync.
Changing the production schema directly to 'fix it quickly,' bypassing migrations and drifting from what the migration history says.
Changing both schema and large amounts of data in one long-running migration, which can lock the table for a long time in production.
Practice exercises
- Easy:
Write a migration that adds a boolean is_active column, defaulting to true, to a users table.
- Medium:
Write a migration that creates a tags table and a join table linking tags to posts (many-to-many).
- Hard:
Explain why editing an already-applied migration, instead of writing a new one, can make a team's databases drift out of sync.
Interview questions
What is a database migration?
A versioned script describing one schema change, saved as a file and run in a known order, so it applies the same way in every environment.
What do the `up` (or `upgrade`) and `down` (or `downgrade`) parts of a migration represent?
up/upgrade applies the change. down/downgrade should be its exact opposite, so the same file can apply the change and cleanly undo it.
How does a migration tool decide which migrations still need to run, and in what order?
It keeps a table in the database (often schema_migrations) listing applied migrations, compares it with the files that exist, and runs only the unapplied ones in filename order.
Why shouldn't you edit an already-applied migration file instead of writing a new one?
Environments that already ran the original never see the edit, so their schema silently drifts from any environment that runs the edited file fresh.
Concretely, what breaks when a team edits an applied migration instead of adding a new one?
A developer whose database already applied it keeps the old schema forever, while anyone migrating from scratch gets the edited version. The tracking table can't notice, because it records that a migration ran, not what it contains.
Why is a down migration risky specifically when the up migration dropped a column or table?
Down can recreate the empty structure but can't bring back its data. It looks like a clean rollback, but the data is already gone for good.
What does 'zero-downtime migration' mean, and why can an ordinary schema change threaten uptime?
It means the running code and the schema are never incompatible, even for a moment. Renaming or dropping a column the live code still reads can break every request the instant it runs.
Describe the 'expand-contract' pattern for renaming a column without downtime.
Expand: add the new column (nullable), have the app write to both old and new columns, and backfill existing rows. Once every app instance reads the new column, contract: drop the old column in a later, separate migration.
Why can adding a `NOT NULL` column with no default be riskier than adding a nullable one?
Every existing row needs a value the instant the constraint applies. With no default there's nothing to put there, so the statement is rejected (or, where the engine must backfill every row, it can hold a long lock while rewriting the table). A nullable column just stores NULL for existing rows.
Why does a plain `CREATE INDEX` risk blocking writes on a large production table, and what's Postgres's alternative?
A normal index build takes a lock that blocks writes for the whole build. CREATE INDEX CONCURRENTLY avoids that exclusive lock, but takes longer and needs two passes over the table.
Why can't `CREATE INDEX CONCURRENTLY` run inside the same transaction as other migration statements?
Postgres requires it to run outside a transaction block, because it uses several transactions internally to build the index safely. The migration tool must run it as a separate, non-transactional step.
What's the danger of renaming a column in one atomic migration during a rolling deploy?
During the rollout, old and new app instances run side by side. The old ones still expect the original name, so they all start failing the instant the rename runs.
What is a 'backward-compatible' migration, and why does it matter for rolling deploys?
One that keeps the schema working for both the code running now and the code being deployed, so neither breaks while both are live.
Why do migration tools enforce a strict run order instead of letting migrations run in any order?
Later migrations assume earlier ones ran; adding a foreign key assumes the referenced table exists. Running them out of order can fail or corrupt the schema.
What happens when two developers on separate branches each create a migration numbered `0012`?
A naming collision: after merging, it's unclear which runs first. Teams fix it by hand during merge/review, or avoid it with timestamp-based filenames instead of small sequential numbers.
Why do many teams prefer timestamp-based migration filenames over small sequential integers?
Two developers are very unlikely to create migrations in the same millisecond, but both picking the next small number (say 0012) happens easily.
What's the difference between a schema migration and a data migration, and why is mixing them risky?
A schema migration changes structure (tables/columns); a data migration changes or backfills row values. Doing both in one step (add a column, then update millions of rows) risks one long statement holding a lock the whole time. Better: a fast schema change, then a batched backfill off the critical path.
Why batch a large backfill into many small updates instead of one large `UPDATE`?
One huge update can hold locks and write lots of transaction log at once, and must restart from scratch if interrupted. Batches keep transactions small, release locks in between, and keep progress if interrupted.
What does it mean for a migration to run inside a transaction, and why doesn't every database support that fully for schema changes?
In a transaction, a failure partway rolls everything back instead of leaving the schema half-changed. Postgres supports this for most DDL, but some databases (e.g. MySQL) commit DDL statements as they run, so a mid-migration failure can leave the schema partly applied.
If a migration fails partway through on a database without transactional DDL, what state is left, and what has to happen next?
Statements before the failure are committed and the rest never ran, so the schema matches neither the old nor the new version. Someone must diagnose and fix it by hand (often with a corrective migration), since re-running the file may fail again on the part that already succeeded.
Why do teams sometimes 'squash' old migrations into one baseline file, and what's lost by doing so?
A long history is slow to replay from scratch (e.g. for a fresh test database) and cluttered. Squashing merges it into one current-schema file, but loses the step-by-step record of how the schema evolved.
What's the risk of applying an autogenerated migration without reviewing it first?
Autogeneration diffs the ORM's models against the database and guesses the change. It can miss things it can't detect or generate something unsafe at production scale. Always review the generated SQL before running it.
Why might autogeneration turn a column rename into 'drop old column, add new column' instead of an actual rename?
It usually compares schemas by name and can't tell that a removed field and an added field are the same column. The drop+add it generates would delete that column's data if applied as-is.
Why run migrations as part of CI/CD instead of manually per environment?
Every environment (a fresh CI database, staging, production) then applies migrations the same way, in the same automated step as the deploy. Relying on someone to remember causes exactly the drift migrations exist to prevent.
Should a migration that adds a column run before or after deploying code that reads it? What about one dropping a column old code still reads?
Add a column before deploying the code that needs it, so it already exists. Drop a column only after every instance runs code that no longer reads it. Reversing either order breaks a rolling deploy.
What's a seed/fixture script, and why is it usually kept separate from schema migrations?
It inserts default or sample data (an initial admin user, reference lookup rows). It's kept separate because it fills data for a particular environment, rather than describing a structural change every environment must apply.
Why is it good practice for a migration to be safe to re-run, even though the tool already tracks what's applied?
It protects against edge cases like the tracking table getting out of sync or a manual retry, so re-running doesn't error or corrupt the schema. For example, guard table creation with CREATE TABLE IF NOT EXISTS.
What does `alembic upgrade head` actually do?
It applies every migration not yet recorded as run, in order, up to the latest one ('head') in the chain.
How does Alembic typically chain migrations together, and how does that differ from relying on a filename's number?
Each migration records the revision id of the one before it, forming a linked chain. Order doesn't depend on filename numbers, so it stays correct even when branches merge migrations out of numeric sequence.
Why does `op.drop_column` in a downgrade function lose data, and when is that an acceptable tradeoff?
Dropping a column deletes every value in it. That's fine for a rollback right after a failed deploy, before the column holds meaningful data, but not once it's in real use.
What's the difference between rolling back a migration and writing a new migration that reverses an earlier one?
Rolling back runs that migration's down script and un-marks it as applied. A new forward migration adds a new step and keeps history moving one way. Many teams prefer the latter once a migration has reached production, since no environment then needs to support rollbacks.
How would you change a large, actively-written-to table's column type without significant downtime?
Expand-contract: add a new column of the target type, write to both, backfill existing rows in batches, switch reads to the new column, then drop the old one in a later migration. Avoid a single blocking conversion that rewrites the whole table.
Why test a migration's down/rollback path, not just its up path?
An untested down migration may not restore the old schema, or may just error. You'd only find out during a real rollback under pressure, when you can least afford it.