N+1 Query Problem — Explained with Examples
The N+1 query problem occurs when an application executes N additional database queries to load related data for each of N parent records, causing performance degradation.
N+1 describes a common performance anti-pattern in database access. The “1” is the initial query to fetch parent records, and the “N” is one query per parent to fetch related children. With 100 blog posts, this means 101 queries instead of 2.
Why N+1 Matters
One extra query per item doesn’t matter with 5 items. With 500, it means 501 queries — potentially seconds of latency. N+1 is the most common performance issue in ORM-driven applications and one of the easiest to fix once you know what to look for.
Real-World Analogy
You go to the library to find books by 10 authors. The librarian runs one query to get the 10 authors (1 query). Then, for each author, walks to the shelf to find their books (10 more trips). Instead, one query could get all books by all 10 authors in a single trip. The first approach is N+1.
Example: N+1 in an ORM
# Models
class Author(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
class Book(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String)
author_id = db.Column(db.Integer, db.ForeignKey('author.id'))
author = db.relationship('Author', backref='books')
# N+1 anti-pattern
authors = Author.query.all() # 1 query
for author in authors:
print(author.books) # N queries (one per author)
# Fixed — eager loading
from sqlalchemy.orm import joinedload
authors = Author.query.options(
joinedload(Author.books)
).all() # 1 query with JOIN
for author in authors:
print(author.books) # 0 additional queriesExpected performance difference: With 100 authors, the N+1 version runs 101 queries. The eager-loaded version runs 1 query.
Related Terms
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro