📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you manage indexes from the EF Core side? Explain HasIndex and the [Index] attribute, unique, filtered and descending indexes and included columns on SQL Server, and which LINQ patterns stop SQL Server using an index even though the query translates.

Covers declaring indexes in EF Core (HasIndex, [Index], IsUnique, HasFilter, IsDescending, IncludeProperties), how they reach SQL Server through migrations, and the non-sargable LINQ patterns (ToLower, Contains, date parts, implicit conversions) that defeat them.

Mid-Level Theory Intermediate ef-core indexes migrations query-performance sargability sql-server

🎯 Key points

  • Indexes are part of the model: HasIndex / [Index] become CREATE INDEX in a migration
  • EF Core creates FK indexes by convention; everything else is your job
  • SQL Server options: IsUnique, HasFilter, IsDescending, IncludeProperties (covering index)
  • Design indexes from the real query shapes: equality columns first, then range / sort
  • Non-sargable: ToLower()/ToUpper(), Contains -> LIKE '%x%', .Year / date parts, arithmetic on the column
  • Implicit conversion: nvarchar parameter against a varchar column; fix with IsUnicode(false)
  • Filtered indexes need a literal predicate; parameterised filters usually cannot use them
  • Verify with the actual plan and Query Store; review sys.dm_db_index_usage_stats for unused indexes

⏱ 30-second answer

In EF Core, indexes are part of the model: HasIndex(...) or the [Index] attribute generate CREATE INDEX in a migration, so the schema stays in source control. EF Core adds indexes for foreign keys by convention; every other index is your decision. On SQL Server you can make them unique, filtered (HasFilter), descending (IsDescending) and covering (IncludeProperties). The other half is writing LINQ that can use them: Name.ToLower() == x, Contains (becomes LIKE '%x%'), o.CreatedAt.Year == 2026 and arithmetic on columns are non-sargable, so SQL Server scans; an nvarchar parameter against a varchar column causes an implicit conversion. I verify with the actual execution plan and Query Store. The trade-off: every index speeds some reads and slows every write.

🗣 Full answer (senior)

How I would answer this in an interview

"I treat indexes as part of the EF Core model. I declare them in the entity configuration with HasIndex, or the [Index] attribute for simple cases, and the migration creates them. That way the index is reviewed with the query that needs it and every environment gets the same schema. EF Core already creates an index for each foreign key by convention, which covers joins, but the indexes that matter for performance, the ones matching your WHERE and ORDER BY, are your job.

On SQL Server, EF Core exposes the useful options. IsUnique() enforces a business rule like one active email per tenant. HasFilter(\"[DeletedAt] IS NULL\") gives a smaller filtered index, which is how you do a unique index that ignores soft-deleted rows. IncludeProperties adds non-key columns so a projection is covered without key lookups, and IsDescending helps queries that sort newest first on a composite key. I design them from the actual query: equality columns first, then the range or sort column, then included columns for what the Select returns.

The part people miss is that LINQ can translate and still defeat the index. c.Email.ToLower() == email becomes LOWER([c].[Email]) = @email, which SQL Server can't seek on, and with the default case-insensitive collation the ToLower was never needed. Contains(term) becomes LIKE '%term%', which always scans. o.CreatedAt.Year == 2026 becomes DATEPART(year, ...), and the fix is a range. A mapping mismatch, like a varchar column EF Core thinks is Unicode, makes EF Core send an nvarchar parameter and SQL Server converts the column on every row. The mistake I see is adding indexes without checking the plan. I always confirm a seek in the actual plan and watch Query Store after release."


Index options in EF Core on SQL Server

API SQL Use for
HasIndex(e => e.Email) / [Index(nameof(Email))] CREATE INDEX Lookups and joins
.IsUnique() CREATE UNIQUE INDEX Business keys
.HasFilter("[DeletedAt] IS NULL") ... WHERE [DeletedAt] IS NULL Soft delete, sparse status values
.IsDescending(false, true) (TenantId ASC, CreatedAt DESC) Newest-first lists
.IncludeProperties(e => new { e.Name, e.Total }) INCLUDE (Name, Total) Covering a projection
.HasDatabaseName("IX_...") Index name Stable names for scripts and monitoring

LINQ that translates but cannot seek

LINQ SQL Sargable fix
c.Email.ToLower() == email LOWER([c].[Email]) = @email Compare directly (case-insensitive collation) or store a normalised column
p.Name.Contains(term) LIKE N'%' + @term + N'%' StartsWith (LIKE 'x%') or full-text search
o.CreatedAt.Year == 2026 DATEPART(year, [o].[CreatedAt]) = 2026 o.CreatedAt >= start && o.CreatedAt < end
o.Total * 1.1m > 100 Arithmetic on the column Move the arithmetic to the parameter
varchar column mapped as Unicode CONVERT_IMPLICIT on the column .IsUnicode(false) or HasColumnType("varchar(50)")

Production example

A login lookup [in a system I worked on] used Email.ToLower() == input against 3 million users and scanned the table: about 250 ms and 40,000 logical reads per login. Removing ToLower() (the collation was already case-insensitive) and adding a unique filtered index on Email turned it into a seek: under 2 ms and 4 reads.

🔍 What the interviewer is checking

Checks that the candidate keeps indexes in the EF Core model, knows the SQL Server index options EF Core exposes, and can spot LINQ that translates but cannot use an index.

Green flags

  • Declares indexes with HasIndex and knows FK indexes are created by convention
  • Mentions filtered, descending and included-column indexes
  • Names concrete non-sargable patterns and their rewrites
  • Mentions implicit conversion from Unicode mismatches
  • Verifies with the actual plan and Query Store

Red flags

  • Thinks EF Core or SQL Server creates the needed indexes automatically
  • Uses ToLower() for case-insensitive comparisons by default
  • Adds indexes without considering write cost or checking the plan

📚 Learn in depth

1. How an EF Core index reaches the database

Entity configuration          migration                     SQL Server
HasIndex(...).IsUnique()  ->  CreateIndex(name, table,  ->  CREATE UNIQUE INDEX
  .HasFilter(...)               columns, unique,              [IX_Users_Email]
                                filter)                       ON [Users]([Email])
                                                              WHERE [DeletedAt] IS NULL

The index is stored in the model snapshot, so removing it from the configuration generates a DropIndex. Index names follow IX_{Table}_{Columns} unless you set HasDatabaseName.

2. Why a function on the column defeats a seek

A B-tree index is sorted by the column's stored value. A seek works only when SQL Server can compute a range of keys from the predicate. LOWER([Email]) = @p asks about a value that isn't stored, so SQL Server must compute LOWER for every row: a scan. The same applies to DATEPART, CONVERT and arithmetic. Predicates that can use a seek are called sargable (Search ARGument ABLE).

3. Collation and case

SQL Server and Azure SQL databases typically use a case-insensitive collation such as SQL_Latin1_General_CP1_CI_AS, so = already ignores case. ToLower() is then pure cost. If you do need case-insensitive search on a case-sensitive column, add a computed, persisted, normalised column with its own index.

4. Implicit conversions

EF Core maps string to nvarchar by default. If the real column is varchar but the model doesn't say so, EF Core sends @p nvarchar(4000). Because nvarchar has higher data type precedence, SQL Server converts the column (CONVERT_IMPLICIT), and depending on collation that can turn a seek into a scan. The plan shows a warning on the SELECT operator. Fix the model with IsUnicode(false) and a max length so parameters match.

5. Designing the index from the query

WHERE TenantId = @t AND Status = @s AND CreatedAt >= @from
ORDER BY CreatedAt DESC
SELECT Id, Total, CustomerName

-> key: (TenantId, Status, CreatedAt DESC)  INCLUDE (Total, CustomerName)

Equality columns first, then the range or sort column; include what the projection returns to avoid key lookups. Every index costs write time, storage and log, so check sys.dm_db_index_usage_stats for unused ones.

6. Verifying

  • Print the SQL with ToQueryString() and run it with the actual plan: look for Index Seek vs Scan, Key Lookup and conversion warnings.
  • Query Store shows plan regressions after a release; Azure SQL's automatic tuning recommendations suggest missing indexes, but review them before applying.

Try it yourself

  1. Create a Users table with 1 million rows, query with and without ToLower(), and compare logical reads with SET STATISTICS IO ON.
  2. Map a varchar column without IsUnicode(false), run a lookup and find the CONVERT_IMPLICIT warning in the plan.
  3. Add a filtered unique index for soft delete and confirm two deleted rows with the same email are allowed.
  4. Rewrite a .Year == 2026 filter as a range and compare plans.
  5. Add IncludeProperties for a projection and watch the Key Lookup disappear.

💻 Code

Index configuration in EF Core 10 and the sargable rewrites of common queries.

namespace Shop.Data;

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

public sealed class Order
{
    public int Id { get; set; }
    public int TenantId { get; set; }
    public OrderStatus Status { get; set; }
    public DateTime CreatedAt { get; set; }
    public decimal Total { get; set; }
    public required string CustomerName { get; set; }
    public required string Reference { get; set; } // varchar(20) in the database
}

public enum OrderStatus { Open, Paid, Shipped, Cancelled }

public sealed class OrderConfiguration : IEntityTypeConfiguration<Order>
{
    public void Configure(EntityTypeBuilder<Order> b)
    {
        b.Property(o => o.CustomerName).HasMaxLength(200);
        b.Property(o => o.Reference).HasMaxLength(20).IsUnicode(false); // avoids CONVERT_IMPLICIT

        // Matches: WHERE TenantId = @t AND Status = @s ORDER BY CreatedAt DESC, projecting Total and CustomerName.
        b.HasIndex(o => new { o.TenantId, o.Status, o.CreatedAt })
            .IsDescending(false, false, true)
            .IncludeProperties(o => new { o.Total, o.CustomerName })
            .HasDatabaseName("IX_Orders_Tenant_Status_CreatedAt");

        // Business key, unique per tenant.
        b.HasIndex(o => new { o.TenantId, o.Reference }).IsUnique();
    }
}

public sealed class OrderSearch(ShopDbContext db)
{
    // Non-sargable: DATEPART on the column.
    // db.Orders.Where(o => o.CreatedAt.Year == year)

    // Sargable: a half-open range on the stored value.
    public Task<List<int>> InYearAsync(int tenantId, int year, CancellationToken ct)
    {
        var from = new DateTime(year, 1, 1);
        var to = from.AddYears(1);
        return db.Orders
            .Where(o => o.TenantId == tenantId && o.CreatedAt >= from && o.CreatedAt < to)
            .Select(o => o.Id)
            .ToListAsync(ct);
    }

    // Non-sargable: o.Reference.ToLower() == reference.ToLower(); the CI collation already ignores case.
    public Task<Order?> ByReferenceAsync(int tenantId, string reference, CancellationToken ct) =>
        db.Orders.FirstOrDefaultAsync(o => o.TenantId == tenantId && o.Reference == reference, ct);
}
-- Generated by the migration
CREATE INDEX [IX_Orders_Tenant_Status_CreatedAt]
    ON [Orders] ([TenantId], [Status], [CreatedAt] DESC)
    INCLUDE ([Total], [CustomerName]);
CREATE UNIQUE INDEX [IX_Orders_TenantId_Reference] ON [Orders] ([TenantId], [Reference]);

⚠ Common mistakes

  • Mistake: Calling ToLower() on both sides for case-insensitive matching. Why it is wrong: it wraps the column in LOWER(), forcing a scan, and the default collation is already case-insensitive. Instead: compare directly, or add a normalised persisted column with an index.
  • Mistake: Using Contains for search on a large table. Why it is wrong: LIKE '%x%' cannot seek. Instead: use StartsWith where it fits, or SQL Server full-text search or Azure AI Search.
  • Mistake: Filtering on .Year, .Date or .Month. Why it is wrong: the column is wrapped in a date function. Instead: filter on a half-open range.
  • Mistake: Leaving varchar columns mapped as Unicode. Why it is wrong: EF Core sends nvarchar parameters and SQL Server converts the column. Instead: IsUnicode(false) with a max length.
  • Mistake: Creating indexes by hand in the database. Why it is wrong: the model snapshot doesn't know them, so environments drift and a later migration can conflict. Instead: declare them in the EF Core model, or manage them deliberately in a separate, documented script.
  • Mistake: Adding an index per column. Why it is wrong: single-column indexes rarely match multi-column predicates and every index slows writes. Instead: design composite indexes from the real query shapes and review usage stats.
  • Mistake: Applying every missing-index suggestion. Why it is wrong: suggestions overlap and ignore write cost. Instead: consolidate them and test with the actual plan.

🏛 Senior insight: trade-offs

Indexes belong with the queries that need them, so I want them in the EF Core model and in the same pull request as the query. The deeper skill is reading the generated SQL for sargability: EF Core will happily translate a predicate that SQL Server cannot seek on. I keep a short list of patterns to flag in review (ToLower, Contains, date parts, arithmetic on columns, Unicode mismatches) and check new hot queries in the actual plan before merging. After release, Query Store tells me if a plan regressed.

Two things people forget. First, filtered indexes and parameters: SQL Server only uses a filtered index if it can prove at compile time that the query's predicate falls inside the filter. A global query filter like DeletedAt == null becomes a literal IS NULL and matches, but Status == status becomes @status and usually does not, because the cached plan has to work for any value; use a constant (EF.Constant in EF Core 8+) where it matters. Second, indexes have a running cost: every insert and update maintains them, so I review sys.dm_db_index_usage_stats (seeks and scans versus updates) and drop indexes nobody reads. Fragmentation matters less on modern SSD storage than it used to, but random GUID keys still cause page splits and low page density, so I watch sys.dm_db_index_physical_stats and prefer sequential keys. Azure SQL automatic tuning can suggest or create indexes; I let it recommend, then review and move the good ones into the EF Core model so the snapshot stays the source of truth.

Option When it fits Cost When not to
Composite index with INCLUDE Hot, stable query shapes Write overhead, storage Rarely run queries
Filtered index Sparse values, soft delete, unique among active rows Must match the filter predicate; parameterised filters may not use it Predicates that vary
Persisted computed column + index Normalised search keys Extra column and write cost When a direct comparison already works
Full-text or Azure AI Search Free-text Contains search Separate infrastructure Exact-match lookups

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions ToLower() or date functions in a WHERE clause Why: Checks they can explain in detail why a function on a column makes a translated query slow
    How to answer

    Because the generated SQL applies the function to every row (LOWER([c].[Email]) = @email, DATEPART(year, [o].[PlacedAt]) = 2026), so SQL Server can't seek an index on the raw column. It scans the whole index instead, which costs CPU and reads proportional to the table and gets worse as data grows. Fixes: express dates as a half-open range (WHERE [o].[PlacedAt] >= @start AND [o].[PlacedAt] < @end); rely on the database's case-insensitive collation instead of ToLower(), so no function is needed at all; or index a persisted computed column when you really need the derived value.

  2. When: Candidate mentions string length or column types Why: Checks they know nvarchar(max) cannot be an index key and why max lengths matter
    How to answer

    An nvarchar(max) column cannot be a key column of a B-tree index (clustered or non-clustered); it can only sit in INCLUDE or a full-text index, so a lookup on it scans. Values that do not fit in the row (over 8,000 bytes) move to LOB pages, so reading them costs extra I/O, and online index operations were historically restricted. The optimiser also estimates row size from the declared type, assuming a max column is about half-full of a large value, so sorts and hash joins get oversized memory grants that waste memory and reduce concurrency. EF Core maps an unconfigured string to nvarchar(max), so the fix is to give strings realistic lengths with HasMaxLength, a convention, or [MaxLength], and keep max for genuine documents.

  3. When: Candidate mentions HasFilter for soft delete or status Why: Checks they know filtered indexes need a predicate the optimiser can match at compile time
    How to answer

    SQL Server uses a filtered index only if it can prove at compile time that the query's predicate implies the index filter. It fails when: the filter value is a parameter (WHERE Status = @status), because the cached plan must work for any value; the predicate is written differently from the filter (an OR, a function, a different column expression) so the optimiser can't match it; the index doesn't cover the query and a scan looks cheaper on the cost estimate; or statistics on the filtered index are stale (they update on modifications to the filtered rows only, so they can lag). In EF Core, keep global query filters as simple literals (DeletedAt == null becomes IS NULL), use EF.Constant (EF Core 8+) where a fixed value matters, include the projected columns, and verify the seek in the actual plan.

🛠 Real-world problems: how you handle them

Login lookups scanning 3 million users
Situation
An identity service on ASP.NET Core and EF Core against Azure SQL [General Purpose, 8 vCores] serving [about 50 logins per second] at peak.
Signals
Login p95 rose to [about 300 ms]; Azure SQL CPU at [70-80%] during the morning peak; Query Store showed the user lookup as the top query by CPU; no errors.
Investigation
Took the query from Query Store and matched it to the code with a `TagWith` comment. The actual plan showed a Clustered Index Scan with `LOWER([u].[Email])` in the predicate and about 40,000 logical reads per execution. Checked the database collation: case-insensitive, so the `ToLower()` had no purpose.
Resolution
Removed `ToLower()` from the LINQ and added a unique filtered index on `Email` (excluding soft-deleted users) through a migration, created online. The plan became an Index Seek with 4 logical reads.
Prevention
Added non-sargable patterns to the code review checklist; a Query Store regression alert; documented the collation assumption in an ADR; an integration test that asserts the user lookup plan uses the index (via `SET SHOWPLAN_XML` in a test database).

How to tell it (STAR)

**S:** Our login endpoint in [the identity service] slowed to around [300 ms] at p95 and Azure SQL CPU was high every morning. **T:** I was asked to bring login latency back under [50 ms] without scaling the database. **A:** Query Store showed the user lookup as the top CPU consumer. The actual plan was a full scan because the LINQ called ToLower on the email, which became LOWER on the column, and the collation was already case-insensitive. I removed the ToLower, added a unique filtered index through an EF Core migration, and added the pattern to our review checklist. **R:** The lookup went from about [40,000] logical reads to [4], login p95 dropped to around [20 ms], and database CPU at peak fell by roughly [a third].

↩ Usually asked after

More in EF Core Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me