✏️ Explanatory Question
Level: Very Hard — The #1 silent performance killer in ORM-based apps (Hibernate, Entity Framework, Django, Laravel).
The cause: The N+1 problem occurs when code runs 1 query to fetch a list (the "1"), then loops through the results and runs 1 additional query per row (the "N"). For 100 authors, that's 1 + 100 = 101 queries. The killer isn't query speed — it's the network round-trip overhead repeated 100 times.
| author_id | name |
|---|---|
| 1 | Rumman |
| 2 | Krushna |
| ... | ... (100 authors) |
| book_id | author_id | title |
|---|---|---|
| 1 | 1 | SQL Mastery |
| 2 | 1 | Indexing 101 |
| 3 | 2 | Joins Deep Dive |
-- Query 1: get all authors (the "1")
SELECT author_id, name FROM authors; -- returns 100 rows
-- Then the app loops and fires ONE query PER author (the "N")
SELECT COUNT(*) FROM books WHERE author_id = 1; -- query 2
SELECT COUNT(*) FROM books WHERE author_id = 2; -- query 3
SELECT COUNT(*) FROM books WHERE author_id = 3; -- query 4
-- ... 100 times ...
SELECT COUNT(*) FROM books WHERE author_id = 100; -- query 101
-- TOTAL: 101 queries, ~100 network round-trips
-- FIX: one query does the whole job (the "1", no "N")
SELECT a.author_id, a.name, COUNT(b.book_id) AS book_count
FROM authors a
LEFT JOIN books b ON a.author_id = b.author_id
GROUP BY a.author_id, a.name;
-- 1 query, 1 round-trip, correct counts (0 for authors with no books)
-- ALTERNATIVE: if you need the actual book rows, fetch them in ONE query
SELECT a.name, b.title
FROM authors a
LEFT JOIN books b ON a.author_id = b.author_id
ORDER BY a.author_id;
-- Then group in application code (still just 1 query)
-- ALTERNATIVE (batching): one IN query instead of 100 separate ones
SELECT author_id, COUNT(*) AS book_count
FROM books
WHERE author_id IN (1,2,3, /* ...all 100 ids... */ 100)
GROUP BY author_id;
JOIN FETCH, Entity Framework .Include(), Django select_related()/prefetch_related(), Laravel with(). These tell the ORM to fetch related data in one (or a few) queries instead of lazily per row.
WHERE parent_id IN (...) for children, then stitch in code) is faster than one massive JOIN. Know the trade-off.