Stage 2 · Lesson 10 of 10
The N+1 query problem
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
- CoursePaidGrokking Relational Database Design and Modeling
Design Gurus · Intermediate · $98 one-time
The modelling and normalisation decisions that stay with a codebase for years
- CourseFreeCS50's Introduction to Databases with SQL
Harvard University · Beginner
Free course from querying through schema design, indexes, transactions and scaling
Practise
Also worth your time
- Database Indexing Explained: B-Tree, Hash, Bitmap, R-Tree, and When to Use Each (opens in a new tab)Read
B-tree and composite indexes, plus the leftmost-prefix rule that trips people up
What sits under your queries: storage engines, transactions and isolation levels