N+1 Query
Database calls inside loops
warningPerformance
no-n-plus-oneWhy this matters
A database query inside a loop makes N+1 round trips to the database. For 100 items, that's 101 queries instead of 1. Response times grow linearly with data size.
✗ Bad
const posts = await db.post.findMany();
for (const post of posts) {
// One query per post — N+1!
const author = await db.user.findUnique({
where: { id: post.authorId },
});
post.author = author;
}✓ Good
const posts = await db.post.findMany({
include: { author: true },
});
// Single query with JOIN — no N+1How to fix
Use eager loading (include/join), batch queries (WHERE id IN), or DataLoader to fetch related data in a single query instead of per-item.