Database schema migrations for SQLAlchemy · version-control your DB · verified against Alembic 1.19 (2026)

Alembic cheat sheet

Alembic is the migration tool for SQLAlchemy (by the same author): it version-controls your database schema the way git versions code. You describe schema changes as ordered revision scripts — each with an upgrade() and a downgrade() — and Alembic applies or rolls them back in dependency order. Autogenerate diffs your models against the live DB to write most scripts for you. This sheet targets Alembic 1.19.

setup & init config (env.py) revisions & apply op.* operations inspect & branch gotcha most common

Verified 2026-08-24 against the official docs at alembic.sqlalchemy.org (Alembic 1.19). Works with any SQLAlchemy-supported DB; the op.* API and autogenerate diff your MetaData. Pairs with SQLModel / SQLAlchemy models — point target_metadata at their MetaData.

Outline

init once, wire env.py to your models, then loop: revision --autogenerate → review the script → upgrade head. Roll back with downgrade; inspect with current/history.

Set up

  1. 1 · Install & init
  2. 2 · Wire up env.py
  3. 3 · Create revisions

Change schema

  1. 4 · op.* operations
  2. 5 · Apply & roll back
  3. 6 · Data & batch (SQLite)

Operate

  1. 7 · Inspect & navigate
  2. 8 · Branches & merges
  3. 9 · Gotchas
  4. Worth memorizing

Set up

Initialize the migration environment and connect it to your models.

1Install & init1.19
2Wire up env.pyconnect models + DB
3Create revisionsthe migration loop

Change schema

Fill upgrade()/downgrade() with op.* calls, then apply.

4op.* operationsinside upgrade()/downgrade()
5Apply & roll backupgrade / downgrade
6Data & batch (SQLite)data migrations + ALTER on SQLite

Operate

See where you are, and manage divergent history.

7Inspect & navigatewhere am I?
8Branches & mergesdivergent history
!Common gotchasread before shipping

Worth memorizing

alembic init alembicscaffolds ini + env.py + versions/
target_metadata = Base.metadatawhat autogenerate diffs against
revision --autogenerate -m "..."then ALWAYS review the script
down_revision chains scriptsGUIDs, not sequence numbers
op.create_table / add_column / alter_columnthe op.* schema API
upgrade head / downgrade -1apply to newest / roll back one
upgrade head --sqloffline: emit SQL, don't run
current / history / headswhere am I; >1 head = branched
stamp headset version pointer, run nothing
merge headsreconcile divergent branches
batch_alter_table for SQLiterebuild table so ALTER works
compare_type / compare_server_defaultoff by default — enable in env.py