How to Fix N+1 Query Problems in Prisma with include, select, and DataLoader

How to Fix N+1 Query Problems in Prisma with include, select, and DataLoader

by | Nov 26, 2026 | Uncategorized | 0 comments

In short: a Prisma N+1 query happens when your code fetches a list, then runs one extra query for each item in it. Prisma’s include and select never cause it on their own. The usual culprits are an await inside a loop, a Promise.all over a map, or a GraphQL field resolver that loads one record per parent.

You spot it by turning on query logging and counting the SQL (Structured Query Language) statements per request. You fix it with eager loading, one batched in query, or a DataLoader in GraphQL resolvers.

This guide walks through that path in order: how the problem works, where it hides in Prisma code, how to detect it, the four fixes and when each one fits. It ends with the pitfalls that bring it back, how to measure the gain, and a checklist you can paste into a pull request template. There is more on it in How to Fix N+1 Query Problem in GraphQL.

What the N+1 query problem is, in SQL and in Prisma

The N+1 query problem is a data access pattern, not a bug in the database. Your code runs one query to get a list of records, which is the “1”. Then it runs one more query for each record to fetch related data, which is the “N”. Some developers prefer the name “1+N”, because the single list query comes first.

Here is the mechanism. Every query is a round trip: the app sends SQL over the network, the database parses and executes it, and the rows travel back. Each trip costs a little latency, even when the query itself takes a fraction of a millisecond. So the total time grows with the number of trips, not with the amount of data.

Example: a page lists 50 blog posts with their author’s name. Done the slow way, that’s 1 query for the posts plus 50 queries for the authors, so 51 round trips. Done properly, it’s 1 or 2 queries.

On your laptop, with the database on the same machine, both versions feel instant. In production, with the database across a network, the 51 trips add up, and they also hold a connection from the pool the whole time.

That last point explains why N+1 problems often show up only after a deploy. The code didn’t change, but the distance between the app and the database did. There’s one honest exception: an in-process database such as SQLite has no network hop, and its authors explain that many small queries are efficient in SQLite. Fewer queries for the same data still wins, but the penalty is much smaller there.

database query code

Where Prisma N+1 queries actually come from

Prisma ORM (an object-relational mapper, a library that turns code calls into SQL) has no lazy loading. Touching a property never loads a relation behind your back. You only get related data when you ask for it with include, select or the fluent API. So a Prisma N+1 query is always written explicitly somewhere in your code, which makes it easier to find than in ORMs with lazy loading.

When you do ask for a relation with include, Prisma loads it in one query per relation level, using an IN (...) list of parent IDs. A findMany on users that includes posts and their comments produces three queries at most, whatever the number of users. That’s batching, not N+1.

The real sources are elsewhere:

  • An await inside a for loop that calls findUnique or findMany for each item.
  • Promise.all(items.map(...)) with a query in the callback. It runs the queries in parallel, so it feels faster, but it’s still N queries and it can drain the connection pool.
  • GraphQL field resolvers where Post.author runs its own query for every post in the list.
  • Helpers and serializers that look up a record “just for this row”, such as a permission check or a formatted label.
  • The same model read through several paths, for instance two nested reads that both load the parent table. That’s not strictly N+1, but it’s the same waste on a smaller scale.

How to detect a Prisma N+1 query

The first tool is the query log. Pass the log option when you create the client, and every SQL statement Prisma sends is printed with a prisma:query prefix:

const prisma = new PrismaClient({ log: ['query'] })

Run the slow endpoint once and read the output. An N+1 pattern is easy to recognise: the same SELECT ... WHERE "id" = $1 repeated dozens of times with only the parameter changing. A healthy request shows a short list of different statements, usually with IN ($1,$2,$3...) clauses.

Reading logs by eye doesn’t scale, so the next step is a counter. Emit query events instead of printing them, then count per request:

const prisma = new PrismaClient({
  log: [{ emit: 'event', level: 'query' }],
})

let queryCount = 0
prisma.$on('query', (e) => {
  queryCount++
  // e.query, e.params and e.duration (ms) are also available
})

Reset the counter at the start of a request and log it at the end, next to the response time. In a real app, store it in request context (AsyncLocalStorage in Node.js, for example) rather than in a global, so parallel requests don’t mix their counts.

On the database side, PostgreSQL’s pg_stat_statements extension groups identical statements and counts how many times each one ran. A cheap query with a huge call count is the signature of N+1. MySQL offers the same view in performance_schema, through the statement digest summary tables. APM tools (application performance monitoring, such as tracing dashboards) show the same thing as a “staircase” of identical database spans under one request.

Finally, lock the result in with a test. A regression test that calls an endpoint and asserts “fewer than 5 queries” catches an N+1 the day someone adds a loop, long before users feel it.

database query code

Fix 1: eager loading with include and select

Eager loading means fetching related data in the same call as the parent records. It’s the fix for most loops in REST (Representational State Transfer) endpoints, the classic APIs with one route per resource. Here’s the slow version:

