How to Use SQLAlchemy ORM to Work with Databases in Python
Python applications often store data in relational databases. When you write SQL manually, you also have to convert rows into objects, link related records, and protect queries against SQL injection. Every schema change then requires finding and updating the affected queries by hand.
An Object Relational Mapper (ORM) eliminates much of this work by mapping Python classes to database tables. A class describes a table, an object represents a row, and an attribute holds a column value. SQLAlchemy, a widely used Python database library, includes an ORM that generates the SQL for youβwhile still letting you inspect it.
In this tutorial, you'll build a small library database using SQLAlchemy ORM. You'll define models, add and query records, load related data efficiently, and handle failed transactions. Let's get started!
You can get the Colab notebook for this tutorial and follow along.
Note (2026 context): SQLAlchemy 2.0+ is now the standard, featuring a unified select() API, improved typing support, and async capabilities. The examples below assume SQLAlchemy 2.x style.
Table of Contents
- Prerequisites
- How to Install SQLAlchemy
- How to Define Your Models
- How to Create the Author Model
- How to Create the Book Model
- How to Connect to the Database
- How to Add Records
- How to Query Data
- How to Filter and Sort Results
- How to Fetch a Single Record
- How to Join and Aggregate Tables
Prerequisites
Before starting, ensure you have Python 3.9+ and a basic understanding of SQL and Python classes. Familiarity with SQLAlchemy is helpful but not required.
How to Install SQLAlchemy
Install SQLAlchemy using pip:
pip install sqlalchemy
For this tutorial, we'll use SQLite as the database backend, which requires no additional setup.
How to Define Your Models
Models are Python classes that inherit from declarative_base() (or DeclarativeBase in SQLAlchemy 2.0). Each class attribute represents a column, and relationships define links between tables.
How to Create the Author Model
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import declarative_base, relationship
Base = declarative_base()
class Author(Base):
__tablename__ = 'authors'
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
books = relationship('Book', back_populates='author')
How to Create the Book Model
class Book(Base):
__tablename__ = 'books'
id = Column(Integer, primary_key=True)
title = Column(String, nullable=False)
author_id = Column(Integer, ForeignKey('authors.id'))
author = relationship('Author', back_populates='books')
This sets up a one-to-many relationship between authors and books.
How to Connect to the Database
Create an engine and session to interact with the database:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine('sqlite:///library.db', echo=True)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
The echo=True flag logs generated SQL, useful for debugging.
How to Add Records
Add authors and books, then commit the transaction:
author = Author(name='Jane Austen')
book = Book(title='Pride and Prejudice', author=author)
session.add(author)
session.add(book)
session.commit()
Use session.rollback() to undo changes if an error occurs.
How to Query Data
SQLAlchemy 2.0 uses select() for queries. Here's how to retrieve all books:
from sqlalchemy import select
stmt = select(Book)
books = session.scalars(stmt).all()
for book in books:
print(book.title)
How to Filter and Sort Results
Apply filters with where() and sorting with order_by():
stmt = select(Book).where(Book.title.ilike('%pride%')).order_by(Book.title)
filtered_books = session.scalars(stmt).all()
How to Fetch a Single Record
Use session.get() or scalars().first():
book = session.get(Book, 1) # by primary key
# or
book = session.scalars(select(Book).where(Book.title == 'Pride and Prejudice')).first()
How to Join and Aggregate Tables
Join tables and compute aggregates like counts:
from sqlalchemy import func
stmt = select(Author.name, func.count(Book.id)).join(Book).group_by(Author.name)
results = session.execute(stmt).all()
for name, count in results:
print(f'{name}: {count} books')
For efficient loading of related data, use selectinload() or joinedload() to avoid N+1 queries:
from sqlalchemy.orm import selectinload
stmt = select(Author).options(selectinload(Author.books))
authors = session.scalars(stmt).all()
Handling Transactions and Errors
Wrap database operations in try/except blocks and roll back on failure:
try:
# perform operations
session.commit()
except Exception as e:
session.rollback()
print(f'Error: {e}')
finally:
session.close()
This ensures data integrity.
Conclusion
SQLAlchemy ORM simplifies database interactions in Python by letting you work with objects instead of raw SQL. You've learned how to define models, connect to a database, add and query records, handle relationships, and manage transactions. With SQLAlchemy 2.0's modern API, you can build robust, maintainable applications. Explore advanced features like async support and migrations with Alembic as you grow.
Happy coding!
via FreeCodeCamp
