Interview question
What is the N+1 query problem and how do you fix it? N+1 query problem क्या है और इसे कैसे fix करें?
Answer
The N+1 problem occurs when fetching a list of records triggers one additional query per record to load related data, instead of one combined query.
Problem:
Total: 1 + N queries
Fix with eager loading:
$posts = Post::all(); // 1 query
foreach ($posts as $post) {
echo $post->author->name; // 1 query PER post = N queries
}Total: 1 + N queries
Fix with eager loading:
$posts = Post::with('author')->get(); // 2 queries total| Posts count | Without eager loading | With eager loading |
|---|---|---|
| 100 | 101 queries | 2 queries |
N+1 problem तब होता है जब records की list fetch करने पर related data load करने के लिए हर record पर एक extra query चलती है।
Problem:
Eager loading से fix:
$posts = Post::all();
foreach ($posts as $post) {
echo $post->author->name; // हर post पर 1 query
}Eager loading से fix:
$posts = Post::with('author')->get();Was this answer clear?