Skip to main content
Module 10 · Lesson 4 of 440/57 in the course~15 min
Module lessons (4/4)

The N+1 Problem

Lesson preview5 hands-on exercises readySQL Course · Module 10 — Optimization and Indexes

Replace chatty per-row ORM round-trips with a single batched SQL JOIN or CTE.

What you'll learn in this lesson

  • Recognize the application anti-pattern of queries N + 1 typical of ORM and lazy-loading loops.
  • Replace N network sequential roundtrips with a single JOIN, a GROUP BY, or a IN (...) / json_agg batch fetch.
  • Quantify why network latency (N × RTT) dominates over SQL execution time.

Overview

The number one anti-pattern that cripples Node.js, Python or Go APIs in production is almost never due to missing indexes, but rather to the infamous N + 1 problem. When an ORM loads a list of N parents (1 query) and then within a for loop queries the database for each child (+ N query), even 1 ms micro-queries add up to seconds of stalling.

Notice how JOIN followed by GROUP BY pushes all the matching and counting work into the SQL engine producing the final summary in a single pass:

Sections covered in this lesson

  1. 11. Mental Model: 101 Roundtrips vs 1 Single Query
  2. 22. Progressive & Annotated Examples
  3. 33. Interactive Laboratory: A Single Pipeline Instead of the Loop
  4. 44. Diagnostic Verification (Quiz)
  5. 55. Progressive Practical Laboratory
Pro Lesson · Module 10 — Optimization and Indexes

Unlock "The N+1 Problem" and the full SQL Course curriculum

Replace chatty per-row ORM round-trips with a single batched SQL JOIN or CTE.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in SQL Course plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.