What is the N+1 query problem, and how do you detect and fix it?
Short answer
N+1 is when 1 query fetches N records, then reading each record's relation fires N more queries: 100 orders become 101 SQL statements. Fix it by fetching everything in one go.
3 points to say:
- Detect it with SQL logs or query-count tests.
- Fix it with
JOIN FETCH,@EntityGraphor@BatchSize. - Switching to EAGER does not remove N+1.
Keep reading the deep dive
Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.