sqlx migrations

Learn what a sqlx migration is, how versioned SQL files build a database schema step by step, and how the _sqlx_migrations table tracks what has run

A migration is a versioned SQL file that changes the database schema, one file per change, applied in order. The schema is the shape of the database: its tables, its columns, and its constraints. A migration says how to move the schema from one shape to the next, and SQLx records each one it applies, so a migration runs exactly once, on every machine, in the same order. Migrations are how a project's database grows up alongside its code.

Where This Fits

The query pages assumed a users table already existed, with four columns and two rows, and they never said where it came from. This page is the answer: the table came from a migration. The query macros need the schema to check against, the handlers need the table to query, and the migration is the file that creates both. The command line tool that creates and runs these files has its own page next, and the command that runs them has the page after that. This page is about the files themselves: what they are, how they are named, and how SQLx tracks them.

Think of migrations as the chapters of a building's renovation log. The first chapter pours the foundation. The second adds the walls. The third adds the roof. Each chapter says what changed and in what order, and nobody redoes the foundation when adding the roof. If a new builder joins the project, they read the log from the start and apply each chapter in turn, and their building ends up identical to everyone else's. The database is the building, and the migration files are the log.

The Smallest Working Version

A migration is a plain SQL file in a migrations directory at the project root. The project's first migration creates the users table:

migrations/20261114062321_create_users_table.sql
CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    name TEXT NOT NULL,
    email TEXT NOT NULL UNIQUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

The file name has two parts. 20261114062321 is the version, a timestamp in the form year, month, day, hour, minute, second: 2026, 11, 14, 06, 23, 21. create_users_table is the description, a short name for the change, written with underscores. The version decides the order: SQLx sorts migrations by version number and applies them from the smallest to the largest. The description is for humans, and it is recorded in the tracking table so a person reading the history can see what each version did.

The SQL inside is ordinary PostgreSQL. SERIAL is an integer column that fills itself with increasing numbers, one per row, which is how the id gets its value without the program supplying one. PRIMARY KEY says the id identifies each row uniquely. TEXT NOT NULL says the column holds text and must always have a value. UNIQUE on the email says no two rows may share an email address. TIMESTAMPTZ NOT NULL DEFAULT NOW() says the column holds a timestamp with a time zone, must always have a value, and defaults to the current time when a row is inserted without one. The created_at column is how the database stamps each row with its creation time, without the program doing anything.

Why Files Instead of Creating Tables by Hand

A table created by hand, typed into a database console, exists on one machine only. A teammate's machine does not have it, the test database does not have it, and the production server does not have it. Each machine drifts apart, and a query that works in development fails everywhere else with a missing table.

A migration file fixes that by making the schema part of the project. The file is committed to version control with the code, so every machine that has the code has the schema changes too. Applying the files in order rebuilds the same schema on any machine, from nothing, and the tracking table makes sure no file is applied twice. The schema becomes reproducible, which is the same property the code already has: check it out, build it, run it, and it works.

The second reason is history. A database that has been changed by hand has no record of how it got its shape. A migration history is the record: each file is one change, with a version that says when it happened and a description that says what it was. When a column's purpose is questioned months later, the migration that added it is the answer.

The Tracking Table

SQLx tracks applied migrations in a table it creates itself, named _sqlx_migrations, inside the same database. The table is created automatically the first time migrations run, and the program never writes to it by hand. Each row records one applied migration: its version, its description, when it was applied, and a checksum of the file's contents.

migration 20261114062321 | create users table | 8be13c90c75446bc8b148d0e9b5bb6da038cf317db0ff015687159fb6a573dbf98f4635d7e647f8fec1b96fe7338507e

The version is the timestamp from the file name. The description is the name from the file, with underscores turned into spaces. The checksum is a hash of the file's contents, a long string of hexadecimal digits that changes if even one character of the file changes. SQLx compares the stored checksum with the file on disk every time migrations run, and if they differ, it stops with an error instead of applying anything:

error: migration 20261114062321 was previously applied but has been modified

That error is the tracking table doing its job. An applied migration is history, and history must not change. If a migration was wrong, the fix is a new migration that corrects it, not an edit to the old one. The checksum makes that rule enforceable: the file cannot be quietly rewritten after it has run.

Never Edit a Migration That Has Already Run:

Once a migration has been applied anywhere, its file is frozen. Editing it changes its checksum, and the next migration run fails with the modified-migration error on every machine that already applied it. A mistake in an applied migration is fixed by a new migration, never by rewriting the old file. A migration that has not yet run anywhere can still be edited freely.

Simple and Reversible Migrations

Migrations come in two kinds. A simple migration is one file, <version>_<description>.sql, with the change and nothing else. It can only go forward. The project's users migration is simple, and most migrations are simple, because most schema changes, adding a table or a column, never need to be undone.

