✅ What is the N+1 Query Problem?
The N+1 problem occurs when your code runs:
-
1 query to load a list of parent records
-
+ N additional queries to load related data for each item individually
So total queries = 1 + N
This is hugely inefficient.
🟦 Simple Example (Best way to understand)
Suppose you want to load a list of Employees and their Projects.
You write:
❌ What actually happens with Lazy Loading:
Query 1:
Now assume Employees table has 10 records.
When we loop through them, EF loads Projects for each employee:
Query 2:
Query 3:
Query 4:
… and so on 10 times.
✔ Total queries = 1 (main query) + 10 (project queries) = 11 queries
This is the N+1 problem.
🟥 Why is this bad?
-
Causes too many database round-trips
-
Slows applications massively
-
Wastes network + DB CPU
-
Very harmful in Web APIs, where response time matters
🟩 How to Fix the N+1 Problem? (Eager Load)
Use .Include():
✔ SQL Generated (Single JOIN Query):
✔ Total queries = 1 query only
No matter how many employees exist.
🟧 Interview Answer (Best Version)
The N+1 problem happens when the application fires one query to fetch the main data and then fires N additional queries to load related data for each item. This usually happens with lazy loading.
For example, loading 100 employees and then loading each employee’s projects separately results in 101 queries.
The solution is using eager loading with
.Include()to fetch all related data in a single query.
🟦 Analogy (Very Easy to Remember)
Imagine you want 10 grocery items.
❌ Lazy Loading Way (N+1)
-
You go to the store (1 trip)
-
Then you go back 10 separate times to buy each item (10 trips)
Total trips = 11
✔ Eager Loading Way
-
You go once and buy all 10 items together
Total trips = 1
No comments:
Post a Comment