Skip to main content

Databases · Intermediate · 24 min

Manage database schema migrations in Python with Alembic

By Padding · Updated 18 Nov 2026
Debian 13 (postgres:18 image) · PostgreSQL 18.7 · Python 3.15 · SQLAlchemy 2.1 · Alembic 1.20

You will put a SQLAlchemy 2.1 model under Alembic 1.20 control on PostgreSQL 18, generate and correct revisions, migrate data in the same revision, upgrade and downgrade, review the SQL before it runs and merge two branch heads.

On this page

Once an app has users, you cannot drop the database and run create_all() again every time a model changes. You need each schema change written down as a small, ordered script that runs the same way on your laptop, in CI and in production, and that can be undone. Alembic is that tool for SQLAlchemy: each change is a Python file called a revision, and a one-row table in the database records which revision it is on.

In this tutorial you take a small shop's customers and orders models and put them under Alembic. You point Alembic at the models and at a database URL from the environment, let it write the first revision, then make the changes that trip people up: renaming a column, changing a default and updating existing rows to match. You read the SQL before it runs, step back with a downgrade, and merge two revisions that were written in parallel.

The commands use Alembic 1.20, SQLAlchemy 2.1 and psycopg 3.3 on Python 3.15, against PostgreSQL 18. PostgreSQL 19 came out in November 2026; nothing here changes on it. If you prefer to write migrations as plain SQL files, the clinic series does that in /tutorials/change-the-clinic-schema-safely-with-versioned-migrations.

Step 1 · Create the database and the project

Create a login role for the app. --pwprompt asks for the password twice, so it never lands in your shell history:

Bash
sudo -u postgres createuser --pwprompt storeapp

Create a database owned by that role. Alembic will run as storeapp, so the role must be allowed to create and alter tables, which owning the database gives it:

Bash
sudo -u postgres createdb --owner=storeapp store

Keep the password out of your code and out of the URL. libpq, the library under psycopg, reads it from ~/.pgpass. Create that file with private permissions before writing to it:

Bash
install -m 600 /dev/null ~/.pgpass

Open it in an editor, for example nano ~/.pgpass, and add this line, replacing the last field with the password you chose:

Text
localhost:5432:store:storeapp:the-password-you-chose

Now set the database URL. The postgresql+psycopg:// prefix tells SQLAlchemy to use psycopg 3. There is no password in it; libpq finds it in ~/.pgpass:

Bash
export DATABASE_URL="postgresql+psycopg://storeapp@localhost:5432/store"

The variable lasts for this terminal session. On a deployed app, set it in the platform's environment or secrets settings.

Create the project and add the three libraries. The ranges accept patch releases and nothing newer, so a new minor version of Alembic never arrives by surprise:

Bash
mkdir -p ~/alembic-demo
cd ~/alembic-demo
uv init --no-package --python 3.15
uv add "sqlalchemy>=2.1,<2.2" "alembic>=1.20,<1.21" "psycopg[binary]>=3.3,<3.4"

Check it worked

Bash
uv run python -c "import sqlalchemy, alembic; print(sqlalchemy.__version__, alembic.__version__)"
psql -h localhost -U storeapp -d store -X -Atc "SELECT current_user, current_database();"

The first line prints something like 2.1.9 1.20.1. The second prints storeapp|store without asking for a password. If it asks, the ~/.pgpass line does not match the host, port, database and user exactly.

Step 2 · Write the models with a naming convention

Before Alembic sees any model, decide how constraints are named. If you leave it to PostgreSQL, a unique constraint becomes something like customers_email_key and a foreign key orders_customer_id_fkey, and other databases pick different names. A later migration that drops or changes a constraint has to name it, so you want names you can predict from the model alone. A naming convention on the MetaData gives every constraint and index a name built from its table and columns.

Write the models:

Bash
cat > models.py <<'PY'
from datetime import datetime
from decimal import Decimal

from sqlalchemy import CheckConstraint, DateTime, ForeignKey, MetaData, Numeric, String, func
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

NAMING_CONVENTION = {
    "ix": "ix_%(column_0_label)s",
    "uq": "uq_%(table_name)s_%(column_0_name)s",
    "ck": "ck_%(table_name)s_%(constraint_name)s",
    "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
    "pk": "pk_%(table_name)s",
}


class Base(DeclarativeBase):
    metadata = MetaData(naming_convention=NAMING_CONVENTION)


