N+1 Query Problem
N+1 Query Problem is a SQL statement in the SELECT Queries category. The N+1 problem occurs when you query a list (1 query) and then query details for each row (N queries). Devastating for performance. The syntax is -- N+1: one query for list, then N queries for details. Fix with JOIN or eager loading.. It returns query optimization pattern. A typical example: -- PROBLEM: N+1 queries -- 1. SELECT * FROM employees; -- Get 100 employees -- 2. For each employee: SELECT * FROM departments WHERE id = ?; -- 100 queries! -- Total: 101 queries, very slow -- FIX: JOIN (1 query) SELECT e.*, d.dept_name, d.budget FROM employees e JOIN departments d ON e.dept_id = d.id; -- Single query returns all needed data -- ORM anti-pattern: -- for employee in Employee.objects.all():… A close relative is SELECT, which retrieves data from a table. The most fundamental SQL statement.