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

📚 Interview question

What is a filtered index in SQL Server and when would you use one, for example for soft-deleted rows or a status column? Explain the gotcha with parameterised queries, filtered unique indexes, and the other limitations you need to know.

Covers filtered index syntax and use cases (soft delete, sparse status values, optional unique keys), why parameterised queries often cannot use them, the required SET options, filter predicate limits and filtered statistics.

Mid-Level Theory Intermediate filtered-index indexes parameterisation soft-delete sql-server unique-constraints

🎯 Key points

  • CREATE INDEX ... WHERE <simple predicate>: indexes only matching rows, smaller and cheaper to maintain
  • Fits soft delete (IsDeleted = 0), rare status values, sparse nullable columns
  • Filtered unique index enforces uniqueness only among rows matching the filter, e.g. many NULLs allowed with WHERE Email IS NOT NULL
  • Plan is compiled for any parameter value, so WHERE Status = @s cannot match WHERE Status = 1
  • Fixes: literal in the query, OPTION (RECOMPILE), or a separate query path for the filtered case
  • Predicate limits: simple comparisons combined with AND, and IN; no OR, functions, LIKE or computed columns
  • Sessions modifying the table need ANSI_NULLS, QUOTED_IDENTIFIER and related SET options ON (error 1934)
  • Filtered statistics update on whole-table modification counts, so they can go stale

⏱ 30-second answer

A filtered index is a non-clustered index with a WHERE clause: it contains only rows matching a simple predicate, so it is smaller, has more accurate statistics and costs less to maintain.

  • Typical uses: soft delete (WHERE IsDeleted = 0), a rare status such as pending jobs, sparse nullable columns, and filtered unique indexes (unique only when present, or only among active rows).
  • The gotcha: a plan is compiled to work for any parameter value, so WHERE Status = @status usually cannot use an index filtered on Status = 1. You need the literal in the query, OPTION (RECOMPILE), or a dedicated query.
  • Sessions that modify the table need the right SET options (QUOTED_IDENTIFIER, ANSI_NULLS on), or inserts fail.

Trade-off: a small, sharp index that only helps queries written to match it.

🗣 Full answer (senior)

How I would answer this in an interview

"A filtered index is a non-clustered index with a WHERE clause, so it only contains the rows that match. If 98% of a jobs table is completed and the workers only ever look for pending jobs, an index filtered on Status = 'Pending' might hold ten thousand rows instead of fifty million. It's smaller, it has its own statistics that describe just those rows, and writes to rows outside the filter don't touch it at all.

The places I use them are soft delete, where the app always queries IsDeleted = 0; rare status values like pending or failed; sparse nullable columns; and filtered unique indexes. That last one is the most useful: 'email must be unique, but only when it's provided', or 'only one active subscription per customer', which a normal unique constraint can't express because it treats all the NULLs or all the cancelled rows as clashing.

The gotcha is parameterisation. When EF Core or Dapper sends WHERE Status = @status, the optimiser compiles a plan that must be correct for every possible value of @status, so it can't pick an index that only holds Status 1. The index sits there unused. The fixes are to write the literal in the query, which EF Core does when the value is a constant in the LINQ expression, to add OPTION (RECOMPILE) for that statement, or to have a dedicated query for the hot filtered case. The other trap is SET options: any session that inserts or updates the table needs QUOTED_IDENTIFIER and ANSI_NULLS on, otherwise inserts fail with error 1934; an old job running with odd settings is how that bites. For example, at [company] we [added a filtered index for unprocessed outbox messages and the poller's reads dropped from tens of thousands of pages to single digits]. A filtered index is a precise tool: it only works for queries written to match it."


Good and bad fits

Fits Doesn't fit
A small, stable subset queried constantly (pending, active, not deleted) Filter matches most of the table
Uniqueness only among some rows Queries always parameterise the filter column
Sparse nullable columns Filter needs OR, functions, LIKE or a computed column
Hot polling queries (outbox, job queues) Apps that connect with non-default SET options

Making queries match

