# N+1 Query Problem

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

**Field:** Software Development  
**Category:** Databases  
**Also known as:** N+1 Problem, N+1 Queries, N+1 Query, N+1, N plus one

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

## 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

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.

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

## Why it matters

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

## Common mistake

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

## Three principles

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

## Related terms

- [Object-Relational Mapping (ORM)](https://learn.benibix.com/term/development/orm)
- [SQL Join](https://learn.benibix.com/term/development/join)
- [Database Query](https://learn.benibix.com/term/development/query)
- [Loop](https://learn.benibix.com/term/development/loop)

---

Source: https://learn.benibix.com/term/development/n-plus-one-query
Author: Behnia Zarei (a developer in Vienna, Austria, who builds and teaches data, AI and business intelligence at BENIBIX)
Publisher: BENIBIX Learn (https://learn.benibix.com/)
Last updated: 2026-11-19
Licence: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Quote freely with attribution.
