JuniorJunior (1–3 yrs)CodingSQLAmazonShopify
N+1 Query Problem
What is the N+1 query problem in ORMs, and how do you fix it?
Answers use simple, clear English.
Quick interview answer
Loading a list of N parents then querying children per parent yields 1+N queries. Fix with eager loading/joins, batch IN queries, or DataLoader-style batching. Measure with query logs.
Detailed answer
Loading a list of N parents then querying children per parent yields 1+N queries. Fix with eager loading/joins, batch IN queries, or DataLoader-style batching. Measure with query logs.
Real example & use case
Blog API listing posts with comments drops from 101 queries to 1–2 after join/include.
Pros & cons
Pros of eager load: fewer round-trips. Cons: over-fetching wide joins — select only needed columns.
Code example
-- Bad: 1 + N
SELECT * FROM posts;
-- then per post: SELECT * FROM comments WHERE post_id = ?;
-- Better:
SELECT p.*, c.*
FROM posts p
LEFT JOIN comments c ON c.post_id = p.id
WHERE p.author_id = @author;Practice code · sql (view only · no execution)
-- Bad: 1 + N
SELECT * FROM posts;
-- then per post: SELECT * FROM comments WHERE post_id = ?;
-- Better:
SELECT p.*, c.*
FROM posts p
LEFT JOIN comments c ON c.post_id = p.id
WHERE p.author_id = @author;#orm#performance#sql