15 min read

Alembic Explained: A Beginner’s Guide to Database Migrations with SQLAlchemy

Nasrul Hasan
Nasrul Hasan
Nasrul Hasan
Cover Image for Alembic Explained: A Beginner’s Guide to Database Migrations with SQLAlchemy

Alembic Explained: A Beginner's Guide to Database Migrations with SQLAlchemy

If you're building applications with Python and SQLAlchemy, you've probably faced this situation:

You modify your database model by adding a new column or changing a table, but now your database no longer matches your code.

Should you delete the database and recreate it?

That might work during the first few days of development, but it quickly becomes impossible once your application has real users and production data.

This is exactly why Alembic exists.

Alembic is the official database migration tool for SQLAlchemy. It helps you safely evolve your database schema over time without losing data.

In this guide, you'll learn everything you need to get started with Alembic—even if you've never used database migrations before.


What is Alembic?

Alembic is a lightweight migration tool that manages changes to your database schema.

Instead of manually writing SQL every time your database changes, Alembic creates migration files that describe those changes.

Think of it like Git for your database schema.

Whenever your models change, Alembic records those changes as migration scripts that can be applied or rolled back whenever needed.


Why Use Alembic?

Imagine you have a simple User table.

Initially:

User
-----
id
name
email
asciidoc

Later you decide to add:

created_at
ebnf

Without Alembic you would need to:

  • Write SQL manually

  • Remember every change

  • Update development and production databases separately

  • Hope nothing breaks

With Alembic:

  • Generate a migration

  • Review it

  • Apply it

  • Done

Every developer on your team gets the exact same database structure.


Installing Alembic

Install using pip:

pip install alembic
cmake

If you're using SQLAlchemy:

pip install sqlalchemy alembic
cmake

Verify installation:

alembic --help
ada

Initializing Alembic

Inside your project:

alembic init migrations
csharp

You'll see something like:

project/
│
├── migrations/
│   ├── versions/
│   ├── env.py
│   └── script.py.mako
│
├── alembic.ini
└── app.py
stylus

Alembic creates everything needed to manage migrations.


Configure the Database URL

Open:

alembic.ini

Update:

sqlalchemy.url = sqlite:///app.db
ini

For PostgreSQL:

sqlalchemy.url = postgresql://user:password@localhost/mydatabase
bash

For MySQL:

sqlalchemy.url = mysql+pymysql://user:password@localhost/mydatabase
bash

Creating Your First SQLAlchemy Model

Example:

from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True)
    name = Column(String(100))
    email = Column(String(100))
angelscript

Alembic compares your models against the database to generate migrations automatically.


Connecting Alembic to Your Models

Open:

migrations/env.py
bash

Locate:

target_metadata = None
ini

Replace it with:

from models import Base

target_metadata = Base.metadata
angelscript

Now Alembic knows which models to inspect.


Creating Your First Migration

Generate a migration:

alembic revision --autogenerate -m "Create users table"
css

Alembic creates a file like:

migrations/versions/
awk

Example:

def upgrade():
    op.create_table(
        "users",
        sa.Column("id", sa.Integer(), nullable=False),
        sa.Column("name", sa.String(length=100)),
        sa.Column("email", sa.String(length=100)),
        sa.PrimaryKeyConstraint("id"),
    )
scss

Always review generated migrations before applying them.


Applying Migrations

Run:

alembic upgrade head
bash

This updates your database to the latest version.


Viewing Migration History

To see migration history:

alembic history
bash

Current version:

alembic current
ebnf

Latest revision:

alembic heads
ebnf

Making Schema Changes

Suppose you update your model:

created_at = Column(DateTime)
ini

Generate another migration:

alembic revision --autogenerate -m "Add created_at"
dsconfig

Alembic detects:

op.add_column(
    "users",
    sa.Column("created_at", sa.DateTime())
)
sas

Then apply it:

alembic upgrade head
bash

No data is lost.


Rolling Back Changes

Need to undo a migration?

Rollback one step:

alembic downgrade -1
apache

Rollback to a specific revision:

alembic downgrade <revision_id>
xml

This makes testing and fixing mistakes much easier.


Important Alembic Commands

Command

Purpose

alembic init migrations

Initialize Alembic

alembic revision -m "msg"

Create migration

alembic revision --autogenerate

Auto detect changes

alembic upgrade head

Apply latest migrations

alembic downgrade -1

Rollback one migration

alembic current

Show current version

alembic history

Show migration history

alembic heads

Show latest revision


Project Workflow

A common development workflow looks like this:

  1. Update your SQLAlchemy models.

  2. Generate a migration.

  3. Review the generated migration.

  4. Apply the migration.

  5. Commit both your code and migration file to version control.

This ensures every environment stays in sync.


Best Practices

Follow these tips for smoother database migrations:

  • Never edit old migration files after they have been shared.

  • Always review autogenerated migrations before running them.

  • Keep migration messages meaningful.

  • Commit migration files to Git.

  • Test migrations on a development database first.

  • Back up production databases before major schema changes.

  • Avoid making multiple unrelated schema changes in a single migration.


Common Mistakes Beginners Make

Forgetting to configure
target_metadata
ebnf

Alembic won't detect your models if
target_metadata
ebnf
isn't set.

Skipping migration review

Autogenerated migrations are helpful but not always perfect.

Editing the database manually

If you make manual schema changes outside Alembic, migration history can become inconsistent.

Deleting migration files

Migration history should remain intact. Deleting files can break upgrades for other developers.


When Should You Use Alembic?

Alembic is an excellent choice if you are:

  • Building APIs with FastAPI

  • Developing Flask applications

  • Using SQLAlchemy ORM

  • Working in a team

  • Deploying applications to production

  • Maintaining databases over time

Even small personal projects benefit from using migrations early.


Conclusion

Alembic is an essential tool for Python developers who use SQLAlchemy. It removes the hassle of manually updating database schemas, keeps development and production databases synchronized, and provides a reliable history of every schema change.

By learning the basics—initializing Alembic, generating migrations, applying upgrades, and rolling back changes—you'll be well-equipped to manage database evolution confidently. As your applications grow, Alembic will help you maintain a clean, consistent, and production-ready database workflow.

If you're starting a new SQLAlchemy project, it's worth setting up Alembic from day one. Your future self—and your teammates—will thank you.