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
emailasciidocLater you decide to add:
created_atebnfWithout 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 alembiccmakeIf you're using SQLAlchemy:
pip install sqlalchemy alembiccmakeVerify installation:
alembic --helpadaInitializing Alembic
Inside your project:
alembic init migrationscsharpYou'll see something like:
project/
│
├── migrations/
│ ├── versions/
│ ├── env.py
│ └── script.py.mako
│
├── alembic.ini
└── app.pystylusAlembic creates everything needed to manage migrations.
Configure the Database URL
Open:
alembic.iniUpdate:
sqlalchemy.url = sqlite:///app.dbiniFor PostgreSQL:
sqlalchemy.url = postgresql://user:password@localhost/mydatabasebash
For MySQL:
sqlalchemy.url = mysql+pymysql://user:password@localhost/mydatabasebash
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))angelscriptAlembic compares your models against the database to generate migrations automatically.
Connecting Alembic to Your Models
Open:
migrations/env.pybash
Locate:
target_metadata = NoneiniReplace it with:
from models import Base
target_metadata = Base.metadataangelscriptNow Alembic knows which models to inspect.
Creating Your First Migration
Generate a migration:
alembic revision --autogenerate -m "Create users table"cssAlembic creates a file like:
migrations/versions/awkExample:
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"),
)scssAlways review generated migrations before applying them.
Applying Migrations
Run:
alembic upgrade headbashThis updates your database to the latest version.
Viewing Migration History
To see migration history:
alembic historybashCurrent version:
alembic currentebnfLatest revision:
alembic headsebnfMaking Schema Changes
Suppose you update your model:
created_at = Column(DateTime)iniGenerate another migration:
alembic revision --autogenerate -m "Add created_at"dsconfigAlembic detects:
op.add_column(
"users",
sa.Column("created_at", sa.DateTime())
)sasThen apply it:
alembic upgrade headbashNo data is lost.
Rolling Back Changes
Need to undo a migration?
Rollback one step:
alembic downgrade -1apacheRollback to a specific revision:
alembic downgrade <revision_id>xmlThis 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:
Update your SQLAlchemy models.
Generate a migration.
Review the generated migration.
Apply the migration.
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_metadataebnf
Alembic won't detect your models if target_metadatatarget_metadataebnf 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.