Learn SQL
-- performance.n_plus_one

The N+1 Query Problem in SQL

The quiet performance killer hiding in ORMs and loops

--concept

N+1 is the pattern where listing 100 employees fires 1 query for the list, then 100 more — one per employee — to fetch each one’s department. Each query is fast; the sum is 101 round-trips and a page that feels broken. The fix is to fetch in one round-trip: a JOIN in SQL, or an eager-load/batch API in an ORM.

--how it works
1

The shape of the problem

1 query for the list + N queries for each item’s detail = N+1. Every individual query is fast; the pattern is quadratic-ish in round-trips.

2

Detect it

Symptom: a list page that slows as rows grow. Proof: query logging showing the same statement repeated with different ids.

3

Fix in SQL — one JOIN

Replace per-row lookups with a single JOIN that fetches list + details together in one round-trip.

4

Fix in ORMs — eager loading

JOIN FETCH (JPA), select_related (Django), includes (Sequelize), eager_load (Rails) — or one WHERE id IN (…) batch. Never query inside a loop.

5

Re-measure

101 queries becomes 1. The win was never the query cost — it was the 100 network round-trips and their latency.

--visualization
queries fired: 0
📱 App / ORMlazy loop🗄 Database0 plans0 round-trips and counting…query log1 · SELECT id, name, department FROM employees
one query per row (N+1) one JOIN, all rows
Stage 1 / 9
A page lists employees… and lazily fetches each department one by one. Count the queries.
--example
query.sql
1-- N+1: 1 + N queries
2SELECT id, name, department FROM employees;
3SELECT location FROM departments WHERE dept_id = 'Engineering';
4SELECT location FROM departments WHERE dept_id = 'Sales';
5-- … one per employee
6
7-- Fixed: 1 query
8SELECT e.name, d.location
9FROM employees e
10JOIN departments d ON e.department = d.dept_id;
Result
namelocation
AliceBerlin
BobMadrid
CynthiaBerlin
DavidLisbon
ElenaMadrid
FaridBerlin

The loop version sends one extra query per employee — six employees, seven round-trips, and 10,000 employees would mean 10,001. The JOIN collects every pair in a single round-trip; the database does the lookup work where the data lives, in bulk, with one plan.

--variants

N+1 — the loop version

Innocent code, hidden storm.

query.sql
1SELECT id, name, department FROM employees;
2-- then, per employee row:
3SELECT location FROM departments WHERE dept_id = 'Engineering';
4SELECT location FROM departments WHERE dept_id = 'Sales';
5-- … 1 + N round-trips
Result
result
7 queries for 6 employees — 1 list + 6 lookups
1Each lookup is a millisecond; the 6 round-trips of latency are the real cost.
2At 10,000 employees this endpoint makes 10,001 queries — latency grows with data size, forever.
3ORMs hide this beautifully: e.department in a template can be a lazy-load query per row.

The JOIN fix — one round-trip

Ship the work to where the data lives.

query.sql
1SELECT e.name, d.location
2FROM employees e
3JOIN departments d ON e.department = d.dept_id;
Result
namelocation
AliceBerlin
BobMadrid
CynthiaBerlin
DavidLisbon
ElenaMadrid
FaridBerlin
1One query, one plan, six pairs — the database does the matching in bulk next to the data.
2Round-trips: 1, regardless of employee count. Latency is constant, not linear.
3This is the single highest-leverage performance fix in most applications.

The IN-batch fix — when JOINs don’t fit

Collect ids, fetch details in one statement.

query.sql
1-- after the list query returns 6 department ids:
2SELECT dept_id, location
3FROM departments
4WHERE dept_id IN ('Engineering', 'Sales', 'Marketing');
5-- 2 queries total, then stitch in application code
Result
dept_idlocation
EngineeringBerlin
SalesMadrid
MarketingLisbon
1Micro-batching (the data-loader pattern) collapses per-id fetches into one IN query per request frame.
2Results are cached per id inside the request, so duplicates cost nothing.
3Use when the detail fetch needs different logic/tables than a JOIN can express cleanly.

What it looks like in an ORM

Lazy loading is the usual culprit.

query.sql
1# Django — bad:
2for e in Employee.objects.all():
3 print(e.department.location) # query per employee!
4
5# Django — fixed:
6for e in Employee.objects.select_related('department'):
7 print(e.department.location) # 1 query total
Result
result
select_related → SQL JOIN under the hood — N+1 collapsed to 1
1The bad loop prints the same 6 locations — but issues 7 queries doing it.
2select_related tells the ORM to JOIN the department in the original query.
3Most teams find N+1s by enabling query logging in development and watching list pages load.
--key facts
ORM magnifierlazy loading turns innocent-looking property access into hidden queries — N+1 is ORM folklore for a reason
Not just readsrow-by-row INSERT/UPDATE loops are the write-side twin — batch them
Data-loader patternrequest-scoped batching caches dedupe per-id fetches into one IN query per frame
--use cases
List endpoints: blog index with author names, orders with customer names
GraphQL resolvers (the classic N+1 field) — solved with DataLoader batching
Reporting loops in background jobs — batch or join before “it’s just a nightly job” fails
Write-side twin: per-row INSERT/UPDATE loops → multi-row statements
--under the hood
Round-trip latency multiplies the pattern: on-prem 0.3 ms × 1000 is tolerable, cloud 5 ms × 1000 is five seconds.
Postgres can piggyback batching with ANY(array) for types IN() handles poorly; JSON aggregations (json_agg) fetch one-to-many lists in a single round-trip.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Take the queries you just visualized and see the data structures that power real databases.