Part 18 / Topic 4 of 7
The N+1 problem
The slowest query pattern isn't a query — it's a loop. Application code fetches 50 orders, then runs SELECT * FROM customers WHERE customer_id = ? once per order: 1 + 50 statements, each paying network latency and parse/plan overhead. The database never sees a slow query; the user sees a slow page — which is why N+1 hides from pg_stat_statements' mean column and screams in its calls column (one innocent query, 400,000 calls).
The cures, in order of preference:
- Join — it was one question:
SELECT ... FROM orders o JOIN customers c USING (customer_id) WHERE ...(Part 5 was the cure all along). - Batch — when the ids really do arrive as a list, fetch them in one statement:
SELECT customer_id, first_name
FROM customers
WHERE customer_id = ANY (ARRAY[1, 3, 5]);
customer_id | first_name
-------------+------------
1 | Asha
3 | Meera
5 | Sara
(3 rows)
ANY($1) takes one array parameter of any length — one round trip for the whole list. (ORMs manufacture N+1s silently — their "lazy loading" default is this exact loop; every ORM has an eager-loading switch, and Stage 5B meets it.)
🧪 Quick quiz — answer from memory, then check.
- Where does N+1 show up in pg_stat_statements?
- The two cures?
Show the answers
- A cheap-looking query with an enormous
callscount (and big total_exec_time). - Join it back into the original query, or batch the lookups with
= ANY(array).
Done here? The practice set for Part 18 — 5 exercises with solutions — is on the part page.