What is an N+1 query? It is one database query that loads a list, then one more query for each row in it: 50 orders cost 51 round trips. The code looks ordinary and passes a ten-row demo, but the page slows with every row customers add, so counting the queries a page runs finds it fastest.

What is an N+1 query: one list, then one more query per row

An N+1 query is the pattern of one query for a list followed by one query per row, so the number of round trips grows with the data. Each query can be fast on its own; the page is slow because it waits on dozens or hundreds of them, in turn or at once.

The name is the count. N stands for the rows the list returns, and the 1 is the query that fetched the list. The Rails guide counts its own example the same way: ten books and their authors take “1 (to find 10 books) + 10 (one per each book to load the author) = 11 queries in total”.

N+1 is one of the database checks a SaaS needs between a demo and production, and the data consistency checklist for SaaS walks through the others.

Here is a typical N+1 query example in a Supabase client: one call loads the posts, then Promise.all(posts.map(async ...)) looks up each post’s author in profiles, one call per post.

const { data: posts } = await supabase.from('posts').select('id, title, author_id');

const withAuthors = await Promise.all(
  posts.map(async (post) => {
    const { data: author } = await supabase
      .from('profiles').select('name').eq('id', post.author_id).single();
    return { ...post, author };
  }),
);

With Promise.all, the per-row lookups run at the same time instead of one after another. For a short list that hides the cost, and it is the reason the code reads as the careful version. It still sends one query per post, so a list of N posts still costs N+1 queries.

Why AI-generated code writes N+1 queries

The loop is the answer that needs the least knowledge of the schema. There is no join to get right and no foreign key to reason about: fetch the list, then fetch each related row. Each call is valid on its own, there is no visible for loop to catch the eye, and a demo with ten rows never shows the cost. As we read it, that is why the code Lovable, Bolt, Cursor or Claude Code writes for a prompt asking for the list with the author names can take this shape. ORMs hide the same loop behind a property. In Rails, reading book.author inside a loop over books runs one query per book, and in Django, touching a related object that was not loaded with the list “Hits the database again”. The code shows a property access; the database log shows a query for every row.

What N+1 queries do to an app as its data grows

The cost of an N+1 query grows with the rows, not with the code, so the page that was fine at launch gets slower every week without a single deploy.

The first effect is waiting. Every query is its own trip: the request crosses the network, the database plans and runs it, and the rows travel back. pg_stat_statements counts each run of a statement in its calls column, which is why a per-row lookup shows up there as one statement with a very large count. Run the lookups one after another and their times add up; run them at once and they compete for the same database connections instead.

The second effect lands on everyone else. The database and the connection pool carry N small queries where one would do, so one busy list page can hold connections that other requests are waiting for. How many connections an app should keep open, and what happens when they run out, is the subject of connection pooling for Postgres.

The third effect is the one founders notice: a dashboard slow with many database calls. An admin dashboard whose cards each loop over the customer list multiplies the pattern, because every card runs its own per-customer lookups on the same page load.

We audited 21 third-party apps in June and July 2026, and in one of them a health-data API brought in a patient’s history with a separate database trip for each item, while code a few hundred lines further on did the same kind of import as one batch. Those 21 apps were chosen for review, not drawn at random, so the finding shows what the pattern looks like in a real codebase, not how often it occurs. The lesson we take from it: the batched version often already exists somewhere in the code, and the loop is the copy nobody updated.

If list pages already slow down for paying customers and nobody on the team can say which pages run one query per row, that is the point to book a free audit: we weigh up with you which screens to measure first and what the fix costs in time. In the Production Hardening Sprint, N+1 query removal is one of the 123 deliverables (4.3).

When an N+1 query is fine

Not every extra query needs fixing. A detail page with a few lookups the product caps, such as one order and its handful of summary rows, can run several cheap queries with no delay a user would notice. The test is whether N is capped by the product or grows with the customer’s data: a post list, a comment thread and an order history all grow. Our working rule is to fix N+1 where N grows with the customer’s data and to leave a few capped lookups alone until the query count and the page time say otherwise.

N+1 query problem solution: joins, batching and eager loading

The N+1 query problem solution is to fetch the related rows in one go: a join, a single batched lookup with an IN list, eager loading in the ORM, or one database function. Each turns N+1 round trips into one or two, whatever the number of rows.

Rails’ own example shows the size of the change: with includes, the ten books and their authors take 2 queries instead of 11. How to solve the N+1 query problem depends on where the loop lives, so the table puts the five usual places side by side.

Where the loop livesThe N+1 shapeThe fixThe call that does it
Plain SQLone select ... where id = $1 per rowone join, or one lookup for every idjoin ... on, where id = any($1)
Supabase client.eq('id', ...) inside a .map over the lista nested select, or one .in() batchselect('id, title, profiles(name)'), .in('id', ids)
Prisma, Drizzlea relation read once per rowload the relation with the listPrisma ORM 7 include: { author: true }, ORM 8 .include("author"); Drizzle with: { author: true }
Rails, Djangoa lazy association read in a loopeager loadingincludes, preload, eager_load; select_related, prefetch_related
Postgres functiona total or count worked out per row in app codeone set-based functionsupabase.rpc('function_name')

