← Back to SQL, page 18

sql-0343 · Easy fresher

Code that loads 50 orders and then queries each order's customer separately is slow. What is the problem and the fix?

This is the N+1 query problem: one query for the list plus one query per row, so 51 round trips. Fetch the related data in one go, either with a JOIN or with a second query using WHERE id IN (...) for all needed customers. ORMs offer eager loading options for this.

Full answer

Each round trip costs network latency and parsing even when the query itself is fast. At 2 ms per query, 51 queries take about 100 ms, and the number grows with the page size.

Fixes:

  • One JOIN: SELECT o.*, c.name FROM orders o JOIN customers c ON c.id = o.customer_id WHERE ... LIMIT 50.
  • Two queries: load the orders, collect distinct customer ids, then SELECT * FROM customers WHERE id IN (...) and stitch in code. This avoids repeating wide customer rows.
  • ORM settings: eager loading (for example select_related or includes) turns lazy per-row loads into one of the forms above.

Detect it by counting queries per request in logs or tests. A test that asserts a maximum query count per endpoint stops regressions.

Key points

  • N+1 = one list query plus one per row
  • Latency per round trip dominates
  • Use a JOIN or a batched IN query
  • Count queries per request in tests

Common mistakes

  • Caching each per-row query instead of batching
  • Assuming fast individual queries mean a fast page

Follow-ups

  • When is the two-query approach better than a join?
  • How would you detect N+1 in production?

Tips

  • Quantify the round trips