class Customer(Base):
    __tablename__ = "customers"

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(120))
    email: Mapped[str] = mapped_column(String(254), unique=True)
    phone: Mapped[str] = mapped_column(String(20))


class Order(Base):
    __tablename__ = "orders"
    __table_args__ = (CheckConstraint("total > 0", name="total_positive"),)

    id: Mapped[int] = mapped_column(primary_key=True)
    customer_id: Mapped[int] = mapped_column(ForeignKey("customers.id"))
    total: Mapped[Decimal] = mapped_column(Numeric(10, 2))
    status: Mapped[str] = mapped_column(String(20), server_default="new")
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now()
    )
PY

The ck pattern uses %(constraint_name)s, so a CHECK constraint still needs a short name of its own (total_positive); the convention adds the table in front. phone is 20 characters because it holds numbers in international format such as +2348012345678, which matters as soon as customers come from more than one country.

Set the convention now, before the first revision. Adding it later renames nothing that already exists, and your database ends up with two naming styles.

Check it worked

Ask SQLAlchemy to print the CREATE TABLE it would send for orders, without touching the database:

Bash
uv run python -c "from sqlalchemy.schema import CreateTable; from sqlalchemy.dialects import postgresql; from models import Base; print(CreateTable(Base.metadata.tables['orders']).compile(dialect=postgresql.dialect()))"

The output includes CONSTRAINT pk_orders PRIMARY KEY (id), CONSTRAINT fk_orders_customer_id_customers FOREIGN KEY(customer_id) REFERENCES customers (id) and CONSTRAINT ck_orders_total_positive CHECK (total > 0).

Step 3 · Initialise Alembic and point it at your models

Create the migration environment in a folder called migrations:

Bash
uv run alembic init migrations

This writes alembic.ini in the project folder and, under migrations/, an env.py, a script.py.mako template for new revisions and an empty versions/ folder. Commit all of them with your code.

env.py is the script Alembic runs for every command. Replace the generated one with this version, which reads the URL from DATABASE_URL and hands Alembic your models' metadata so it can compare them with the database:

Bash
cat > migrations/env.py <<'PY'
import os
from logging.config import fileConfig

from alembic import context
from sqlalchemy import create_engine, pool

from models import Base

config = context.config
if config.config_file_name is not None:
    fileConfig(config.config_file_name)

target_metadata = Base.metadata

DATABASE_URL = os.environ.get("DATABASE_URL")
if not DATABASE_URL:
    raise SystemExit("Set DATABASE_URL, for example postgresql+psycopg://user@host:5432/db")


def run_migrations_offline() -> None:
    """Write SQL to stdout instead of running it (alembic ... --sql)."""
    context.configure(
        url=DATABASE_URL,
        target_metadata=target_metadata,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
    )
    with context.begin_transaction():
        context.run_migrations()


def run_migrations_online() -> None:
    engine = create_engine(DATABASE_URL, poolclass=pool.NullPool)
    with engine.connect() as connection:
        context.configure(connection=connection, target_metadata=target_metadata)
        with context.begin_transaction():
            context.run_migrations()


if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online()
PY

from models import Base works because the generated alembic.ini has prepend_sys_path = ., which puts the project folder on Python's import path. NullPool opens one connection for the run and closes it, which is all a migration command needs. literal_binds=True in offline mode writes values into the SQL itself, since there is no connection to send them on.

alembic.ini still has a line sqlalchemy.url = driver://user:pass@localhost/dbname. This env.py never reads it. Delete that line in your editor so nobody is tempted to put a real password in a committed file.

Check it worked

Bash
uv run alembic current

Alembic connects and prints two log lines, something like INFO [alembic.runtime.migration] Context impl PostgresqlImpl. and Will assume transactional DDL., and no revision, because the database has none yet. An error that says Set DATABASE_URL means the variable is not set in this terminal.

Step 4 · Generate the first revision and apply it

--autogenerate compares the models with the database and writes the difference as a revision. --rev-id sets the revision's ID; without it Alembic picks a random 12-character one. Short ordered IDs are easier to read in a tutorial, and either works in a team:

Bash
uv run alembic revision --autogenerate --rev-id 0001 -m "create customers and orders"
cat migrations/versions/0001_*.py

