LESSON 9 OF 19

The N+1 Query Problem: Eliminating Queries Executed Inside Loops

Learn how to detect the N+1 Query problem in order processing and compare projection, Include and pre-grouped data approaches to reduce database roundtrips.

40 dk 74

Introduction

Displaying a list of orders may appear straightforward: load the orders first, then display each order's customer or products. However, if related data is queried separately inside a loop, the application can generate far more database calls than expected. This is known as the N+1 Query problem.

In N+1, the 1 represents the initial query that loads the main records, while N represents the additional query executed for every record in that result. For example, loading 100 orders and then querying the customer for each order produces 101 queries. As the data volume grows, latency, connection usage and production costs can increase rapidly.

In this lesson, you will reproduce the flawed approach, inspect the generated SQL and compare projection, Include and pre-grouped data strategies for solving the same requirement.

Sample model and problem scenario

In this example, every order belongs to a customer and contains order items associated with products:

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; } = null!;
    public ICollection<Order> Orders { get; set; } = new List<Order>();
}

public class Order
{
    public int Id { get; set; }
    public DateTime CreatedAt { get; set; }
    public int CustomerId { get; set; }
    public Customer Customer { get; set; } = null!;
    public ICollection<OrderItem> Items { get; set; } = new List<OrderItem>();
}

public class OrderItem
{
    public int Id { get; set; }
    public int OrderId { get; set; }
    public int ProductId { get; set; }
    public int Quantity { get; set; }
    public Product Product { get; set; } = null!;
}

The problem commonly appears in code like this:

var orders = await db.Orders
    .Where(o => o.CreatedAt >= startDate)
    .ToListAsync();

foreach (var order in orders)
{
    var customer = await db.Customers
        .FirstOrDefaultAsync(c => c.Id == order.CustomerId);

    Console.WriteLine($"{order.Id} - {customer?.Name}");
}

The first ToListAsync generates one query. The FirstOrDefaultAsync call inside the loop runs again for every order. With 50 orders, the application sends 51 queries; with 1,000 orders, it sends 1,001. This may look acceptable with test data but can consume database connections unnecessarily in a real environment.

How to detect the N+1 problem

1. Enable SQL logging

During development, EF Core commands can be observed with LogTo:

protected override void OnConfiguring(
    DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder
        .UseSqlServer(connectionString)
        .LogTo(Console.WriteLine, LogLevel.Information);
}

If the log shows the same customer query being repeated with different parameter values, you have strong evidence of an N+1 pattern. In production, avoid writing unrestricted SQL details to the console. Prefer structured logging, appropriate filters and protection for sensitive values.

2. Inspect the SQL representation

To inspect the SQL that a LINQ query would generate without executing it, call ToQueryString():

var query = db.Orders
    .Where(o => o.CreatedAt >= startDate)
    .Select(o => new
    {
        o.Id,
        CustomerName = o.Customer.Name
    });

Console.WriteLine(query.ToQueryString());

ToQueryString displays the SQL representation of one query. To evaluate the total number of commands, use application logs, a database profiler or a command interceptor in tests.

Solution 1: Use projection for one query

If the list only displays the order number, date and customer name, loading the complete entity graph is unnecessary. Projection is often the best starting point:

var orderRows = await db.Orders
    .AsNoTracking()
    .Where(o => o.CreatedAt >= startDate)
    .OrderByDescending(o => o.CreatedAt)
    .Select(o => new OrderListRow
    {
        OrderId = o.Id,
        CreatedAt = o.CreatedAt,
        CustomerName = o.Customer.Name
    })
    .ToListAsync();

The customer name is selected through the relationship as part of the same SQL query. The application does not need to look up the customer again inside the loop. Since only the required columns are selected, the amount of transferred data is also reduced.

Projection is particularly suitable for list screens, reports and API responses. If the use case requires updating entities or working with a complex aggregate, loading entities may still be appropriate. For read-only screens, however, a DTO or a dedicated row model is usually more controlled.

Solution 2: Use Include for eager loading

If the business logic really requires Order, Customer and Items entities, related data can be loaded explicitly with eager loading:

var orders = await db.Orders
    .AsNoTracking()
    .Where(o => o.CreatedAt >= startDate)
    .Include(o => o.Customer)
    .Include(o => o.Items)
        .ThenInclude(i => i.Product)
    .ToListAsync();

foreach (var order in orders)
{
    Console.WriteLine(order.Customer.Name);
    foreach (var item in order.Items)
    {
        Console.WriteLine($"{item.Product.Name}: {item.Quantity}");
    }
}

