Backend development

Stage 2 · Lesson 10 of 10

The N+1 query problem

Relational databases and SQL

load related objects lazily by default, meaning only when you first touch them. That causes the N+1 problem. You fetch 50 orders, then read order.customer.name in a loop or a template, and 50 more queries run, one per order.

In Django, select_related follows using a join. prefetch_related fetches many-to-many or reverse relations in one extra query. In , use joinedload or selectinload on the query.

Count your queries in development with Django Debug Toolbar, assertNumQueries in tests, or SQLAlchemy's echo=True. With async SQLAlchemy, raises an error instead of running quietly, which forces you to decide up front.

Common trapa template or touching a relation you never loaded.

A question to check yourself, an AI practice session and 1 cheat sheet entry come with the full roadmap. Unlock

Resources for this stage

Start with· follow one of these

Practise

Also worth your time

Mark this stage as not done?