Query shape Uses WHERE Status = 1 filtered index?
WHERE Status = 1 (literal) Yes
WHERE Status = @s Usually no
WHERE Status = @s OPTION (RECOMPILE) Yes, the value is embedded at compile time
EF Core .Where(j => j.Status == JobStatus.Pending) (constant) Yes, EF inlines constants
EF Core .Where(j => j.Status == status) (variable) No, sent as a parameter

Production example

An outbox table held 40 million published messages and about 2,000 unpublished ones. The poller's query used an index on (PublishedAt, Id) and still read about 9,000 pages every second. A filtered index ON (Id) WHERE PublishedAt IS NULL was 30 pages; reads per poll fell to 3 and the poller's CPU share on the database dropped from 11% to under 1%.

🔍 What the interviewer is checking

Checks whether the candidate knows when filtered indexes help and the practical traps that make them silently unused or break inserts.

Green flags

  • Names soft delete, queue polling and filtered unique indexes
  • Explains why parameterised predicates cannot use them
  • Knows the SET options requirement and error 1934
  • Mentions filtered statistics staleness

Red flags

  • Thinks filtered indexes work with any query on the column
  • Uses them for filters matching most rows
  • Never checks the plan to confirm use

📚 Learn in depth

1. What gets stored

Table: 50,000,000 rows
  Status = Completed  49,980,000
  Status = Pending        12,000  ──► IX_Jobs_Pending (WHERE Status = 1): 12,000 leaf rows
  Status = Failed          8,000

Only rows matching the predicate exist in the index. An update that moves a row into or out of the filter becomes an insert or delete in the index; updates to rows that stay outside never touch it.

2. Predicate rules

Allowed: simple comparisons (=, <>, >, <, IS NULL, IS NOT NULL), IN lists, combined with AND, on columns of the table. Not allowed: OR, LIKE, functions, computed columns, user-defined types, spatial and hierarchyid columns. If you need OR, consider two indexes.

3. Why parameters break matching

The optimiser picks a plan that will be reused for later executions with other values. If @s could be 2, an index containing only Status 1 would return wrong results, so it is not a valid choice. The plan can only use a filtered index when the predicate is provably inside the filter at compile time: a literal, a value embedded by OPTION (RECOMPILE), or a predicate that implies the filter (Status = 1 AND ...).

Related: if the query's predicate is narrower than the filter on a column that is not in the index (filter Status IN (1,2), query Status = 1), SQL Server needs the column; put the filter column in INCLUDE to avoid a lookup.

4. SET options

Filtered indexes, like indexed views and indexes on computed columns, require ANSI_NULLS, ANSI_PADDING, ANSI_WARNINGS, ARITHABORT, CONCAT_NULL_YIELDS_NULL and QUOTED_IDENTIFIER ON and NUMERIC_ROUNDABORT OFF for sessions that modify the table. Modern drivers (Microsoft.Data.SqlClient) set these correctly; old ODBC jobs, sqlcmd without -I, or legacy tools may not, and their inserts fail with error 1934.

5. Filtered statistics

Each filtered index gets filtered statistics, which give much better estimates for skewed data. But the auto-update threshold is based on modifications to the whole table, not the filtered subset, so a 12,000-row filtered statistic on a 50-million-row table may rarely update. Schedule UPDATE STATISTICS for such indexes if estimates drift.

6. Filtered unique indexes

A UNIQUE constraint allows only one NULL. A filtered unique index enforces "unique among non-null" or "unique among active rows":

CREATE UNIQUE INDEX UX_Subscriptions_ActivePerCustomer
  ON dbo.Subscriptions (CustomerId) WHERE IsActive = 1;

Try it yourself

  1. Create a jobs table with 5 million rows, 0.1% pending, and a filtered index on pending rows. Compare its size with a full index in sys.dm_db_partition_stats.
  2. Run the query with a literal, then with sp_executesql and a parameter; compare plans.
  3. Add OPTION (RECOMPILE) to the parameterised version and confirm the filtered index is used.
  4. Connect with SET QUOTED_IDENTIFIER OFF and try an insert to reproduce error 1934.
  5. Run DBCC SHOW_STATISTICS on the filtered index statistics and note the rows sampled and last update.

