Skip to content
Prompt Words
History

N+1 query

Also called: N+1 problem, N plus one queries, query in a loop.

Code loads a list with one query, then runs one more query for each item in it. 50 posts become 51 database calls, and the page gets slower as the list grows.

One GET /orders request returns 5 orders, each with its customer. Inside it, N+1 asks for each customer in its own query; an IN query asks for all 5 at once.

N+1
–not run yet
One IN query
–not run yet

Rough time if each query takes about 2 ms.

Nothing loaded yet. Try both ways and compare the query count.

    Idle

    Say it in a prompt

    Fix the N+1 queries on the orders page. It loads 100 orders and then each order's customer and items one at a time; eager-load customers and items so the page makes 3 queries in total, and log a warning in development when one request runs more than 20 queries.

    Vague vs precise prompt

    Vague prompt

    the posts page is slow, make it faster

    Typical resultAdds a cache in front of the page or suggests a bigger database. The page still runs one author query per post, so it slows down again as posts grow.

    Precise prompt

    GET /posts has an N+1 query: 1 query for 50 posts, then 1 per post for its author. Load all authors in one query with WHERE id IN (...), or eager-load them, and add a test that the endpoint runs at most 3 queries.

    Typical resultThe endpoint makes 2 queries however many posts there are, and the test fails if someone puts a query back inside the loop.

    Where it shows up

    • A blog's home page lists 10 posts and then asks the database for each post's author separately: 11 queries where 2 would do.
    • An ORM loads a related record lazily inside a loop, so a page that felt fast with 5 rows in development is slow with 500 rows in production.

    You might describe it as

    • the page gets slower the more items there are
    • hundreds of tiny database queries for one page
    • a database call inside a for loop

    Not to be confused with

    • Batch endpoint

      An N+1 query is too many database calls inside one request; a batch endpoint lets a client send many operations in one HTTP request.

    • Bulk write

      An N+1 query is many small reads; a bulk write fixes many small writes by saving them in one statement.