Stage 2 · Lesson 11 of 11
The N+1 query problem
You do not need an to have an N+1 problem; a loop is enough. Load 50 orders, then call GetCustomer(ctx, order.CustomerID) inside the loop. You have made 51 to the database where one would do.
At 2 to 5 ms per round trip, that adds up fast. The fixes are plain . the tables in one query.
Or collect the ids and fetch them all together with WHERE id = ANY($1), then match the results up with a map. handles both well. Log queries with their timings in development, or add a pgx tracer, to count queries per request.
Common traphiding the query inside a small helper, so the loop looks harmless.
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