N+1 query
An N+1 query is a pattern where code runs one query for a list, then one more query for each of its N rows.
An N+1 query is a pattern where code runs one query to fetch a list of N rows, then runs one extra query per row to fetch related data, for N+1 queries in total. It is usually caused by an ORM loading relationships lazily inside a loop.
Laravel’s documentation gives a typical example: loading all books, then reading each book’s author in a loop runs one query for the books and one per book for the authors, so 25 books means 26 queries. Loading the authors up front with eager loading reduces that to two.
SELECT * FROM books;SELECT * FROM authors WHERE id = 1;SELECT * FROM authors WHERE id = 2;-- ...one per bookEach query is fast, so nothing looks slow on its own, but the round trips add up. SQLEye flags the pattern at the database: the same query shape at least 5 times on one connection within 1,000 ms, with differing values, by default. See N+1 detection.
SQLEye is developed and maintained by CodeROG. This page is also available as Markdown.