This approach removes the need to query inside the loop. However, Include is not automatically the best choice for every scenario. Large collections, multiple collection Includes and unnecessary columns can make a single query very large and may cause row multiplication.

When appropriate, consider AsSplitQuery():

var orders = await db.Orders
    .AsNoTracking()
    .AsSplitQuery()
    .Include(o => o.Customer)
    .Include(o => o.Items)
        .ThenInclude(i => i.Product)
    .ToListAsync();

A split query can load relationships with separate SQL commands and reduce cartesian multiplication in large join results. The total number of queries may no longer be one, so the decision should be based on data volume and measurements.

Solution 3: Pre-grouped or indexed data

In some cases, loading data from separate sources and matching it in memory is clearer or more efficient. For example, load the orders and customer IDs first, then retrieve all required customers with one Contains query:

var orders = await db.Orders
    .AsNoTracking()
    .Where(o => o.CreatedAt >= startDate)
    .Select(o => new { o.Id, o.CustomerId, o.CreatedAt })
    .ToListAsync();

var customerIds = orders
    .Select(o => o.CustomerId)
    .Distinct()
    .ToList();

var customers = await db.Customers
    .AsNoTracking()
    .Where(c => customerIds.Contains(c.Id))
    .ToDictionaryAsync(c => c.Id);

var rows = orders.Select(o => new
{
    o.Id,
    o.CreatedAt,
    CustomerName = customers[o.CustomerId].Name
}).ToList();

This approach performs two queries instead of one query per order. However, consider the size of customerIds, how the provider handles the generated IN expression and what should happen if a customer record is missing. Combining data in memory can also increase application memory usage for very large result sets.

Batching order item data

Suppose a report needs the total quantity and distinct product count for every order. Rather than querying products or items separately for each order, express the requirement in one projection:

var summaries = await db.Orders
    .AsNoTracking()
    .Where(o => o.CreatedAt >= startDate)
    .Select(o => new
    {
        OrderId = o.Id,
        CustomerName = o.Customer.Name,
        ItemCount = o.Items.Sum(i => i.Quantity),
        ProductCount = o.Items.Select(i => i.ProductId).Distinct().Count()
    })
    .ToListAsync();

The calculations are pushed to the database whenever the provider can translate them. This can prevent unnecessary rows from being materialized in memory. You should still inspect the generated SQL because translation details can vary by provider and expression.

Common mistakes

  • Using lazy loading invisibly: Accessing a navigation property may trigger another query. This is especially difficult to notice in serializers, views and mapping code.
  • Calling ToList too early: If ToList is called before filtering and projection, the remaining work may happen in memory and too much data may be loaded.
  • Adding Include everywhere: Loading unused relationships increases query size and result volume. Define the requirement first, then choose projection or Include.
  • Assuming AsNoTracking solves N+1: No-tracking queries can reduce tracking overhead, but they do not automatically reduce the number of database roundtrips.
  • Looking only at duration: One fast query executed hundreds of times can still be a serious problem. Measure both execution time and roundtrip count.
  • Including multiple collections without measuring: Check whether result rows multiply significantly. Projection or split queries may be more suitable.

Practice exercise

Complete the following exercise in the existing laboratory project:

  1. Create test data with at least 20 orders and several different customers.
  2. Write the flawed version that queries the customer inside the loop.
  3. Use LogTo to observe the total number of SQL commands.
  4. Rewrite the same requirement with projection and compare the query count.
  5. Create a second solution using Include and ThenInclude as if the entity objects were required.
  6. Verify that both solutions return the same result, then compare selected columns, execution time and transferred data.

At the end, answer these questions: Which approach transfers the least data? When is Include easier to read? How did split queries change the command count? What are the limits of the pre-grouped approach when the customer list becomes very large?

Conclusion

The N+1 Query problem is usually caused not by the database model itself, but by the way data is accessed. Running FirstOrDefaultAsync, FindAsync or similar operations inside a loop can become a serious performance issue as the result set grows.

Start by inspecting logs and measuring the number of commands. For list and report screens, consider projection so that only the required fields are selected. If the entity graph is needed, use Include and ThenInclude while measuring cartesian multiplication and split-query behavior for large collections. When several queries are appropriate, group identifiers and use a batch query with dictionary-based matching.

The central principle is simple: database queries should not be hidden inside loops. They should be visible in the code, measured and verified through generated SQL. This leads to more predictable, measurable and maintainable data-access code in EF Core applications.

Sources