💻 Code

A filtered index for a polling query, a filtered unique index, and the parameterisation trap.

CREATE TABLE dbo.Jobs
(
    JobId      bigint IDENTITY NOT NULL CONSTRAINT PK_Jobs PRIMARY KEY,
    Status     tinyint NOT NULL,          -- 1 = Pending, 2 = Running, 3 = Done, 4 = Failed
    DueAt      datetime2(3) NOT NULL,
    Payload    nvarchar(4000) NOT NULL
);

-- Only pending rows: tiny, and untouched by updates to finished jobs
CREATE NONCLUSTERED INDEX IX_Jobs_Pending_DueAt
    ON dbo.Jobs (DueAt)
    INCLUDE (Status)
    WHERE Status = 1;

-- Uses the filtered index: the literal proves the predicate is inside the filter
SELECT TOP (50) JobId, DueAt FROM dbo.Jobs WHERE Status = 1 AND DueAt <= SYSUTCDATETIME() ORDER BY DueAt;

-- Cannot use it: the cached plan must also work for @status = 3
EXEC sp_executesql
    N'SELECT TOP (50) JobId, DueAt FROM dbo.Jobs WHERE Status = @status AND DueAt <= SYSUTCDATETIME() ORDER BY DueAt;',
    N'@status tinyint', @status = 1;

-- Unique only among active rows: one active subscription per customer
CREATE UNIQUE NONCLUSTERED INDEX UX_Subscriptions_ActivePerCustomer
    ON dbo.Subscriptions (CustomerId)
    WHERE IsActive = 1;

In EF Core 10 a constant in the expression is inlined as a literal, so the filtered index matches; a captured variable is sent as a parameter.

namespace Jobs.Data;

using Microsoft.EntityFrameworkCore;

public enum JobStatus : byte { Pending = 1, Running = 2, Done = 3, Failed = 4 }

public sealed class Job
{
    public long JobId { get; set; }
    public JobStatus Status { get; set; }
    public DateTime DueAt { get; set; }
    public required string Payload { get; set; }
}

public sealed class JobsContext(DbContextOptions<JobsContext> options) : DbContext(options)
{
    public DbSet<Job> Jobs => Set<Job>();

    protected override void OnModelCreating(ModelBuilder b) =>
        b.Entity<Job>()
         .HasIndex(j => j.DueAt)
         .HasFilter("[Status] = 1")
         .HasDatabaseName("IX_Jobs_Pending_DueAt");
}

public sealed class JobPoller(JobsContext db)
{
    public Task<List<long>> NextBatchAsync(DateTime now, CancellationToken ct) =>
        db.Jobs
          .Where(j => j.Status == JobStatus.Pending && j.DueAt <= now)  // constant enum: inlined as 1
          .OrderBy(j => j.DueAt)
          .Select(j => j.JobId)
          .Take(50)
          .ToListAsync(ct);
}

⚠ Common mistakes

  • Mistake: Parameterising the filter column and expecting the filtered index to be used. Why it is wrong: the cached plan must be valid for every value, so the index is not eligible. Instead: a literal, OPTION (RECOMPILE), or a dedicated query for the filtered case.
  • Mistake: Using a filtered index where the filter matches most rows. Why it is wrong: it is almost as big as a full index and serves fewer queries. Instead: filter on small, stable subsets.
  • Mistake: Writing OR or a function in the filter. Why it is wrong: not supported; the CREATE fails. Instead: two filtered indexes, or a full index.
  • Mistake: Ignoring SET options. Why it is wrong: sessions with QUOTED_IDENTIFIER OFF (old jobs, some tools) get error 1934 on insert. Instead: check connection settings of every writer before deploying.
  • Mistake: Using a plain UNIQUE constraint for an optional natural key. Why it is wrong: SQL Server allows only one NULL in a unique constraint. Instead: a filtered unique index WHERE col IS NOT NULL.
  • Mistake: Trusting filtered statistics to stay current. Why it is wrong: auto-update fires on whole-table modifications. Instead: update those statistics on a schedule if estimates drift.
  • Mistake: Leaving the filter column out of the index when queries filter more narrowly than the filter. Why it is wrong: it causes a key lookup to evaluate the column. Instead: add it as an INCLUDE column.

