What Is Alembic? Database Migrations Explained
How Alembic tracks and applies versioned schema changes for SQLAlchemy projects, and why you need it the moment a database schema has to change
Alembic manages database schema changes over time for SQLAlchemy projects — versioned migration scripts you can apply, review, and roll back, instead of hand-editing a production schema directly.
What an Alembic migration is
Each change to the schema lives in its own small Python file, called a migration or revision. The file has an upgrade() function that applies the change and a downgrade() function that undoes it, plus two identifiers: its own revision ID and the down_revision ID of the migration before it. That chain of IDs is how Alembic knows the order to apply them in, and the first file has a down_revision of None.
revision = "ae1027a6acf"
down_revision = "1975ea83b712"
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column("account", sa.Column("last_transaction_date", sa.DateTime))
def downgrade():
op.drop_column("account", "last_transaction_date")Alembic stores which revision a database is currently at, so it knows exactly what is left to apply.
The problem it solves
Once an application is running against a real database, changing the schema — adding a column, changing a type, adding an index — can’t just mean editing your models and hoping the database catches up. You need a record of what changed, in what order, and a way to apply that exact sequence of changes to any environment (local, staging, production) reliably. Alembic generates and manages that sequence as versioned migration scripts.
How it fits with SQLAlchemy
SQLAlchemy itself has no built-in migration system — Alembic, built by the same maintainer, is the standard tool that fills that gap. A typical workflow: change your SQLAlchemy models, run alembic revision --autogenerate to produce a draft migration script by diffing your models against the database’s current schema, review and adjust that script, then alembic upgrade head to apply it.
Getting started
pip install alembic
cd /path/to/yourproject
alembic init alembicThat creates an alembic.ini file and an alembic/ folder containing env.py, a template for new migrations and a versions/ folder for them. Then:
- Set
sqlalchemy.urlinalembic.inito your database URL. - Create a migration:
alembic revision -m "create account table". - Fill in its
upgrade()anddowngrade()functions, or let autogeneration do it (see below). - Apply it with
alembic upgrade head, whereheadmeans the most recent revision.
| Command | What it does |
|---|---|
alembic revision -m "message" |
Create a new, empty migration |
alembic revision --autogenerate -m "message" |
Create a migration by comparing your models to the database |
alembic upgrade head |
Apply every migration not yet applied |
alembic downgrade -1 |
Undo the most recent migration |
alembic current |
Show which revision the database is at |
alembic history |
List the migrations in order |
alembic stamp head |
Record a revision as applied without running it |
alembic heads |
Show the newest revisions (more than one means a branch) |
alembic merge -m "message" heads |
Join branches back into one line of history |
To make --autogenerate work, open env.py and set target_metadata to your models’ MetaData object, for example target_metadata = Base.metadata. The generated file is a draft that you review before applying.
A worked example: add a column, then rename one
The examples below were run with Alembic 1.20.1 and SQLAlchemy 2.1.8 against SQLite. Start with one model, and target_metadata = Base.metadata set in env.py as above:
from sqlalchemy import String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase):
pass
class Account(Base):
__tablename__ = "account"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(50))alembic revision --autogenerate -m "create account table" logs Detected added table 'account' and writes a migration containing op.create_table(...), with a matching op.drop_table('account') in downgrade(). alembic upgrade head creates the table.
Now add email: Mapped[str | None] = mapped_column(String(120)) to the model and autogenerate again. The log says Detected added column 'account.email', and the script contains one line:
op.add_column('account', sa.Column('email', sa.String(length=120), nullable=True))That is autogeneration working as intended. Review it, then run alembic upgrade head.
Autogeneration has limits
Autogeneration catches new and removed tables and columns, nullable changes and (by default) column type changes by comparing your models to the live schema. It cannot tell that you renamed something. Rename name to full_name in the model and the log reports Detected added column 'account.full_name' and Detected removed column 'account.name', and the migration it writes is:
op.add_column('account', sa.Column('full_name', sa.String(length=50), nullable=False))
op.drop_column('account', 'name')Alembic’s autogenerate docs say the same: a column rename is detected as an add and a drop, and should be hand-edited into a rename. Run as written, this does two bad things. On a table that already has a row, SQLite refused it with Cannot add a NOT NULL column with default value NULL. On a database that accepts the new column, it would still discard everything stored in the old one. Edit the generated file so each direction is a single rename:
def upgrade() -> None:
op.alter_column('account', 'name', new_column_name='full_name')
def downgrade() -> None:
op.alter_column('account', 'full_name', new_column_name='name')That ran cleanly on SQLite and the existing row kept its value. Table renames behave the same way, and the docs add that anonymously named constraints cannot be detected, so give your constraints names. Reviewing every autogenerated script before applying it is standard practice, not an edge case to worry about occasionally.
SQLite needs batch mode for some changes
SQLite cannot alter a column’s type in place. Widening email to String(200), autogenerate wrote a plain op.alter_column(...), and applying it failed with sqlite3.OperationalError: near "TYPE": syntax error. Alembic’s answer is batch mode, which rebuilds the table behind the scenes. Turn it on for autogenerate in env.py:
context.configure(
connection=connection,
target_metadata=target_metadata,
render_as_batch=True,
)Autogenerate then wraps the change in with op.batch_alter_table('account') as batch_op:, and the same upgrade succeeded with the existing row intact. Alembic’s batch docs say the mode is safe to use in all cases: on other databases it emits the usual ALTER statements, and the table rebuild only happens on SQLite. It matters most there because many projects use SQLite in development and tests even when production runs PostgreSQL, so a migration that passes on SQLite is not proof it will behave the same on your production database.
Adding Alembic to a database that already has tables
If the tables already exist, for example because they were created with Base.metadata.create_all(), running the first migration fails (table account already exists). Tell Alembic the database is already at that revision instead: alembic stamp head records the revision in the alembic_version table without running anything, and alembic current then reports it. Later alembic upgrade head runs only the migrations after it.
When two branches both add a migration
Two developers who each create a migration from the same parent leave the history with two heads. alembic upgrade head then refuses to run:
FAILED: Multiple head revisions are present for given argument 'head'; please specify a specific target revision, '<branchname>@head' to narrow to a specific head, or 'heads' for all heads
alembic heads lists both. alembic upgrade heads applies both branches, but the usual fix is a merge revision, alembic merge -m "merge branches" heads, which creates an empty migration that depends on both. After that, alembic upgrade head works again and alembic heads shows a single head.
Reading the SQL before you run it
alembic upgrade <from>:<to> --sql prints the SQL for a range of revisions instead of executing it, which is useful when a DBA wants to review changes first. For the add-column step above it printed ALTER TABLE account ADD COLUMN email VARCHAR(120); followed by the update to the alembic_version table.
What about Django?
If you’re using Django instead of SQLAlchemy, you don’t need Alembic — Django ships its own built-in migration system (makemigrations/migrate) that does the equivalent job for Django’s ORM. Alembic is specifically the answer for the SQLAlchemy ecosystem, covered alongside Django’s own migrations in SQLAlchemy vs Django ORM.
When you actually need it
The moment a SQLAlchemy-backed application has a real database with real data in it, not just a fresh schema you can recreate freely — that’s when hand-editing the schema becomes risky and Alembic’s versioned, reviewable migration history becomes worth the setup.
Frequently Asked Questions
What is Alembic used for?
Managing database schema changes over time for SQLAlchemy projects — generating versioned migration scripts, applying them in order, and rolling them back if needed, instead of hand-editing a production database’s schema directly.
Is Alembic part of SQLAlchemy?
No — it’s a separate but tightly integrated tool built by the same maintainer specifically to handle migrations, which SQLAlchemy itself doesn’t include. It’s the standard pairing for any production SQLAlchemy project.
Does Alembic generate migrations automatically?
It can autogenerate a migration script by comparing your current SQLAlchemy models against the database’s actual schema, though the generated script should always be reviewed — autogeneration catches most common changes but not everything (like renamed columns, which look like a drop-and-add unless you edit the script).
What is an Alembic migration?
A migration is a small Python file that describes one change to the database schema, with an upgrade() function that applies it and a downgrade() function that reverses it. Each file records its own revision ID and the ID of the one before it, so Alembic knows the order to apply them in.
How do I get started with Alembic?
Install it with pip, run alembic init alembic in your project to create the migration environment, set your database URL in alembic.ini, create a revision with alembic revision -m “message”, then apply it with alembic upgrade head. To autogenerate migrations from your models, point target_metadata in env.py at your SQLAlchemy MetaData.
Do you need Alembic if you’re using Django instead of SQLAlchemy?
No — Django ships its own built-in migration system (makemigrations/migrate) that serves the same purpose for Django’s ORM. Alembic is specifically the SQLAlchemy-ecosystem answer to the same problem.
Does Alembic detect a renamed column?
No. A rename is autogenerated as adding a new column and dropping the old one, which loses the data in it, and Alembic’s docs say it should be hand-edited into a rename. Replace the pair with op.alter_column(‘table’, ‘old’, new_column_name=‘new’) in upgrade() and the reverse in downgrade().
Why does Alembic fail on SQLite with a syntax error near TYPE?
SQLite cannot change a column’s type with ALTER, so a plain op.alter_column fails. Turn on batch mode by passing render_as_batch=True to context.configure() in env.py, and Alembic wraps the change in batch_alter_table, which rebuilds the table.
How do you fix Alembic’s multiple head revisions error?
Two migrations were created from the same parent. Run alembic heads to see them, then alembic merge -m merge_branches heads to create a merge revision, and alembic upgrade head will work again.
How do you start using Alembic on an existing database?
Create the first migration to match the current schema, then run alembic stamp head to record it as applied without executing it. Later migrations then apply normally with alembic upgrade head.