Stage 2 · Lesson 11 of 11
The N+1 query problem
is not an , but a loop is enough to cause the N+1 problem. Load 50 orders, then await find_customer(&pool, order.customer_id) inside a for loop, and you have made 51 to the database where one would do. Each await looks harmless, and the handler still passes tests with three rows.
The fixes are plain SQL. the tables in one query. Or collect the ids into a Vec, fetch them all together with WHERE id = ANY($1), and match them up with a HashMap.
SQLx logs every statement it runs through the tracing , so turn that on in development and count the queries per request.
Common traphiding the query inside a small helper function, so the loop in the handler looks innocent.
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
Keep handy
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