Skip to content
Search

N+1 Query Problem

lastmod 2026-02-12created 2026-02-121 edits

N+1 Query Problem (N+1 query problem, N+1 SELECT problem, N+1 problem)

  • A problem where one query fetches N rows, and then N more queries are run to get related columns
  • A problem where, for each row in a query result, a query is run repeatedly, once per row, to get the referenced information
  • Because the cost (count) of DB queries is high, solving it with methods such as eager loading is recommended

Example

Problem case:

$books = query_rows("SELECT * FROM books");
foreach( $books as &$book ) {
    $book['author_name'] = query_one("SELECT name FROM authors WHERE id=?", $book['author_id']); 
}
  • 1 query to get N books
  • N queries to get author_name
  • Quite disadvantageous for performance, but it does have the advantage that the logic is easy to understand.
$books = query_rows("SELECT b.*, a.author_name
    FROM books b LEFT JOIN authors a ON b.author_id=a.id");
  • Using a JOIN as above gets the result in a single query.

See also

  • SQL
  • eager loading
  • LEFT JOIN
  • query

Favorite site

author Zer0 sitemap