LESSON 17 OF 19

Finding the Cause of a Slow Query: Inspecting Generated SQL, Logging and Index Impact

Measure slow EF Core queries with logging, ToQueryString and query plans, then compare indexes, sargable predicates and unnecessary Include usage.

40 dk 97

Introduction

Discovering that a query is slow does not identify the root cause. The delay may come from a missing index, an inefficient LINQ-to-SQL translation, unnecessary related data, excessive materialization, or a database plan that scans far more rows than expected. For that reason, performance analysis should not stop at the C# expression. You must inspect the generated SQL, execution time, result size and database query plan together.

In this lesson, we will analyze a slow order-filtering query in an EF Core 10 and .NET 10 application using SQL Server. We will make the query measurable, inspect its SQL with ToQueryString, filter EF Core logs and use the execution plan to evaluate index usage. We will then compare indexed and non-indexed cases, sargable and non-sargable predicates, and unnecessary Include usage.

1. Preparing a reproducible performance lab

Assume that customers have orders and that the application needs to list orders created within a date range with a particular status.

public class Order
{
    public long Id { get; set; }
    public int CustomerId { get; set; }
    public string Status { get; set; } = null!;
    public DateTime CreatedAt { get; set; }
    public decimal TotalAmount { get; set; }

    public Customer Customer { get; set; } = null!;
}

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

The initial query is intentionally simple:

var orders = await db.Orders
    .Where(o => o.Status == "Paid"
        && o.CreatedAt >= from
        && o.CreatedAt < to)
    .OrderByDescending(o => o.CreatedAt)
    .ToListAsync(cancellationToken);

First, measure the operation. A Stopwatch can be useful during development, while production systems should also use application metrics, tracing and database monitoring.

var stopwatch = Stopwatch.StartNew();

var orders = await db.Orders
    .Where(o => o.Status == "Paid"
        && o.CreatedAt >= from
        && o.CreatedAt < to)
    .OrderByDescending(o => o.CreatedAt)
    .ToListAsync(cancellationToken);

stopwatch.Stop();
logger.LogInformation(
    "Order query returned {Count} rows in {ElapsedMs} ms",
    orders.Count,
    stopwatch.ElapsedMilliseconds);

A single measurement can be misleading. The first execution may include connection setup, compilation or cache effects, while later executions may behave differently. Use representative data, realistic parameters and multiple runs before drawing conclusions.

2. Enabling EF Core logging

EF Core integrates with Microsoft.Extensions.Logging and can write database command information through the application's logging pipeline. During development, LogTo provides a convenient way to inspect command execution.

protected override void OnConfiguring(
    DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder
        .UseSqlServer(connectionString)
        .LogTo(
            Console.WriteLine,
            new[] { DbLoggerCategory.Database.Command.Name },
            LogLevel.Information)
        .EnableDetailedErrors();
}

The log normally includes the command, parameters and execution duration. A representative entry might look like this:

Executed DbCommand (184ms) [Parameters=[@__from_0='2026-01-01'], CommandType='Text']
SELECT [o].[Id], [o].[CreatedAt], [o].[CustomerId], [o].[Status], [o].[TotalAmount]
FROM [Orders] AS [o]
WHERE [o].[Status] = N'Paid'
  AND [o].[CreatedAt] >= @__from_0
  AND [o].[CreatedAt] < @__to_0
ORDER BY [o].[CreatedAt] DESC

Separate two kinds of duration. The database command time is not always the same as the total application time. Network transfer, materialization and application-side processing may contribute to the total. Conversely, a fast command can still be problematic if it returns a very large result set.

Do not enable unrestricted sensitive-data logging in production. SQL parameters may contain personal, financial or business information. Use appropriate log levels, masking and access controls.

3. Inspecting SQL with ToQueryString

ToQueryString shows the SQL that EF Core is expected to generate without executing the query. It is useful for examining translation and detecting unexpected joins or filters.

var query = db.Orders
    .Where(o => o.Status == "Paid"
        && o.CreatedAt >= from
        && o.CreatedAt < to)
    .OrderByDescending(o => o.CreatedAt);

var sql = query.ToQueryString();
logger.LogDebug("Generated SQL:\n{Sql}", sql);

var orders = await query.ToListAsync(cancellationToken);

When reading the generated SQL, ask the following questions:

  • Is filtering performed in the database, or are all rows loaded first?
  • Did EF Core generate an unexpected join, subquery or sort?
  • Are only the required columns selected?
  • Are functions or conversions applied to filtered columns?
  • Are values parameterized?

ToQueryString is not a performance benchmark. It displays SQL text, but it does not reveal I/O, cardinality estimates or the actual access method. Run the query with representative parameters and inspect the database plan to understand real execution behavior.

4. Query plans and index impact

