Skip to content

N+1 Query

Medium — good to knowDatabase

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."

Made with passive-aggressive love by manoga.digital. Powered by Claude.