🗃️N+1 Query Problem
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
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;Common mistake
Key takeaways
- 1One plus one each. The query count grows with the list.
- 2Hidden in loops. Often caused by an ORM.
- 3Load up front. One join or one extra query.