🏛 Senior insight: trade-offs

Filtered indexes shine on queue-like and soft-delete patterns, where the hot subset is tiny and the cold data is huge. Their weakness is that they couple the index to the exact query text and to a data distribution, so I document them next to the query (or the EF Core configuration) and add a test or Query Store check that the plan still uses them.

Two things erode them over time. Query changes: a refactor that parameterises the filter value, or a predicate written with a different type (Status = '1' against a tinyint, or a bit compared with an int variable), stops the match. Data changes: if the 'rare' subset grows, for example a stuck worker leaves 5 million jobs pending, the filtered index loses its advantage and its statistics lag. I watch its row count in sys.dm_db_partition_stats as well as its usage.

Option When it fits Cost When not to
Filtered index Small hot subset, query uses literals Query must match; SET options Filter value is always a parameter
Full index with the column leading Many values queried with parameters Larger, maintained on every write Hot subset is under 1% of rows
Filtered unique index Uniqueness among some rows Same SET option rules Rule spans tables (use another approach)
Separate archive table Cold data almost never read Move job, union for history Soft-deleted rows must remain restorable in place

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions EF Core parameterising the filter value. Why: Checks the EF Core side of making filtered indexes match.
    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.

  2. When: Candidate mentions unique when present or one active row per customer. Why: Checks how filtered unique indexes relate to ordinary constraints.
    How to answer

    SQL Server constraints are rules the engine enforces on every write from every client:

    • PRIMARY KEY: unique and NOT NULL; creates a clustered index by default.
    • UNIQUE: no duplicates; backed by a unique index (allows one NULL).
    • FOREIGN KEY: the value must exist in the parent; blocks orphans; does not create an index for you.
    • CHECK: a row-level condition such as Quantity > 0 (NULL passes).
    • DEFAULT and NOT NULL: a value always exists.

    I validate in .NET for good error messages, but enforce in the database because other writers exist (scripts, jobs, other services) and race conditions slip past app checks. The cost is a little write overhead and needing to translate constraint errors into friendly responses.

🛠 Real-world problems: how you handle them

Filtered index ignored by the job poller after a refactor
Situation
A [background job platform] on Azure SQL polled a 60-million-row jobs table every second from [12] worker instances. A filtered index on pending jobs kept the poll cheap.
Signals
After a release, database CPU rose from [15]% to [55]%, Application Insights showed the poll dependency p95 going from 3 ms to 180 ms, and Query Store flagged the poll query as a top consumer.
Investigation
Query Store showed a new query id for the poll with a plan scanning `IX_Jobs_DueAt` (a full index) instead of `IX_Jobs_Pending_DueAt`. Comparing the query text with the previous one: a refactor had changed `.Where(j => j.Status == JobStatus.Pending)` to a method taking `JobStatus status`, so EF Core now sent `@status` as a parameter. `SET STATISTICS IO` confirmed [48,000] logical reads per poll versus 4 before.
Resolution
Immediate: hot-fixed the query back to a constant enum value, which EF Core inlines as a literal; the plan returned to the filtered index within minutes. Long-term: kept a generic method for other statuses but routed the pending case to a dedicated query, and added a comment linking the query to the index.
Prevention
An integration test runs the poll against a seeded SQL Server container and asserts the plan uses the filtered index (reading the showplan XML); a Query Store alert on plan changes for the poll query; a code-review checklist item for filtered indexes.

How to tell it (STAR)

**S:** At [company] our job workers polled a [60-million-row] table every second, kept cheap by a filtered index on pending jobs. **T:** After a release database CPU tripled and I had to find out why. **A:** I used Query Store to find the poll query's new plan, saw it had switched to a full index, and traced it to a refactor that turned the status constant into a parameter, so the filtered index was no longer valid for the plan. I restored the constant for the pending path and added a plan assertion test. **R:** Reads per poll went from [48,000] back to 4, CPU returned to [15]%, and the test has caught one similar regression since.

More in Indexes

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me