Alembic logs what it found, something like Detected added table 'customers', and writes migrations/versions/0001_create_customers_and_orders.py. Read it before you run it. The parts to look at:

  • down_revision = None says this is the first revision. Every later one names its parent, and that chain is the order Alembic runs them in.
  • upgrade() has op.create_table('customers', ...) then op.create_table('orders', ...), in an order that respects the foreign key. downgrade() drops them in reverse.
  • Constraint names are wrapped in op.f(), such as sa.UniqueConstraint('email', name=op.f('uq_customers_email')). op.f() marks a name as final, so the naming convention is not applied to it a second time.
  • server_default='new' and server_default=sa.text('now()') are there: autogenerate picks up defaults on new columns.

The comment # ### commands auto generated by Alembic - please adjust! ### means what it says. The file is a draft you are expected to edit.

Apply it:

Bash
uv run alembic upgrade head

head means the newest revision. On PostgreSQL, Alembic runs the whole upgrade in one transaction, so if a statement fails part-way, the schema is left as it was.

Add some rows, so the next migrations have real data to keep:

Bash
psql -h localhost -U storeapp -d store -X -v ON_ERROR_STOP=1 -c "INSERT INTO customers (name, email, phone) VALUES ('Amara Okafor', 'amara@example.com', '+2348012345678'), ('Kwame Mensah', 'kwame@example.com', '+233201234567');" -c "INSERT INTO orders (customer_id, total) VALUES (1, 4500.00), (1, 1200.00), (2, 800.00);"

If your tables already exist because the app ran create_all(), generate the first revision against an empty database as above, then run uv run alembic stamp head once against the existing database. stamp records the revision without running it.

Check it worked

Bash
uv run alembic current
psql -h localhost -U storeapp -d store -X -Atc "SELECT conname FROM pg_constraint WHERE conrelid IN ('customers'::regclass, 'orders'::regclass) AND contype <> 'n' ORDER BY conname;"

alembic current prints 0001 (head). The query lists ck_orders_total_positive, fk_orders_customer_id_customers, pk_customers, pk_orders and uq_customers_email: every name came from your convention. (contype <> 'n' hides the NOT NULL constraints, which PostgreSQL 18 also lists in pg_constraint.) Alembic also created a table called alembic_version holding one row, 0001.

Step 5 · See what autogenerate gets wrong

Two changes arrive. The team wants the column called phone_number, and new orders should start as pending instead of new. Rewrite models.py with both changes; only the phone_number line and the status default differ from before:

Bash
cat > models.py <<'PY'
from datetime import datetime
from decimal import Decimal

from sqlalchemy import CheckConstraint, DateTime, ForeignKey, MetaData, Numeric, String, func
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

NAMING_CONVENTION = {
    "ix": "ix_%(column_0_label)s",
    "uq": "uq_%(table_name)s_%(column_0_name)s",
    "ck": "ck_%(table_name)s_%(constraint_name)s",
    "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
    "pk": "pk_%(table_name)s",
}


class Base(DeclarativeBase):
    metadata = MetaData(naming_convention=NAMING_CONVENTION)


class Customer(Base):
    __tablename__ = "customers"

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(120))
    email: Mapped[str] = mapped_column(String(254), unique=True)
    phone_number: Mapped[str] = mapped_column(String(20))


class Order(Base):
    __tablename__ = "orders"
    __table_args__ = (CheckConstraint("total > 0", name="total_positive"),)

    id: Mapped[int] = mapped_column(primary_key=True)
    customer_id: Mapped[int] = mapped_column(ForeignKey("customers.id"))
    total: Mapped[Decimal] = mapped_column(Numeric(10, 2))
    status: Mapped[str] = mapped_column(String(20), server_default="pending")
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now()
    )
PY

Generate a revision and read it:

Bash
uv run alembic revision --autogenerate --rev-id 0002 -m "rename phone and set status default"
cat migrations/versions/0002_*.py

Look at upgrade(). It has two operations, and neither is what you meant:

Text
op.add_column('customers', sa.Column('phone_number', sa.String(length=20), nullable=False))
op.drop_column('customers', 'phone')

Autogenerate cannot tell a rename from a new column plus a removed one, because both look the same when it compares names. Run as written, this revision fails on the add_column, since a NOT NULL column with no default cannot be added to a table that has rows. Had the column been nullable, it would have succeeded and deleted every phone number.

There is also nothing about status. By default autogenerate does not compare server defaults on existing columns. You can turn that on with compare_server_default=True in context.configure(), but the Alembic docs warn it cannot always be accurate, so many teams leave it off and write default changes by hand. Autogenerate also misses table renames and changes to CHECK constraints. Treat every generated revision as a first draft.

Check it worked