A reversible migration is a pair of files with the same version and description: <version>_<description>.up.sql for the change, and <version>_<description>.down.sql for its reverse. The down file says how to undo the up file: if the up file creates a table, the down file drops it. Reversible migrations exist so a deployment can be rolled back, and the revert command runs the down file of the most recent migration. The trade is that the down file must be written by hand, and it must be correct: a down file that drops the wrong thing destroys data, and reverting does not restore rows that the up migration discarded.

The CLI creates a reversible pair when asked with the -r flag, and it detects which kind the project already uses: once the latest migration is reversible, new ones are created reversible too. A project picks one kind and stays with it, because mixing them makes the history harder to read.

How Migrations Run, in Order

Migrations run in version order, smallest first, and only the ones that have not yet run. The runner compares the files on disk with the rows in the tracking table, and every file whose version is missing from the table is pending. It applies the pending files in order, records each one in the tracking table, and stops at the first failure. A second run with nothing pending does nothing and succeeds, which is why migrations are safe to run on every deployment: the command is idempotent, meaning running it twice has the same effect as running it once.

Each migration runs inside a transaction, which is a unit of work that either completes fully or not at all. If a migration file has two statements and the second fails, the first is rolled back, and the database is left as it was before the file ran. The tracking table is updated in the same transaction, so a failed migration leaves no row behind, and the next run tries it again from the start. PostgreSQL supports transactional schema changes, which is what makes this guarantee possible. A file that must not run in a transaction, such as one that creates an index without locking the table, opts out with a -- no-transaction comment as its first line.

Growing the Schema With a Second Migration

The project's second change adds a column to the users table. It is a new file, with a later version, and it changes only what is new:

migrations/20261114071400_add_nickname_column.up.sql
ALTER TABLE users ADD COLUMN nickname TEXT;
migrations/20261114071400_add_nickname_column.down.sql
ALTER TABLE users DROP COLUMN nickname;

This pair is reversible, so it has an up file and a down file. The up file adds the column, and the down file removes it. The version is later than the first migration's, so it runs after it. The description says what the change is. Nothing in the first migration's file changes, and nothing in the second file repeats the table creation. Each file says only what is new, and the history stays readable: create the table, then add the column.

A migration that adds a NOT NULL column to a table with existing rows needs a default value, because the existing rows have no value for the new column. The statement would be ADD COLUMN nickname TEXT NOT NULL DEFAULT '', which fills the existing rows with an empty string and requires a value for future rows. A migration that adds a column without a default to a non-empty table fails, and the error names the missing value. The rule is to think about the existing rows when writing the change, not only about the future ones.

What Migrations Are Not

Migrations are for schema, not for data. A migration that inserts seed data, the first users or the default settings, mixes two concerns: the shape of the database and its contents. Seed data belongs in a separate step, a script or a fixture the tests load, because seed data changes often and migrations never change after running. The one exception is a data migration, where a schema change requires existing rows to be transformed, such as splitting one column into two. That SQL lives in the migration because it must run at the same time as the schema change, in the same transaction.

Migrations are also not a backup. A migration history can rebuild an empty database to the current schema, but it cannot restore the rows. Backups are a separate concern, handled by the database's own tools, and a migration is no substitute for one.

Common Beginner Mistakes

Editing an Applied Migration

The checksum error above is the symptom. The cause is editing a file that has already run, to fix a mistake or to add a column that was forgotten. The fix is a new migration with the correction, applied after the old one. The old file stays exactly as it was, and the history records both the mistake and its fix, which is honest and auditable.

Two Migrations With the Same Version

Two files created in the same second get the same timestamp version, and the runner cannot order them. The fix is to rename one with a later version, or to recreate it so the timestamp differs. The CLI generates the timestamp from the current time, so two migrations created quickly in succession can collide. Creating them one at a time, or checking the file names after creation, avoids the problem.

A Migration That Depends on Another Database

A migration file runs against one database, the one DATABASE_URL names. A file that references a table in another database, or that assumes a table created by a different project's migrations, fails on a fresh machine where that other database does not exist. Each project's migrations must be self-contained: they build everything the project's queries need, from nothing, in order.

Forgetting That Down Files Are Hand-Written

The CLI creates the down file empty, with a placeholder comment. An empty down file reverts nothing, and a revert that runs it reports success while leaving the change in place. The down file must be filled in by hand, with the exact reverse of the up file, and tested by running the migration forward and then reverting it. A down file that is never tested is a down file that does not work.

The Migration Directory in One Place

Here is the project's migration directory after two changes:

migrations/
    20261114062321_create_users_table.sql
    20261114071400_add_nickname_column.up.sql
    20261114071400_add_nickname_column.down.sql

One simple migration and one reversible pair, in version order, each file saying one thing. The directory is the whole schema history, and it is all a new machine needs, with the migration command, to build the database the application expects.

Summary

A migration is a small, frozen, ordered fact about the schema: one file, one change, one version, applied once and recorded forever. The insight worth keeping is the immutability. The checksum is not bureaucracy, it is the guarantee that two machines with the same migration files have the same database, and that a change to history is caught instead of silently applied.

The files are only half the story. The other half is the tool that creates them, runs them, and keeps the tracking table honest, and that tool is the command line companion to this crate.