Python applications often store their data in relational databases. When you write the SQL yourself, you also have to turn rows into objects, link related records, and protect queries against SQL injection. Each schema change then means finding and updating the affected queries by hand.
An Object Relational Mapper (ORM) takes much of this work off your hands by mapping Python classes to database tables. A class describes a table, an object stands for a row, and an attribute holds a column value. SQLAlchemy, a widely used Python database library, includes an ORM that writes the SQL for you and still lets you inspect it.
In this tutorial, you'll build a small library database with 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.
Table of Contents
- Prerequisites
- How to Install SQLAlchemy
- How to Define Your Models
- How to Connect to the Database
- How to Add Records
- How to Query Data
- How to Load Related Data Efficiently
- How to Update and Delete Records
- How to Handle Transactions
Prerequisites
To follow along, you'll need:
- Python 3.11 or later
- Familiarity with Python classes and type hints
- Basic SQL knowledge: tables, primary keys, foreign keys, and joins
- SQLAlchemy 2.1 or later in a virtual environment (the installation steps are covered next)
SQLAlchemy is the library your code will use, and SQLite is the database it will talk to. SQLite works through Python's built-in sqlite3 module, so you don't have to set up a database server.
How to Install SQLAlchemy
Create and activate a virtual environment:
python -m venv .venv
source .venv/bin/activate
On Windows, activate it with .venv\Scripts\activate. Then install SQLAlchemy:
pip install "sqlalchemy>=2.1"
The code in this tutorial was tested with SQLAlchemy 2.1.9. Create a file named main.py, and add each Python snippet to the bottom of it as you go.
How to Define Your Models
Every model inherits from a shared base class. Start by creating one:
from sqlalchemy import ForeignKey, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
class Base(DeclarativeBase):
pass
Base keeps a record of every table you declare through its subclasses.
How to Create the Author Model
Add an Author class:
class Author(Base):
__tablename__ = "authors"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(100))
email: Mapped[str] = mapped_column(unique=True)
books: Mapped[list["Book"]] = relationship(
back_populates="author", cascade="all, delete-orphan"
)
Let's parse the definition:
__tablename__sets the name of the table.Mapped[...]declares the Python type of each attribute.mapped_column()adds database details such as the primary key, length, or a unique constraint.relationship()links an author to a list of books. Thecascadeoption saves, and deletes, those books along with their author.
How to Create the Book Model
Each book belongs to one author:
class Book(Base):
__tablename__ = "books"
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str] = mapped_column(String(200))
year: Mapped[int]
rating: Mapped[float | None]
author_id: Mapped[int] = mapped_column(ForeignKey("authors.id"))
author: Mapped["Author"] = relationship(back_populates="books")
ForeignKey("authors.id") connects the two tables. The back_populates arguments keep both sides of the relationship in sync in Python.
The type hints also control nullability. year is a required column, while float | None allows rating to be empty.
How to Connect to the Database
An engine manages connections to your database. Create one, then create the tables:
from sqlalchemy import create_engine
engine = create_engine("sqlite://")
Base.metadata.create_all(engine)
print(list(Base.metadata.tables))
Output:
['authors', 'books']
The URL sqlite:// creates an in-memory database, so every run starts fresh. To keep your data on disk, use sqlite:///library.db.
create_all() creates only the tables that don't exist yet. It leaves existing tables unchanged, so use a migration tool such as Alembic when your schema changes.
How to Add Records
You talk to the database through a session. Think of it as a shopping cart: you put objects in, and commit() is the checkout.
from sqlalchemy.orm import Session
ursula = Author(
name="Ursula K. Le Guin",
email="ursula@example.com",
books=[
Book(title="A Wizard of Earthsea", year=1968, rating=4.6),
Book(title="The Dispossessed", year=1974, rating=4.8),
],
)
At this point, ursula is a regular Python object that exists only in memory. Create a second author:
octavia = Author(
name="Octavia E. Butler",
email="octavia@example.com",
books=[Book(title="Kindred", year=1979)],
)
Now save both:
with Session(engine) as session:
session.add_all([ursula, octavia])
session.commit()
print(ursula.id, octavia.id)
Output:
1 2
You added only the authors, and SQLAlchemy saved their books too. It also filled in each author_id for you.
The with block closes the session when you're done, even if an error occurs.
How to Query Data
To read data, build a statement with select() and run it through a session.
How to Filter and Sort Results
Fetch the books published after 1970, oldest first:
from sqlalchemy import select
stmt = select(Book).where(Book.year > 1970).order_by(Book.year)
with Session(engine) as session:
for book in session.scalars(stmt):
print(book.title, book.year)
Output:
The Dispossessed 1974
Kindred 1979
scalars() returns Book objects you can work with directly. If you're curious about the SQL, print the statement:
print(stmt)
Output:
SELECT books.id, books.title, books.year, books.rating, books.author_id
FROM books
WHERE books.year > :year_1 ORDER BY books.year
The :year_1 placeholder shows that the value travels separately from the SQL text. This protects your query against SQL injection.
How to Fetch a Single Record
Use get() for a primary key lookup. For any other condition that matches at most one row, use scalar_one_or_none():
with Session(engine) as session:
first_book = session.get(Book, 1)
print(first_book.title)
stmt = select(Author).where(Author.email == "nobody@example.com")
print(session.execute(stmt).scalar_one_or_none())
Output:
A Wizard of Earthsea
None
How to Join and Aggregate Tables
Suppose you want to count the books by each author. Join the tables and group the rows:
from sqlalchemy import func
stmt = (
select(Author.name, func.count(Book.id))
.join(Author.books)
.group_by(Author.id)
.order_by(Author.name)
)
join(Author.books) uses the relationship to work out the join condition. Since you're selecting individual columns, call execute() to get rows back:
with Session(engine) as session:
for name, total in session.execute(stmt):
print(f"{name}: {total}")
Output:
Octavia E. Butler: 1
Ursula K. Le Guin: 2
How to Load Related Data Efficiently
By default, SQLAlchemy loads a relationship when you first access it. This is called lazy loading.
To see its cost, add a query counter:
from sqlalchemy import event
queries = []
@event.listens_for(engine, "before_cursor_execute")
def track_query(conn, cursor, statement, *args):
queries.append(statement)
The problem: loop over the authors and access their books.
with Session(engine) as session:
for author in session.scalars(select(Author)):
print(author.name, len(author.books))
print("Queries:", len(queries))
Output:
Ursula K. Le Guin 2
Octavia E. Butler 1
Queries: 3
One query fetched the authors, and each author triggered another. With 500 authors, you'd send 501 queries. This is the N+1 query problem.
The solution: ask for the books up front with selectinload().
from sqlalchemy.orm import selectinload
queries.clear()
stmt = select(Author).options(selectinload(Author.books))
with Session(engine) as session:
for author in session.scalars(stmt):
print(author.name, len(author.books))
print("Queries:", len(queries))
Output:
Ursula K. Le Guin 2
Octavia E. Butler 1
Queries: 2
The second query loads the books for all the authors in one batch. I generally go for selectinload() first for collections. For many-to-one links such as Book.author, joinedload() is a good fit.
How to Update and Delete Records
To update a row, load the object and change its attribute:
with Session(engine) as session:
stmt = select(Book).where(Book.title == "Kindred")
kindred = session.scalars(stmt).one()
kindred.rating = 4.7
session.commit()
print(kindred.title, kindred.rating)
Output:
Kindred 4.7
The session tracks the change and sends an UPDATE statement when you commit.
To delete a row, pass the object to delete():
with Session(engine) as session:
author = session.get(Author, 2)
session.delete(author)
session.commit()
remaining = session.scalar(select(func.count(Book.id)))
print("Books left:", remaining)
Output:
Books left: 2
Deleting Octavia also deleted Kindred, thanks to the cascade rule on Author.books.
No worries if you can't recall what cascade does. The cascade="all, delete-orphan" setting on Author.books tells SQLAlchemy that when you delete an author, it should delete that author's books too.
Before the deletion, the database has three books: Ursula wrote A Wizard of Earthsea and The Dispossessed, and Octavia wrote Kindred. The code deletes one author, Octavia, whose ID is 2, so SQLAlchemy also removes her only book, Kindred. Three books minus one leaves two, both by Ursula, which is why the output shows Books left: 2.
How to Handle Transactions
A transaction groups changes so that they all succeed or all fail.
The problem: add a new author along with an email address that's already taken.
duplicate = Author(name="Another Ursula", email="ursula@example.com")
with Session(engine) as session:
session.add(duplicate)
session.commit()
Output:
The solution: replace that last with block with the code below, which opens the transaction using session.begin() and catches the error.
from sqlalchemy.exc import IntegrityError
try:
with Session(engine) as session, session.begin():
session.add(Author(name="N. K. Jemisin", email="nora@example.com"))
session.add(Author(name="Another Ursula", email="ursula@example.com"))
except IntegrityError:
print("That email already exists. Nothing was saved.")
Output:
That email already exists. Nothing was saved.
session.begin() commits when the block succeeds and rolls back when it raises an exception. The first author in the block was valid, but the rollback discarded that insert too:
with Session(engine) as session:
print(session.scalars(select(Author.name)).all())
Which is why you can't find N.K. Jemisin in the output:
['Ursula K. Le Guin']
If you call commit() yourself and want to keep using the same session after a failure, call session.rollback() first.
Conclusion
In this tutorial, you defined two related models, saved and queried records, fixed an N+1 problem, and rolled back a failed transaction.
The table below maps each task to the tool you used for it:
| Task | What to use |
|---|---|
| Define a table | A subclass of Base with mapped_column() |
| Link two tables | ForeignKey and relationship() |
| Add records | session.add() or session.add_all() |
| Fetch by primary key | session.get() |
| Fetch many objects | session.scalars(select(...)) |
| Fetch columns | session.execute(select(...)) |
| Load collections up front | selectinload() |
| Delete a record | session.delete() |
| Commit or roll back automatically | session.begin() |
The ORM is a good choice when your application creates, reads, and updates related objects. For large bulk operations or complex reports, SQLAlchemy Core or handwritten SQL gives you tighter control.
As a next step, switch the engine to a database file and add Alembic to manage schema changes. The official SQLAlchemy ORM documentation covers relationships and loading strategies in more depth. Keep learning!