upgrade() in your 0002 file shows add_column and drop_column for customers, and the word pending appears nowhere in the file.

Step 6 · Fix the revision and migrate the data with it

Replace the draft with a revision that does what you meant. This deletes only the 0002 file you generated in the last step; 0001 is untouched:

Bash
rm migrations/versions/0002_*.py
cat > migrations/versions/0002_rename_phone_and_set_status_default.py <<'PY'
"""rename phone and set status default

Revision ID: 0002
Revises: 0001
"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa

revision: str = "0002"
down_revision: Union[str, Sequence[str], None] = "0001"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None

# A minimal description of the table, for the data step only. Do not import
# models.py here: the models keep changing, and this file must not.
orders = sa.table("orders", sa.column("status", sa.String))


def upgrade() -> None:
    op.alter_column("customers", "phone", new_column_name="phone_number")
    op.alter_column("orders", "status", server_default="pending")
    op.execute(orders.update().where(orders.c.status == "new").values(status="pending"))


def downgrade() -> None:
    op.execute(orders.update().where(orders.c.status == "pending").values(status="new"))
    op.alter_column("orders", "status", server_default="new")
    op.alter_column("customers", "phone_number", new_column_name="phone")
PY

alter_column(..., new_column_name=...) renames the column in place, so the data stays. server_default="pending" changes the default for future inserts only; existing rows keep new. The UPDATE moves those rows to pending in the same revision, so the schema and the data change together and roll back together.

The data step uses sa.table() rather than the Order model on purpose. A revision has to run correctly years from now, against whatever models.py looks like then. If it imported the model and someone later renamed status, this old revision would break.

downgrade() undoes the steps in reverse order. It can only be as good as the information it has: here every pending row becomes new, which is right only because pending did not exist before this revision. When a change throws information away, say so in a comment, or make downgrade() raise an error rather than pretend.

Check it worked

Bash
uv run alembic history

The output is something like:

Text
0001 -> 0002 (head), rename phone and set status default
<base> -> 0001, create customers and orders

Step 7 · Review the SQL, then upgrade and downgrade

Before a migration touches a shared database, read the exact SQL it will send. --sql runs Alembic in offline mode: it writes the statements to standard output and connects to nothing. 0001:0002 is the range to render:

Bash
uv run alembic upgrade 0001:0002 --sql > review-0002.sql
cat review-0002.sql

The file holds something like this, between BEGIN; and COMMIT;:

Text
ALTER TABLE customers RENAME phone TO phone_number;
ALTER TABLE orders ALTER COLUMN status SET DEFAULT 'pending';
UPDATE orders SET status='pending' WHERE orders.status = 'new';
UPDATE alembic_version SET version_num='0002' WHERE alembic_version.version_num = '0001';

This is also how you hand a migration to a database administrator who runs it with psql -f, or attach it to a pull request so a reviewer sees the SQL and not only the Python.

Take a backup of any database that matters before you migrate it (see /tutorials/back-up-and-restore-postgresql-with-pg-dump). Then apply the revision:

Bash
uv run alembic upgrade head
psql -h localhost -U storeapp -d store -X -c "SELECT o.id, c.name, c.phone_number, o.status FROM orders o JOIN customers c ON c.id = o.customer_id ORDER BY o.id;"

The three orders show their customers' phone numbers under phone_number, and each has status pending.

Now step back one revision, check the old shape is back, and go forward again:

Bash
uv run alembic downgrade -1
psql -h localhost -U storeapp -d store -X -c "SELECT c.phone, o.status FROM orders o JOIN customers c ON c.id = o.customer_id ORDER BY o.id;"
uv run alembic upgrade head

-1 means one revision back from the current one. You can also name a target, such as uv run alembic downgrade 0001, or base to undo everything. Running a downgrade and the upgrade again on a copy of the data is the quickest way to find a downgrade() that does not work, before you need it.

Check it worked

The query between the two commands showed a phone column and status new on all three orders. After the final upgrade, insert an order without a status and see the new default:

Bash
psql -h localhost -U storeapp -d store -X -Atc "INSERT INTO orders (customer_id, total) VALUES (2, 650.00) RETURNING status;"
uv run alembic current

The insert prints pending (then INSERT 0 1), and alembic current prints 0002 (head).

Step 8 · Merge two heads

In a team, two people often branch from the same revision. You add a city column to customers on your branch; a colleague adds an index on orders.created_at on theirs. Both revisions say down_revision = "0002". When both branches are merged in git, the chain forks: Alembic now has two heads.

Create the two revision files as they would arrive from the two branches:

Bash
cat > migrations/versions/0003_add_customer_city.py <<'PY'
"""add customer city

