N+1 problem
- SQL course
- Advanced
- Lesson 70/81
- 4 min
Learn the N+1 query trap.
N+1 problem
The N+1 problem is one query returning N rows, then a separate query per row. It is slow.
-- YANLIŞ: her sipariş için ayrı müşteri sorgusu
-- DOĞRU: JOIN ile tek sorgu
SELECT o.id, c.name FROM orders o JOIN customers c ON o.customer_id = c.id;JOIN solves N+1.
o.id, c.name is selected from orders o. customers c is joined on o.customer_id = c.id, keeping only matching rows.
N+1 problem — details
The N+1 problem is common in ORMs. It is solved with JOIN or eager loading.
For example, listing 100 orders and fetching each customer with a separate query means 101 queries; a single JOIN returns the same data in one query.
Practice N+1 problem
Solve the N+1 problem with JOIN: combine orders and customers in one query.
Starter code
-- solve N+1
SELECT o.id, c.name FROM orders oSample solution
SELECT o.id, c.name FROM orders o JOIN customers c ON o.customer_id = c.id;Expected output
id name 1 Ayşe 2 Mehmet
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Add JOIN
SELECT o.id, c.name FROM orders o ____ customers c ON o.customer_id = c.id
SELECT o.id, c.name FROM orders o JOIN customers c ON o.customer_id = c.id
Explanation: JOIN combines orders and customers on customer_id; an indexed column speeds up the plan.
2 N+1 problem: match the terms
| Term | Meaning |
|---|---|
N+1 |
many queries |
JOIN |
single query |
slow |
problem |
ORM |
common |
3 What solves the N+1 problem?
- JOIN Correct answer
- DISTINCT
- INDEX
- VIEW
Explanation: JOIN solves N+1.