SyntaxStudy
Sign Up
MySQL Intermediate 4 min read

The N+1 Query Problem

N+1 Problem

N+1 occurs when you fetch N rows and then issue a separate query for each row. Fix by using JOINs, subqueries, or batch loading.

Example
-- N+1 (one query per order)
SELECT id FROM orders;  -- returns 100 rows
-- then for each row:
SELECT * FROM customers WHERE id = ?;

-- Fixed with JOIN
SELECT o.id, c.name
FROM orders o
JOIN customers c ON c.id = o.customer_id;
Pro Tip

ORM eager loading (e.g., with()) translates to a JOIN or IN() query — always use it.