# Schema Migrations

> Change a database schema with numbered, versioned files that run once, in order, so every environment ends up identical.

Subject: SQL | Lesson 44 of 44 | 7 min read
Interactive lesson: https://codewithanimation.in/sql/migrations
Previous: [Connection Pooling](https://codewithanimation.in/sql/connection-pooling.md)

## Version control for the database shape

A **migration** is a file with the SQL that moves a database from one version of its schema to the next: create a table, add a column, add a rule. Migrations are numbered, kept in your repository next to the code, and applied in order by a **migration tool**, such as Flyway.

The tool keeps a **history table** inside the database that records which migrations have already run, together with a **checksum** (a fingerprint) of each file.

## Same schema on every machine

Your laptop, the test server and production must have the same tables, or the code that works on one fails on another. Typing `ALTER TABLE` by hand on each one does not scale. With migrations, to bring any database up to date you run the tool, and it applies what is missing, once, in order.

## Run migrate

```
V1__create_products.sql
V2__seed_products.sql
V3__add_price.sql
V4__price_is_required.sql
```

On an empty database the tool applies V1, V2 and V3 in version order and records each in the history table. Run it again and nothing happens, because every file is already there: running migrate is safe to repeat.

V4 runs `ALTER TABLE products ALTER COLUMN price SET NOT NULL`, but the rows added in V2 have no price, so PostgreSQL refuses: `column "price" of relation "products" contains null values`. Each migration is one transaction and PostgreSQL can roll back DDL, so V4 leaves no trace: the table is exactly as V3 left it, and V4 is not in the history.

Because V4 was never applied, you can simply fix the file. Fill in the prices first, then add the rule, and run migrate again. Now V4 is applied.

## Common mistake: Never edit a migration that has run

Once a migration has been applied anywhere, treat its file as read-only. If you edit V2 afterwards, its checksum no longer matches the one in the history, and the tool refuses to run anything: validation fails. That is the point of the checksum. Other databases may already have run the old version of V2, so editing it would make your databases silently different.

To change something that has already been applied, add a new migration (V5) that fixes it going forward. This is called rolling forward.

Mind the data as well as the shape. Adding a rule to a table that already holds rows, as in V4, works only if the data obeys it. Test migrations on a copy of real data before you run them on production.

Dropping a column or table destroys data for good, and the code that is still running may still use it. Add the new column first, move the code over, and drop the old column in a later migration.

## Tip: Small files, one change each

Keep each migration small and about one change, give it a clear name, and review it like code. Run migrations automatically in your deploy pipeline, and never change one after it has been shared.

## Try it: Replay a migration tool

Press Run migrate and read the failure. Then fix V4 and run again. Next edit V2 and run migrate, and finally add V5.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/sql/migrations

## Check yourself

### Question 1

You run migrate twice in a row, with no new files. What happens the second time?

- A. Nothing: every file is already in the history
- B. All the files run again
- C. The tool drops the tables and starts again

Correct answer: A

The history table lists the applied versions, so only files that are not in it are run.

- Why not B: Each versioned migration is applied exactly once. The history table records what has run.
- Why not C: A migration tool never rebuilds the database. It only applies what is missing.

### Question 2

V4 fails half way. In PostgreSQL, what is the state of the database after the failed migration?

- A. Exactly as V3 left it, because the failed migration was rolled back
- B. Half of V4 is applied
- C. The whole database is empty

Correct answer: A

Each migration is one transaction. A failure rolls back that migration only, and the earlier ones remain.

- Why not B: A migration runs as one transaction, and PostgreSQL can roll back DDL, so it is all or nothing.
- Why not C: V1 to V3 were committed earlier and stay applied.

### Question 3

You find a typo in V2, which was applied last week. What is the right fix?

- A. Add a new migration that corrects it
- B. Edit V2 and run migrate again
- C. Delete the V2 row from the history table

Correct answer: A

Applied migrations are read-only. Roll the change forward with a new file.

- Why not B: The checksum will no longer match, so validation fails. And other databases may already have run the old V2.
- Why not C: That would make the tool run V2 again on a database that already has its changes.

## Remember this

- A migration is a numbered SQL file. A tool applies the missing ones once, in order, and records them in a history table with a checksum.
- Running migrate again is safe: applied files are skipped.
- Each migration is one transaction. In PostgreSQL a failed one leaves no trace, because DDL can be rolled back.
- Never edit a migration that has run, because validation will fail. Add a new one that fixes it.
