Glossary · PHP & Backend

What is the N+1 query problem?

Short answer

The N+1 query problem is a performance bug where code runs one database query to fetch a list of N records, then one more query for each record to fetch related data, N+1 queries in total instead of one or two. It usually comes from lazy loading in ORMs such as Eloquent or Doctrine and gets slower as data grows.

An example in Laravel

$posts = Post::all();            // 1 query
foreach ($posts as $post) {
    echo $post->author->name;    // 1 query per post
}

With 100 posts that is 101 queries. Eager loading fetches the authors in a single extra query:

$posts = Post::with('author')->get();   // 2 queries in total

How to catch it

  • Laravel: call Model::preventLazyLoading() in development so lazy loading throws an exception, and watch query counts in Laravel Debugbar or Telescope.
  • Symfony and Doctrine: use the profiler’s Doctrine panel; fetch joins or addSelect for related entities.
  • In tests, assert the number of queries for key pages.

Where else it appears

APIs that return nested resources, templates that touch relationships in loops, and GraphQL resolvers, where a batching layer such as DataLoader groups lookups into one query.

Published · Updated · By · All terms

Go deeper