CodePark/ questions / ORMs & the N+1 problem
START PRACTICINGPRACTICE
Backend question · Databases & SQL › ORMs & the N+1 problem

How many SQL queries does this Prisma code send?

const users = await prisma.user.findMany({ take: 20 });
for (const u of users) {
  const posts = await prisma.post.findMany({
    where: { authorId: u.id },
  });
  console.log(u.name, posts.length);
}
21

The answer is 21. One query fetches 20 users. Then the loop awaits a separate query for each user. That is 1 + 20 = 21 queries. This is the N+1 pattern.

The code only needs the count of posts. So add
include: { _count: { select: { posts: true } } } to the first query, and it gets the counts in one request.