N+1 Query
ELI5 — The Vibe Check
N+1 is when your code runs 1 query to get a list of things, then runs 1 more query for EACH thing on the list. Get 100 posts, then query comments 100 times — that is 101 queries instead of 2. Your app slows to a crawl. Super common ORm mistake.
Real Talk
The N+1 query problem occurs when code fetches a list of N records (1 query) then executes an additional query for each record to fetch related data (N queries), totaling N+1 queries. It is a common performance problem with ORMs. Solutions include eager loading (JOIN or IN clause) to fetch all related data in fewer queries.
Show Me The Code
// BAD: N+1 (100 users = 101 queries)
const users = await db.users.findMany();
for (const user of users) {
const orders = await db.orders.findMany({ where: { userId: user.id } });
}
// GOOD: 2 queries
const users = await db.users.findMany({
include: { orders: true } // Eager load
});
When You'll Hear This
"The ORM was generating an N+1 query and making 500 database calls per page load." / "Fix N+1 by using include/eager loading."
Related Terms
Eager Loading
Eager loading fetches all the related data you need upfront in one or two queries.
Explain Plan
EXPLAIN shows you exactly how the database plans to execute your query — which indexes it uses, how many rows it scans, where it is slow.
Lazy Loading
Lazy loading waits until you actually access related data before fetching it. Access post.author and only then does it query the database.
Query Optimization
Query optimization is the art of making slow database queries fast. Add an index here, rewrite that subquery as a JOIN, fetch only the columns you need.