Course contentsShow
← Software Engineering
Lesson 944 of 1,93329. Object-Relational MappingFree lesson

The N+1 Query Problem

Understanding how lazy loading can trigger hundreds of queries and learning to recognize and prevent this common ORM pitfall.

The N+1 Query Problem

You'll learn: How lazy loading can accidentally cause your ORM to execute hundreds of unnecessary database queries, slowing your application to a crawl.

What Is the N+1 Query Problem?

The N+1 query problem occurs when your code executes 1 query to fetch a list of N parent objects, then executes N additional queries—one per parent—to fetch related child data. This happens when an ORM uses lazy loading and you iterate over a collection accessing related objects.

Example scenario: You fetch 100 users, then loop through them displaying each user's associated company name. With lazy loading, the ORM fetches companies on-demand:

  1. 1 query to fetch 100 users
  2. 100 queries to fetch each user's company (one at a time)
  3. Total: 101 queries instead of 2

Why This Happens

When you map associations in an ORM, the default behavior is often lazy loading—related objects aren't fetched until you actually access them. This feels natural in code (user.company.name) but creates a hidden performance disaster when repeated in loops.

Recognizing the Problem

Watch for:

  • Loops over collections that access related objects
  • Slow page loads with many small, repetitive queries in logs
  • Query counts that scale linearly with result set size

Prevention Strategies

Use eager loading to fetch related data upfront in a single query or small number of queries (JOIN or separate bulk queries). The Repository Pattern and Query Object Pattern help you explicitly control loading strategy rather than relying on default lazy behavior.

Key Takeaway: The N+1 problem turns N objects into N+1 database round-trips; prevent it by eagerly loading associations when you know you'll need them, not relying on implicit lazy loading during iteration.