In SQL: one join or one IN list

The per-row select ... where id = $1 goes away in favor of one statement. A join returns each post with its author’s name; = any($1) takes an array of ids and compares the column with each element, so one statement serves the whole list.

-- N+1: this runs once for every post
select name from profiles where id = $1;
-- One statement: a join
select p.id, p.title, pr.name from posts p join profiles pr on pr.id = p.author_id;
-- Or one lookup for every author id at once
select id, name from profiles where id = any($1);

The one statement still has to find its rows fast. A lookup by primary key has an index already, but a lookup by a foreign key, such as the comments that belong to a post, may have none: Postgres does not create an index on the referencing columns when a foreign key is declared. Without one, the one query is slow instead of the many, and the last H3 of this section covers adding it.

In the Supabase client: a nested select or .in()

Supabase’s joins and nesting docs say the Data APIs “automatically detect relationships based on the foreign keys”, so a nested select names the related table inside the same select() call and the related row arrives nested in each result. This needs a foreign key from posts.author_id to profiles. Where there is none, or the lookup is not a plain relation, the .in() filter matches “only rows where column is included in the values array”, which turns the per-row calls into one.

// Option 1: one call, each post arrives with its profile nested
const { data: posts } = await supabase.from('posts').select('id, title, profiles(name)');

// Option 2: the list, then every author in one .in() call
const { data: list } = await supabase.from('posts').select('id, title, author_id');
const ids = [...new Set(list.map((p) => p.author_id))];
const { data: authors } = ids.length
  ? await supabase.from('profiles').select('id, name').in('id', ids)
  : { data: [] };
const byId = new Map(authors.map((a) => [a.id, a]));

Three details make the batch safe. The Set drops duplicate ids, the empty-list check skips a call that has nothing to ask for, and the Map puts each author back on its post by id, since Postgres returns rows without an order by “in whatever order the system finds fastest to produce”. In our view the parent list should also be paginated, so the id list never grows without bound. The other reasons a Supabase project drags, such as missing indexes and per-row policies, are covered in why a Supabase app feels slow.

To eager load related records in an ORM, ask for the relation together with the list instead of touching it once per row. Each ORM spells it differently:

// Prisma ORM 7
const posts = await prisma.post.findMany({ include: { author: true } });
// Drizzle
const posts = await db.query.posts.findMany({ with: { author: true } });
# Rails
books = Book.includes(:author).limit(10)
# Django
entries = Entry.objects.select_related("blog")

Prisma’s relation queries now document Prisma ORM 8, where .include("author") replaces ORM 7’s include: { author: true } and fetches the relation “in the same query as the parent: one SQL statement”. On ORM 7, the relationLoadStrategy option, still in Preview, picks join, the default, which fetches everything in a single query, or query, which sends one query per table. Drizzle’s relational queries load related rows with with, and the docs say “a single SQL statement is outputted by Drizzle”. The Rails guide to eager loading offers includes, preload and eager_load and says to prefer includes, which “will use either preload or eager_load depending on the query”. In Django, select_related follows a foreign key or one-to-one relation with a join, and prefetch_related covers the many side with one extra batch query per lookup; Django’s select_related and prefetch_related reference has the details.

If the app hides soft-deleted rows with a default filter, check that the relation loaded with the list still leaves those rows out. That filter is its own topic: excluding soft deleted rows from default queries.

Batch the lookups a loop makes

To batch the database queries a loop makes, collect the keys it would look up, run one query for all of them, and match the results back to the rows by key in memory. The Supabase .in() code above is that pattern; in SQL it is the any($1) lookup, and in a background job it is the same three steps around the job’s loop. One side effect is useful: a batch that returns fewer rows than it asked for can point at references with no parent row, the orphaned rows the database cleanup checklist finds. The way to avoid the N+1 query problem in new code is to write the batch the first time a loop touches the database.

Push the work into one database function

When the per-row work is a total or a count, such as comments per post, one Postgres function can do it for every row in a single statement, and the client calls it once with rpc(), as in supabase.rpc('post_comment_counts').

create or replace function public.post_comment_counts()
returns table (post_id bigint, comment_count bigint)
language sql security invoker
as $$
  select post_id, count(*) from public.comments group by post_id;
$$;
revoke execute on function public.post_comment_counts() from public, anon;
grant execute on function public.post_comment_counts() to authenticated;

A function is not an access boundary, so treat it with the same care as a table. Supabase database functions run “either as the user calling it (invoker) or as its creator (definer)”; Supabase advises security invoker, “which is also the default”, and warns that “A security definer function can return rows the caller isn’t allowed to read.” The same page says “By default, any role can run a database function”, so revoke execute from public and anon and grant it only to the role that needs it, as the code does. Then sign in as one test user and confirm the counts include only rows that user is allowed to read.

