Lab: Hunting an N+1 in the SQL Log
Turn on the SQL log, watch one listing turn into twenty-five queries, remove the N+1 with selectinload, compare it with joinedload, and lock the query count in with a test.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: the environment and the database
- Step 2: seed enough rows to matter
- Step 3: meet the N+1
- Step 4: count queries, then fix them with selectinload
- Step 5: joinedload, and the error it raises first
- Step 6: lock the count in with a test
- Check your understanding
- Apply it: stretch tasks
- Review prompt
Lessons of Data Access with SQLAlchemy
- ORM, Query Builder or Raw SQL: Choosing the Level Concept · 15 min
- Typed Models and Relationships Worked example · 25 min
- Queries in 2.0 Style, and When to Write SQL Yourself Worked example · 25 min
- Lab: Hunting an N+1 in the SQL Log Lab · 25 min
- Sessions, Pools and Async Engines in a Web App Concept · 25 min
- Check: Read the ORM Code, Predict the SQL Knowledge check · 8 questions
What you will learn
- Detect an N+1 query pattern from the SQL log and remove it with an explicit loading strategy.
Prerequisites: SQL Fundamentals
01. Goal and setup
By the end of this lab you will have seen an N+1 query pattern with your own eyes, in the SQL log, and removed it twice: once with selectinload and once with joinedload. You will count queries programmatically with an event listener instead of squinting at logs, and finish with a pytest test that fails if anyone ever reintroduces the pattern.
An N+1 is what happens when code that looks like one loop becomes one query for the list plus one more query per item: 25 queries for 24 authors. Each query is fast, so nothing looks wrong in development — until the page with 500 rows runs 501 round trips.
You need: Python 3.12, uv, Docker, and the models.py from the typed models lesson. Versions in this run: Python 3.12.13, SQLAlchemy 2.1.9, psycopg 3.3.9, pytest 9.2.0 and PostgreSQL 17.12 (postgres:17-alpine, a supported major; 19 is the newest major, and this lab was not tested on it). The install command pins them, so your output matches the one printed here.
The project folder ends up like this:
sqla-lab/
├── .venv/ created by uv (never committed)
├── models.py Authors and Books, from the models lesson
├── seed.py step 2: 24 authors, 3 books each
├── listing.py step 3: the naive listing, echo on
├── counter.py steps 4–5: counted strategies
└── test_constant_queries.py step 6: the guard test02. Step 1: the environment and the database
mkdir sqla-lab && cd sqla-lab
uv venv --python 3.12 .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
uv pip install "sqlalchemy[asyncio]==2.1.9" "psycopg[binary]==3.3.9" \
asyncpg==0.32.0 pytest==9.2.0
python -c "import sqlalchemy as sa, psycopg; print(sa.__version__, psycopg.__version__)"Installed 11 packages in 1.35s
+ asyncpg==0.32.0
+ greenlet==3.5.6
+ psycopg==3.3.9
+ pytest==9.2.0
+ sqlalchemy==2.1.92.1.9 3.3.9sqlalchemy[asyncio] pulls in greenlet, which the async engine from the next lesson needs; psycopg[binary] is the PostgreSQL driver used throughout this lab. Now the database. This is a throwaway container like the one from the psql lesson, on the same port — if your sql-lab container is still running, stop it with docker stop sql-lab (you can start it again later) or reuse it and create a lab database inside it with docker exec sql-lab createdb -U postgres lab.
docker run --name sqla-lab \
-e POSTGRES_PASSWORD=lab \
-e POSTGRES_DB=lab \
-p 55433:5432 \
-d postgres:17-alpine
sleep 3 && docker exec sqla-lab pg_isready -U postgres -d lab7441b028ca22c0b69d6d0d197aac2a2715bdf7de48b699b7cea7b437cb3e8c7a2
/var/run/postgresql:5432 - accepting connectionsThe long hex line is the container id docker run prints; yours will differ. Copy models.py from the typed models lesson into the folder — the lab builds directly on it.
03. Step 2: seed enough rows to matter
"""Create the tables and seed 24 authors with 3 books each."""
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from models import Author, Base, Book
engine = create_engine(
"postgresql+psycopg://postgres:lab@localhost:55433/lab"
)
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)
with Session(engine) as session:
for n in range(1, 25):
session.add(
Author(
name=f"Author {n:02d}",
books=[
Book(title=f"Book {n:02d}-a", pages=100 + n),
Book(title=f"Book {n:02d}-b", pages=200 + n),
Book(title=f"Book {n:02d}-c", pages=300 + n),
],
)
)
session.commit()
print("seeded 24 authors and 72 books")seeded 24 authors and 72 books04. Step 3: meet the N+1
Here is the innocent-looking listing. One query for the authors, then a plain loop that touches each author's books:
"""List every author with their number of books, the naive way."""
from sqlalchemy import create_engine, select
from sqlalchemy.orm import Session
from models import Author
engine = create_engine(
"postgresql+psycopg://postgres:lab@localhost:55433/lab", echo=True
)
with Session(engine) as session:
authors = session.scalars(select(Author).order_by(Author.name)).all()
for author in authors:
print(f"{author.name}: {len(author.books)} books")python listing.py > listing.log 2>&1
grep "^Author" listing.log | tail -1
grep -c "SELECT authors.id" listing.log
grep -c "SELECT books.id, books.author_id" listing.logAuthor 24: 3 books
1
24SELECT authors.id, authors.name
FROM authors ORDER BY authors.name
[generated in 0.00031s] {}
SELECT books.id, books.author_id, books.title, books.subtitle,
books.pages, books.created_at
FROM books
WHERE %(param_1)s::INTEGER = books.author_id
[generated in 0.00041s] {'param_1': 1}That is the pattern in full. The first SELECT loads 24 authors. Then the first time the loop reads author.books, the relationship is lazy: the collection is not there yet, so the session quietly runs a query for it. Twenty-four iterations later, twenty-four identical queries have run, differing only in param_1. The log is the evidence — one query shaped like a list, then N queries shaped like an item. Nothing errored, and the whole run finished in well under a second: an N+1 is quiet until production.
05. Step 4: count queries, then fix them with selectinload
Grepping logs does not scale to a test suite. SQLAlchemy emits an event before every statement a cursor executes, so a small listener can count them while the code runs normally.
"""Count the queries each loading strategy needs for the same listing."""
from sqlalchemy import create_engine, event, select
from sqlalchemy.orm import Load, Session, joinedload, selectinload
from models import Author
engine = create_engine(
"postgresql+psycopg://postgres:lab@localhost:55433/lab"
)
count = {"n": 0}
@event.listens_for(engine, "before_cursor_execute")
def count_queries(conn, cursor, statement, parameters, context, executemany):
count["n"] += 1
def titles_per_author(strategy: Load | None = None) -> dict[str, int]:
count["n"] = 0
with Session(engine) as session:
stmt = select(Author).order_by(Author.name)
if strategy is not None:
stmt = stmt.options(strategy)
# .unique() is required whenever rows can repeat (joinedload)
return {a.name: len(a.books) for a in session.scalars(stmt).unique()}
lazy = titles_per_author()
print(f"lazy loading: {count['n']} queries for {len(lazy)} authors")
selectin = titles_per_author(selectinload(Author.books))
print(f"selectinload: {count['n']} queries for {len(selectin)} authors")
joined = titles_per_author(joinedload(Author.books))
print(f"joinedload: {count['n']} query for {len(joined)} authors")lazy loading: 25 queries for 24 authors
selectinload: 2 queries for 24 authors
joinedload: 1 query for 24 authorsThe lazy count confirms the log: 1 + 24 = 25. selectinload(Author.books) is an explicit loading strategy: attached to the statement with .options(), it loads the books of up to 500 authors in one extra query, immediately after the authors. A page of 24 authors or of 500 takes two queries; beyond 500, SQLAlchemy splits the IN list into batches of 500 keys (set by selectinload(Author.books, chunksize=...) in 2.1), so 24,000 authors take 1 + 48 queries — one per 500 authors, never one per author. That bounded count is what "constant number of queries" means for a page, and it is the property the practice for this skill asks you to assert.
SELECT books.author_id, books.id, books.title, books.subtitle,
books.pages, books.created_at
FROM books
WHERE books.author_id IN (%(primary_keys_1)s::INTEGER,
%(primary_keys_2)s::INTEGER, ... 24 parameters in all)06. Step 5: joinedload, and the error it raises first
joinedload goes further: one query total, the books fetched by a LEFT OUTER JOIN alongside their authors. Try it in a fresh script, iterating session.scalars(stmt) exactly as before:
"""Joined loading in one query — first attempt, without .unique()."""
from sqlalchemy import create_engine, select
from sqlalchemy.orm import Session, joinedload
from models import Author
engine = create_engine(
"postgresql+psycopg://postgres:lab@localhost:55433/lab"
)
with Session(engine) as session:
stmt = (
select(Author)
.options(joinedload(Author.books))
.order_by(Author.name)
)
counts = {a.name: len(a.books) for a in session.scalars(stmt)}
print(counts["Author 01"])sqlalchemy.exc.InvalidRequestError: The unique() method must be
invoked on this Result, as it contains results that include joined
eager loads against collectionsThe error is the fan-out made visible. A joined result has one row per book, so an author with three books appears in three rows; SQLAlchemy refuses to guess which repeats are the same object, and asks you to say so. Add .unique() to the result — session.scalars(stmt).unique() — and run again:
3SELECT authors.id, authors.name, books_1.id AS id_1,
books_1.author_id, books_1.title, books_1.subtitle,
books_1.pages, books_1.created_at
FROM authors LEFT OUTER JOIN books AS books_1
ON authors.id = books_1.author_id
ORDER BY authors.nameOne query, three rows per author, de-duplicated in Python. Which strategy should you pick? For collections like Author.books, selectinload is usually the safer default: the row count stays flat and .unique() is not needed. joinedload shines for many-to-one links — each book's author costs no extra query and adds no duplicate rows. When a parent has hundreds of children, the joined form ships the parent's columns hundreds of times over the wire, which is exactly what selectinload avoids. Both beat lazy loading the moment you loop.
07. Step 6: lock the count in with a test
A fix that is not pinned regresses. The test below seeds its own database, counts statements with the same listener, and asserts the listing takes exactly two queries — the property you want, not the SQL text.
"""Listing authors with their books must take a constant number of queries."""
import pytest
from sqlalchemy import create_engine, event, select
from sqlalchemy.orm import Session, selectinload
from models import Author, Base, Book
URL = "postgresql+psycopg://postgres:lab@localhost:55433/lab"
@pytest.fixture()
def engine():
engine = create_engine(URL)
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)
with Session(engine) as session:
for n in range(1, 25):
session.add(
Author(
name=f"Author {n:02d}",
books=[
Book(title=f"Book {n:02d}-{s}", pages=p)
for s, p in zip("abc", (100, 200, 300))
],
)
)
session.commit()
queries = {"n": 0}
@event.listens_for(engine, "before_cursor_execute")
def count(conn, cursor, statement, parameters, context, executemany):
queries["n"] += 1
engine.counts = queries # small reachability hack for the test body
yield engine
engine.dispose()
def test_listing_stays_at_two_queries(engine):
with Session(engine) as session:
stmt = (
select(Author)
.options(selectinload(Author.books))
.order_by(Author.name)
)
rows = {a.name: len(a.books) for a in session.scalars(stmt).unique()}
assert len(rows) == 24
assert all(n == 3 for n in rows.values())
assert engine.counts["n"] == 2, engine.counts["n"]. [100%]
1 passed in 0.61sNow prove that the guard bites. Delete the .options(selectinload(Author.books)) line from the test, run it again and keep only the assertion lines of the report:
python -m pytest -q test_constant_queries.py | grep "^E "E AssertionError: 25
E assert 25 == 2The count jumped to 25 and the assertion failed with the number in the message. Put the line back before you go on. That is the whole guard — any change that reintroduces per-author queries, anywhere in the listing path, now fails a build instead of slowing a page.
08. Check your understanding
09. Apply it: stretch tasks
Take the lab into the service from this skill's practice:
- Replace the loop in the listing endpoint with
selectinload, and move the query-count test next to the endpoint's tests so it guards the real code path. - Add
.options(raiseload(Author.books))to a route that should never touch books, and check that an accidentalauthor.booksnow raises instead of quietly querying. The SQLAlchemy relationship loading guide lists every loader strategy. - Repeat the whole lab against the async engine from the next lesson: the counts stay the same, and the lazy strategy fails with
MissingGreenletinstead of an N+1 — a nicer failure, because it is loud.
10. Review prompt
Without looking back: describe the shape of an N+1 in a SQL log — what does the first query look like, and the N that follow? What does selectinload change about the second query, and why does the total stop growing with every row? Why does joinedload against a collection require .unique() on the result, and when would you still choose it? Finally, write from memory the assertion you would put in a test to keep an endpoint at a constant query count.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.