Why it matters: a filtered “top 25, newest first” query can take 25 s while its dedicated search index sits unused.

Context

An EF Core search filters with Where(m => matchingIds.Contains(m.Id)), where matchingIds comes from a token table matched with LIKE 'term%'. It then pages with OrderByDescending(CreatedAt).Skip().Take(25). The SQL is:

SELECT m.Id FROM Items m
WHERE m.Id IN (SELECT t.ItemId FROM SearchTokens t WHERE t.Token LIKE @pattern)
ORDER BY m.CreatedAt DESC
OFFSET @skip ROWS FETCH NEXT @take ROWS ONLY

The insight

OFFSET/FETCH sets a row goal: the optimizer only has to find 25 rows, so it costs the plan as if it can stop early.

  • It estimated that about 900 rows would yield 25 matches.
  • So it scanned the CreatedAt index newest-first and did a nested-loop semi-join seek into the token table’s primary key for every row. The token index (Token INCLUDE ItemId) went unused.
  • For a term whose matches are rare or old, this walks the whole table: about 818k logical reads on 244k rows.
  • On a small DTU tier it was disk-bound: 2.2 s CPU against 24 s elapsed.
  • The estimate came from statistics sampled at 3%, which put a rare term at thousands of matches.

The count query for the same filter has no row goal and gets the sane plan (token index seek, hash join). If the count is fast and the page is slow, suspect a row goal.

Finding it after the fact

Query Store keeps the plan, so the query does not have to be reproduced:

SELECT TOP (20) q.query_id, p.plan_id, rs.last_execution_time,
rs.max_duration / 1000.0 AS max_duration_ms,
rs.max_logical_io_reads, rs.max_rowcount,
qt.query_sql_text, p.query_plan
FROM sys.query_store_query_text qt
JOIN sys.query_store_query q ON q.query_text_id = qt.query_text_id
JOIN sys.query_store_plan p ON p.query_id = q.query_id
JOIN sys.query_store_runtime_stats rs ON rs.plan_id = p.plan_id
WHERE qt.query_sql_text LIKE N'%SearchTokens%'
ORDER BY rs.max_duration DESC;

These plans have estimates only, no actual row counts. Compare EstimatedRowsRead on the scan with max_logical_io_reads.

Fixes

  • Start from the token side: get matching IDs from the token index first, then join and sort.
  • Or remove the row goal with a hint. EF Core has no query-hint API, so tag the query and append the hint in a command interceptor:
query = query.TagWith("disable-row-goal");
// DbCommandInterceptor, in ReaderExecuting / ReaderExecutingAsync:
if (command.CommandText.StartsWith("-- disable-row-goal", StringComparison.Ordinal))
command.CommandText += "\nOPTION (USE HINT('DISABLE_OPTIMIZER_ROWGOAL'), RECOMPILE)";
  • The hint alone is not enough. The best plan depends on the term. A plan compiled for a rare term (nested-loop lookups per match) cost about 750k reads when a broad term reused it. RECOMPILE fixed that at a few milliseconds of compile time per search.
  • Trade-off: a term that matches almost everything gets slower, because the query now joins and sorts all matches instead of stopping after the first 25. Locally that was about 200 ms instead of 8 ms.
  • Skip the page query when the count is 0. A term with no matches is the worst case for the row-goal plan, because nothing ever stops the scan.

A slow first query after many writes can be a synchronous statistics rebuild, not the query itself. In Query Store the execution looks fast while the caller waited seconds. AUTO_UPDATE_STATISTICS_ASYNC ON moves the rebuild to the background.