// 1 query for posts, then 1 query per post: N+1
const posts = await prisma.post.findMany({ take: 50, orderBy: { createdAt: 'desc' } })
for (const post of posts) {
  post.author = await prisma.user.findUnique({ where: { id: post.authorId } })
}

And the eager-loaded version, which needs at most two queries whatever the page size:

const posts = await prisma.post.findMany({
  take: 50,
  orderBy: { createdAt: 'desc' },
  select: {
    id: true,
    title: true,
    author: { select: { name: true } },
  },
})

Prefer select over include when the page only needs a few fields. include returns every scalar column of the related model, which is over-fetching: you move data you never display. Note that Prisma doesn’t accept select and include at the same level of one query, so pick one per level and nest the other inside.

If you only need a number, such as “12 comments”, don’t load the comments at all. Use the relation count instead: include: { _count: { select: { comments: true } } }. It returns the count without pulling the rows.

Fix 2: batch with an in query and a Map

Sometimes eager loading doesn’t fit. The IDs come from several places, or the same parent model is needed by two separate lists. In that case, collect the IDs, run one query with an in filter, and join in memory:

const authorIds = [...new Set(posts.map((p) => p.authorId))]
const authors = await prisma.user.findMany({
  where: { id: { in: authorIds } },
  select: { id: true, name: true },
})
const byId = new Map(authors.map((a) => [a.id, a]))
const result = posts.map((p) => ({ ...p, author: byId.get(p.authorId) ?? null }))

This is exactly what Prisma does internally for include, written by hand. It also removes duplicate reads: two lists that both point to the same table load that table once instead of twice. The trade-off is that rebuilding nested objects in Node.js costs some processor time (CPU), so check with your counter and a timer that the change actually helps.

database query code

Fix 3: choose a relation load strategy

Recent versions of Prisma let you choose how include and nested select are executed, through the relationLoadStrategy option. It arrived in Prisma 5.7.0 as the relationJoins preview feature. Database support and status have changed since, so check the documentation for your version before relying on it.

  • join runs a single query and lets the database assemble the result (a lateral join on PostgreSQL). One round trip, which helps when the database is far away.
  • query runs one query per relation level and merges the results in the application. Several round trips, but simpler SQL that can be easier on a busy database.
const users = await prisma.user.findMany({
  relationLoadStrategy: 'join',
  include: { posts: true },
})

Neither strategy creates N+1. They differ in where the work happens, so treat the choice as a tuning knob after the loops are gone. In our view, join is the better default for API endpoints that return a page of nested data, and query is worth testing when a join returns very wide rows. Prisma join performances is a useful companion to this.

Fix 4: GraphQL resolvers with DataLoader

GraphQL is where N+1 thrives. On a GraphQL server, each field has its own resolver, so a query asking for 100 reviews with their authors calls the author resolver 100 times. If that resolver looks up each author by post ID, you get 101 queries, and the client query looks perfectly innocent.

Prisma has a partial answer built in, described in the query optimization section of its documentation. Its client batches findUnique() calls that happen in the same tick of the event loop (the same pass through Node.js’s queue of pending work) into one findMany. The documentation lists the conditions for batching, such as identical include parameters, worth reading when a resolver still isn’t batched. So writing relation resolvers with the fluent API helps:

const resolvers = {
  Post: {
    author: (parent, _args, { prisma }) =>
      prisma.post.findUnique({ where: { id: parent.id } }).author(),
  },
}

For everything else, including findMany per parent, use the dataloader package. A loader collects every key requested during one tick, calls your batch function once, then hands each resolver its own result:

import DataLoader from 'dataloader'

export const createLoaders = (prisma) => ({
  userById: new DataLoader(async (ids) => {
    const users = await prisma.user.findMany({ where: { id: { in: [...ids] } } })
    const map = new Map(users.map((u) => [u.id, u]))
    return ids.map((id) => map.get(id) ?? null)
  }),
})

// resolver
Post: { author: (post, _a, ctx) => ctx.loaders.userById.load(post.authorId) }

Two rules from the DataLoader documentation matter here. The batch function must return an array with the same length and order as the keys, which is why the code maps back through ids. And you should create new loaders for each request, because a loader caches what it loads.

Batching one-to-many relations, like “all posts for each author”, is harder. The batch function must group rows by parent key, and per-parent filters or ordering make that messy. If many resolvers need it, the alternative is a root resolver: translate the GraphQL selection into one Prisma select at the top. Libraries such as PrismaSelect from Pal.js do that translation, at the cost of tying your GraphQL schema closely to your database schema.

database query code

When raw SQL is the better tool

A common objection to ORMs is that a simple SQL query ends up as a series of queries in a loop. That’s a fair complaint about how ORMs get used, but you don’t have to leave Prisma to fix it. Some needs are simply easier to express in SQL: picking random rows, ordering parents by an average of their children, or aggregating across several tables in one pass.

Prisma gives you two ways out. $queryRaw takes a tagged template, so values are sent as parameters and not pasted into the string. TypedSQL, introduced as a preview feature in Prisma 5.19.0, goes further. You write .sql files in prisma/sql/, run prisma generate --sql, and call them through $queryRawTyped with fully typed results.

In our view, the right split is simple: keep Prisma’s query API for everyday reads and writes, where type safety pays off. Reach for TypedSQL on the handful of reporting or ranking queries that would otherwise turn into loops. Either way, the rule is the same: one request should cost a small, fixed number of queries.

Which fix to use: a decision table

Situation Do this Avoid
REST endpoint returns a list with a related field Nested select on the list query findUnique in a loop, or bare include when you need two fields
IDs come from several lists or services One findMany with in, then a Map Promise.all of single lookups
GraphQL to-one relation (post → author) Fluent API findUnique().author() or a DataLoader A loader shared across requests
GraphQL to-many relation with filters DataLoader grouped by parent key, or a root resolver One findMany per parent
You only need a count _count Loading the rows to call .length
Ranking, random picks, cross-table aggregates TypedSQL or $queryRaw Rebuilding SQL logic in a JavaScript loop
database query code

Five pitfalls that bring N+1 back

  • Symptom: the endpoint got faster but the database CPU didn’t drop. Cause: a loop was wrapped in Promise.all, so N queries now run in parallel. Fix: count queries, not milliseconds, and replace the loop with one batched query.
  • Symptom: the batched in query is still slow. Cause: the foreign key column has no index. PostgreSQL doesn’t index referencing columns automatically, while MySQL’s InnoDB engine creates an index for each foreign key. Fix: add @@index([authorId]) to the model and migrate.
  • Symptom: a filter suddenly returns every row. Cause: a value in where was undefined, and Prisma treats undefined as “no filter”. Fix: validate inputs before building the query, and never let an empty ID list fall back to undefined.
  • Symptom: GraphQL users see stale or someone else’s data. Cause: a DataLoader created once at startup and reused across requests. Fix: build loaders in the request context factory.
  • Symptom: fields come back attached to the wrong parent. Cause: the batch function returned rows in database order, not key order. Fix: map results back through the keys array, as in the example above.

How to measure the gain

Measure before you change anything, on the same endpoint and the same data. Three numbers are enough:

  • Queries per request, from the $on('query') counter.
  • Response time, ideally the 95th percentile (the time under which 95% of requests finish) rather than the average.
  • Total query time, the sum of e.duration for the request.

Example: if a list endpoint showed 51 queries before the fix and 2 after, the query count is the proof, whatever your timing noise. Then watch response times in production for a week, because the gain is often larger there than locally. To catch the next regression early, also review the top statements by call count in pg_stat_statements each month.

Use realistic data volumes. An N+1 on a table with 13 rows is invisible; the same code with 5,000 rows is not. A seed script that creates a few thousand records is a cheap way to make problems visible before users find them.

Prisma N+1 query checklist

  1. Turn on log: ['query'] in development.
  2. Add a per-request query counter and log it with the response time.
  3. Search the code for await inside loops and queries inside .map().
  4. Replace per-item lookups with nested select, or one in query plus a Map.
  5. Use _count when you only need a number.
  6. In GraphQL, use the fluent API or DataLoader, with new loaders per request.
  7. Index every foreign key column you filter or join on.
  8. Move ranking and aggregate queries to TypedSQL or $queryRaw.
  9. Test the join and query load strategies on the heaviest endpoints.
  10. Add a test that fails when an endpoint’s query count rises.

Start with the one endpoint your users wait on most. Turn on the counter, write down the number, and fix the biggest loop you find. A single afternoon on that path usually teaches a team more about its data access than any refactor plan. If you’re building or maintaining a Node.js API, make the query counter part of your project template, so every new endpoint ships with its number visible from day one.

FAQ

What is Prisma and why is it used?

Prisma is an open-source ORM for Node.js and TypeScript. You describe your data model in a schema file, and Prisma generates a typed client and migrations from it. Teams use it mainly for type safety and a readable query API. Much the same conclusion turns up on dev.to.

Does connection pooling fix an N+1 problem?

No. A connection pool saves the cost of opening connections, but each of the N queries still makes its own round trip. Pooling can even hide the problem for a while, until traffic grows and the pool runs out of free connections.

Is N+1 the same thing as over-fetching?

No, they’re opposite mistakes. Over-fetching loads more columns or rows than the page needs, while N+1 loads too little at first and goes back for the rest one item at a time. A nested select addresses both at once.

How do I optimize a slow SQL query in general?

Run it with EXPLAIN ANALYZE on PostgreSQL, or EXPLAIN on MySQL, to see whether it scans whole tables. Then add indexes on the columns used in filters and joins, and select only the columns you need. Check the query count first, though: ten fast queries in a loop won’t show up as one slow query.

Should I switch ORMs to get rid of N+1 queries?

Usually not. N+1 comes from how the code asks for data, and every ORM, including query builders, lets you write a loop of queries. Fixing the access pattern in Prisma is faster than a migration and teaches the same lesson.