In SQL Server, an estimated or actual execution plan shows how the database engine accesses the data. A Table Scan or broad Index Scan on a large table may indicate that many rows are being examined. With a suitable index, the engine may use a narrower Index Seek and perform less work before returning the result.

Configure a composite index for the filter:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Order>()
        .HasIndex(o => new { o.Status, o.CreatedAt });
}

Create and apply a migration:

dotnet ef migrations add AddOrderStatusCreatedAtIndex
dotnet ef database update

An index does not automatically improve every query. Column order matters in a composite index. An index beginning with Status and continuing with CreatedAt is a natural fit for a query filtering on both properties. A query filtering only on CreatedAt may receive limited benefit, depending on the database engine, statistics and data distribution.

Indexes can improve reads, but they also add maintenance work to inserts, updates and deletes. Avoid indexing every column. Evaluate selectivity, workload shape, write cost and the actual execution plan together.

5. Sargable and non-sargable predicates

A predicate is commonly called sargable when the database can use an index range efficiently to evaluate it. Applying a function to the indexed column often makes that more difficult.

For example, this filter applies a date transformation to the column:

var result = await db.Orders
    .Where(o => o.CreatedAt.Date == targetDate)
    .ToListAsync(cancellationToken);

Depending on the provider and translation, this can result in a database function being applied to the column. A range predicate is usually a better shape:

var dayStart = targetDate.Date;
var nextDay = dayStart.AddDays(1);

var result = await db.Orders
    .Where(o => o.CreatedAt >= dayStart
        && o.CreatedAt < nextDay)
    .ToListAsync(cancellationToken);

String searches provide another example. A prefix search using StartsWith can be eligible for index assistance, while a suffix search using EndsWith commonly cannot use the beginning of a normal index efficiently. If suffix or flexible text search is a business requirement, consider normalized search columns, full-text search or a database-specific search feature.

Be equally careful with ToLower, ToUpper, Substring and explicit collation changes. Instead of transforming every row during the query, consider an appropriate database collation or a dedicated normalized column. Always confirm the result in the actual execution plan.

6. Why unnecessary Include increases query cost

Include is appropriate when related entities are needed, but loading complete customer entities merely to display a name may be excessive.

var orders = await db.Orders
    .Include(o => o.Customer)
    .Where(o => o.Status == "Paid")
    .ToListAsync(cancellationToken);

If the screen only needs the customer name, projection is often more appropriate:

var rows = await db.Orders
    .Where(o => o.Status == "Paid")
    .Select(o => new OrderListItem(
        o.Id,
        o.CreatedAt,
        o.TotalAmount,
        o.Customer.Name))
    .AsNoTracking()
    .ToListAsync(cancellationToken);

Projection reduces selected columns and avoids materializing full entity graphs. Multiple collection includes can multiply rows in a join and create a large intermediate result. In that situation, compare projection, filtered includes and split queries. A split query may issue multiple SQL commands, so it should also be validated through logging and measurement rather than selected automatically.

7. Common mistakes and corrections

  • Looking only at C#: Inspect SQL and the execution plan before blaming EF Core or the database.
  • Adding an index to every slow query: Consider column order, selectivity, statistics and write overhead.
  • Optimizing without a baseline: Record parameters, duration, result count and plan before changing the query.
  • Applying functions to filter columns: Prefer range predicates or normalized search columns where appropriate.
  • Using Include by default: Select the fields required by the use case with projection.
  • Logging everything in production: This can expose sensitive data and create unnecessary operational cost.
  • Treating ToQueryString as a benchmark: Use actual execution with representative parameters to assess performance.

8. Practice exercise

Compare the following three query shapes against the same dataset:

  1. Run the version using CreatedAt.Date == targetDate and save the generated SQL.
  2. Run the version using a start-of-day and next-day range.
  3. Compare an entity query with Include(o => o.Customer) against a projection that selects only the required fields.

For every test, record duration, row count, execution plan and logical reads. Then add the Status, CreatedAt composite index, apply the migration and repeat the tests. Report the results in a table similar to this:

ScenarioDurationPlanObservation
Date function predicate...ScanTransformation on the column
Range predicate...Seek or narrower scanIndex-friendly shape
Unnecessary Include...Large joinExtra columns and rows
Projection with index...SeekLess data and materialization

Conclusion

The most reliable way to solve a slow EF Core query is to measure rather than guess. Start by recording actual duration and result size. Then inspect the generated SQL with ToQueryString, review runtime behavior through EF Core logging and examine the database execution plan to understand how data is accessed.

Indexes are important, but they are not a complete solution. Sargable predicates, appropriate composite-index order, limited navigation loading and projection should be evaluated together. This evidence-based workflow helps you diagnose performance problems consistently and build database access code that remains understandable and efficient as the application grows.

Sources