What is a (n+1) query?

Basics of web backend development

Martin Thoma
Plain and Simple

--

An (n+1) query is a performance issue that happens in backend development. Instead of doing one query to show n objects, one does one query to get the objects and n additional query to get detail information.

Example

Imagine you have a website about books. The DB has two tables:

Book:

  • book_id
  • title
  • author_id

Author:

  • author_id
  • name

The book website has a page where all books are listed, so it executes:

SELECT * FROM book

Maybe you’re doing it in an ORM, so something like this:

for book in Book.objects.all():
print("{book.title} | book.author.name ")

Looks fine, but the ORM executes a SELECT-query for every single book to get the author-dataset:

SELECT * FROM book
# now for n=5 books:
SELECT * FROM author WHERE author_id = 4
SELECT * FROM author WHERE author_id = 1
SELECT * FROM author WHERE author_id = 3
SELECT * FROM author WHERE author_id = 2
SELECT * FROM author WHERE author_id = 5

Why is it an issue?

--

--

No responses yet