Revision ID: 0003
Revises: 0002
"""
from alembic import op
import sqlalchemy as sa

revision = "0003"
down_revision = "0002"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.add_column("customers", sa.Column("city", sa.String(length=80), nullable=True))


def downgrade() -> None:
    op.drop_column("customers", "city")
PY
cat > migrations/versions/0004_index_order_dates.py <<'PY'
"""index order dates

Revision ID: 0004
Revises: 0002
"""
from alembic import op

revision = "0004"
down_revision = "0002"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.create_index(op.f("ix_orders_created_at"), "orders", ["created_at"])


def downgrade() -> None:
    op.drop_index(op.f("ix_orders_created_at"), table_name="orders")
PY
uv run alembic heads

alembic heads prints two lines, 0003 (head) and 0004 (head). Try to upgrade:

Bash
uv run alembic upgrade head

It stops with Multiple head revisions are present for given argument 'head' and changes nothing. Alembic will not guess which order the two should run in. Make a merge revision whose parents are both heads:

Bash
uv run alembic merge -m "merge city and order index" --rev-id 0005 heads
uv run alembic heads

The new file has down_revision = ('0003', '0004') and empty upgrade() and downgrade() functions. Its only job is to join the chain again. If the two branches had touched the same column, this is where you would add the code that reconciles them.

Bring the models in line with both changes, then upgrade:

Bash
cat > models.py <<'PY'
from datetime import datetime
from decimal import Decimal

from sqlalchemy import CheckConstraint, DateTime, ForeignKey, MetaData, Numeric, String, func
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

NAMING_CONVENTION = {
    "ix": "ix_%(column_0_label)s",
    "uq": "uq_%(table_name)s_%(column_0_name)s",
    "ck": "ck_%(table_name)s_%(constraint_name)s",
    "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
    "pk": "pk_%(table_name)s",
}


class Base(DeclarativeBase):
    metadata = MetaData(naming_convention=NAMING_CONVENTION)


class Customer(Base):
    __tablename__ = "customers"

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(120))
    email: Mapped[str] = mapped_column(String(254), unique=True)
    phone_number: Mapped[str] = mapped_column(String(20))
    city: Mapped[str | None] = mapped_column(String(80))


class Order(Base):
    __tablename__ = "orders"
    __table_args__ = (CheckConstraint("total > 0", name="total_positive"),)

    id: Mapped[int] = mapped_column(primary_key=True)
    customer_id: Mapped[int] = mapped_column(ForeignKey("customers.id"))
    total: Mapped[Decimal] = mapped_column(Numeric(10, 2))
    status: Mapped[str] = mapped_column(String(20), server_default="pending")
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now(), index=True
    )
PY
uv run alembic upgrade head

Check it worked

Bash
uv run alembic heads
uv run alembic check

alembic heads prints a single line, 0005 (head). alembic check compares the models with the upgraded database and prints No new upgrade operations detected. If someone changes a model and forgets the revision, it exits with an error and lists the difference, which makes it a useful step in CI after alembic upgrade head on a scratch database.

Step 9 · Clean up

This deletes the project folder, the store database with every row in it and the storeapp role. Leave the project folder first:

Bash
cd ~
rm -rf ~/alembic-demo
sudo -u postgres dropdb store
sudo -u postgres dropuser storeapp
unset DATABASE_URL

Open ~/.pgpass in your editor and delete the localhost:5432:store:storeapp:... line. If it was the only line, delete the file with rm ~/.pgpass.

Check it worked

Bash
sudo -u postgres psql -X -Atc "SELECT count(*) FROM pg_database WHERE datname = 'store';" -c "SELECT count(*) FROM pg_roles WHERE rolname = 'storeapp';"

Both lines print 0.

Next steps

  • Write migrations as plain SQL files and apply them with checks that block risky changes, on the clinic booking database: /tutorials/change-the-clinic-schema-safely-with-versioned-migrations.
  • Use the same SQLAlchemy models inside a Flask app: /tutorials/store-data-in-a-flask-app-with-sqlalchemy.
  • See the psycopg layer under SQLAlchemy, including transactions and SQLSTATE errors: /tutorials/connect-to-postgresql-from-python-with-psycopg.
  • Make sure you can restore before you migrate production: /tutorials/back-up-and-restore-postgresql-with-pg-dump.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.