शब्दकोश · डेटाबेस

N+1 Query Problem

The N+1 query problem is a performance bug where code runs one query for a list and then one more query per item, causing hundreds of needless database calls.

अपडेट: अक्टूबर 6, 2026

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.

Get notified when this term updates

Plus occasional practical tips on uptime and monitoring, nothing else. Unsubscribe anytime.

यह पेज सामान्य जानकारी है, जिसे हमारी संपादकीय टीम ने लिखा है और दस्तावेज़ीकरण बदलने पर अपडेट किया जाता है। सर्वर और प्रदाता अलग-अलग होते हैं, इसलिए बदलाव पहले सुरक्षित तरीके से जाँचें। देखें: संपादकीय नीति और अस्वीकरण.