Add the index the fixed query needs

The join or IN list moves the work into one query, and that query now filters on the foreign key, which the PostgreSQL manual says it is “often a good idea to index”. Read the plan with PostgreSQL’s EXPLAIN before trusting the fix. Its ANALYZE option runs the statement for real (“the statement is actually executed”), so use EXPLAIN ANALYZE only on a read, in a copy of the database that is not production. Which indexes to add, and how to read the plan they produce, is covered step by step in how to analyze a Postgres query.

How to verify it: count database queries per request

A query count per request is the test for N+1: load a representative list view and a detail view, read how many queries each ran, and fix the page whose count rises with its rows. The same count, kept as an automated test after the fix, stops the pattern from coming back.

The steps work on any stack; only the tool that reads the count changes. Keep the evidence each step names, because the before and after numbers are what show the fix worked.

  1. 01 Seed a database that is not production with a realistic number of rows for the list under test, so N is as large as a real customer would make it. Evidence: the row counts.
  2. 02 Read the query counts before loading anything: the calls column of pg_stat_statements, or the ORM query log (Prisma with log set to query, the Rails development log, Django connection.queries with DEBUG on). Evidence: the starting numbers.
  3. 03 Load one representative list view and one detail view, once each. Evidence: the two URLs and the time of each load.
  4. 04 Read the counts again and compare the change: a lookup whose calls rose by the number of rows, next to a list query that rose by one, is an N+1 in two lines. Evidence: the before and after counts.
  5. 05 After the fix, keep the count as a test that fails the build if someone brings the loop back, such as Django assertNumQueries or Rails strict loading turned on for tests. Evidence: the test, failing before the fix and passing after.

On Postgres, pg_stat_statements usually combines statements that differ only in the values of their constants into one entry and shows the constant as $1, so the per-row lookup appears as a single line whose calls climb with the list. On Supabase, open the Extensions page first and enable pg_stat_statements if it is off. This query lists the busiest statements:

select calls, query
from pg_stat_statements
order by calls desc
limit 20;

Compare the change between two readings rather than clearing the counters. Called with no arguments, pg_stat_statements_reset() will “discard all statistics”, and by default only superusers can run it. For the ORM log, Prisma ORM 7 prints each query when the client is created with log: ["query"], and Django’s connection.queries lists each statement in order but “is only available if DEBUG is True”. The lasting check is the test in step 5: Django’s assertNumQueries “Asserts that when func is called … that num database queries are executed”, and Rails raises ActiveRecord::StrictLoadingViolationError on a lazy load once config.active_record.strict_loading_by_default is true. Keep the before and after counts and the page time together. A query count says nothing about how the app behaves with many users at once; that takes load testing a web application.

In the Production Hardening Sprint, deliverable 4.3 is verified this way: measure database query counts for representative list and detail views.

Where the sprint does this

Our engineers replace repeated per-record lookups with appropriate joins, batching, or prefetching (deliverable 4.3), and review every foreign key and hot query path with execution plans and implement appropriate indexes (4.2). We apply the equivalent controls for your database and framework, and the implementation follows your stack.

Common questions about N+1 queries in ORMs and SQL

How can I solve the N+1 query problem in Hibernate?

Fetch the association with the query that loads the list, using a join fetch in JPQL or a Jakarta Persistence entity graph that marks the association for eager loading. Hibernate’s @BatchSize annotation is the fallback: it loads uninitialized proxies in batches instead of one at a time, but the Hibernate user guide calls a DTO projection or a JOIN FETCH “a much better alternative” most of the time, since either fetches the data in a single query.

How can I efficiently solve the N+1 query problem in an entity framework?

In Entity Framework Core, load the related data in the same query with Include, and use ThenInclude for each level below it, as in context.Blogs.Include(blog => blog.Posts).ThenInclude(post => post.Author). When one query includes several collections, the joined result can repeat rows as a cross product, which Microsoft’s docs call Cartesian explosion; adding AsSplitQuery() then sends one extra SQL query per included collection instead.

How to run multiple SELECT SQL queries at once?

Send them in one round trip. PostgreSQL’s simple query protocol accepts several statements separated by semicolons in one message and runs them as a single transaction unless the message includes its own transaction control commands, and UNION ALL merges SELECTs that return the same number of columns, with compatible types, into one result. When the SELECTs come from an N+1 loop, replace them with one SELECT that uses IN, = any or a join, so the per-row statements are never sent at all.

When should I get help with N+1 queries in a live app?

Get help when list pages slow down as customers add data and nobody on the team can say which pages run one query per row, because a fix on the wrong screen spends the time and leaves the slow one as it was. AxonBuild can go over your slowest screens with you on a free audit and help you decide which to measure first.