Skip to content
BENIBIX Learn

N+1 Query Problem

Development🗃️ DatabasesDatabases in Code

Also known as N+1 Problem, N+1 Queries, N+1 Query, N+1, N plus one

One query for a list, then one more for each item. Pages get slow.

Think of it like

Think of it like going to the shop once for each thing on your list. You could go once for all.

Example

Jack's order page sent 201 queries for 200 orders. Loading the customers in one extra query cut it to 2, and the page went from 2 seconds to 80 milliseconds.

Why it matters

It is one of the most common reasons a page is slow. Once you see it, it is easy to fix.

Definition

The N+1 query problem is when code gets a list, then runs one more query per item. For 100 orders, that is 1 query for the orders and 100 more for their customers. Each query is fast, but together they make the page slow. It often happens by accident with an ORM, inside a loop. The fix is one join, or asking the ORM to load the related rows up front.

Example code

sql
SELECT * FROM orders;                  -- 1 query
SELECT * FROM customers WHERE id = 1;  -- then 1 per order
SELECT * FROM customers WHERE id = 2;
SELECT * FROM customers WHERE id = 3;
The log shows one query for the list and one for each order.

Common mistake

Only testing with three rows of data. With three, it looks fine; with three thousand, the page crawls.

Key takeaways

  1. 1
    One plus one each. The query count grows with the list.
  2. 2
    Hidden in loops. Often caused by an ORM.
  3. 3
    Load up front. One join or one extra query.