The N+1 query problem occurs when code fetches a list of N items with one query and then runs a separate query for each item to load related data, resulting in N+1 queries instead of one or two.
Why it matters
Each query has network and parsing overhead, so a page that looks simple can send hundreds of queries and become slow as data grows. It is common with ORMs, where related objects load lazily and the extra queries are hidden behind innocent-looking property access. Query logs and counters reveal it quickly.
Example
posts = Post.all() # 1 query
for p in posts:
print(p.author.name) # 1 query per post
With 100 posts that is 101 queries. Eager loading (a join or WHERE author_id IN (...)) reduces it to two queries.
Common mistakes
- Not noticing it in development where the data set is small and everything feels fast.
- Fixing it with a huge join that returns a massive result when two simple queries would do.
- Hiding the problem behind caching rather than fixing the access pattern.
Related
Get notified when this term updates
Plus occasional practical tips on uptime and monitoring, nothing else. Unsubscribe anytime.
This page is general information written by our editorial team and updated when documentation changes. Servers and providers differ, so test changes safely first. See our editorial policy and disclaimer.