Covers diagnosing parameter sniffing: why SSMS and the app get different plans (ARITHABORT and other SET options, local variables), finding the regressed plan in Query Store, comparing compiled and runtime parameter values, and fixes from OPTION (RECOMPILE) and OPTIMIZE FOR to plan forcing, Query Store hints, PSP optimisation and code changes.
This is almost always parameter sniffing. SQL Server compiled the plan for the first parameter values it saw, maybe a tiny customer, and now reuses it for a customer with 2 million rows. SSMS looks fast because it runs with SET ARITHABORT ON (the app's SqlClient uses OFF), so it gets a separate cache entry and compiles a fresh plan for my values.
I confirm it in Query Store: the regressed query, two plan ids, and in the plan XML ParameterCompiledValue vs ParameterRuntimeValue. Mitigate by forcing the good plan. Then fix properly: OPTION (RECOMPILE) for infrequent queries, OPTIMIZE FOR, a Query Store hint, splitting code paths, or an index that makes one plan good for everyone. SQL Server 2022's PSP optimisation helps some cases.
> "'Fast in SSMS, slow in the app' and 'slow since yesterday with no code change' together point straight at parameter sniffing. When a parameterised statement compiles, the optimiser sniffs the parameter values and builds a plan for them: seek plus key lookups for a customer with 20 orders, say. That plan is cached and reused. If it was evicted and recompiled yesterday, perhaps after a statistics update or a failover, and the first caller was unusual, everyone else now runs a plan built for the wrong data. SSMS hides it because SSMS sets ARITHABORT ON and SqlClient doesn't; SET options are part of the cache key, so my SSMS run compiles its own plan for my values. And if I paste the query with DECLARE @CustomerId int = 42, that's a local variable, which uses the density vector, so I'm not testing the same thing at all.
>
> For example, at [company] our [order history] endpoint went from [300 ms] to [28 s] one morning. I opened Query Store's Regressed Queries, found the procedure with two plans, and the new plan's XML showed ParameterCompiledValue was a customer with [11] orders, while the runtime value was one of our biggest accounts with [1.8 million]. The old plan used a hash join and scan; the new one did 1.8 million key lookups. I forced the previous plan in Query Store, which brought p95 back within [minutes], then fixed it properly by [adding a covering index so both plan shapes became cheap] and kept the forced plan off.
>
> The mistake I see is running DBCC FREEPROCCACHE on the server. It 'fixes' it until the next unlucky compile and causes a CPU storm while every plan recompiles. Parameter sniffing is a feature that usually helps; the fix is to make the plan right for the data distribution, not to keep rolling the dice."
| Step | Tool | What I'm looking for |
|---|---|---|
| 1 | Application Insights dependency telemetry | Which SQL call regressed, when it started |
| 2 | Query Store: Regressed Queries / Queries With High Variation | Same query_id, new plan_id, duration jump |
| 3 | Plan XML ParameterList |
Compiled vs runtime values |
| 4 | Histogram / row counts per value | How skewed the parameter is |
| 5 | Reproduce with sp_executesql and the app's SET options |
Same plan as the app |
| Cause | Effect |
|---|---|
ARITHABORT ON in SSMS, OFF in SqlClient |
Different plan cache entry, fresh compile |
| Local variables in a pasted query | Density-based estimate, not sniffing |
| Literal values instead of parameters | Different statement text, its own plan |
| Different database context or schema-unqualified names | Different cache entry |
| Fix | When it fits | Cost |
|---|---|---|
| Force last good plan (Query Store) | Immediate mitigation | Plan may age badly; review later |
OPTION (RECOMPILE) |
Runs < a few times per second, very skewed | Compile CPU every execution |
OPTIMIZE FOR (@p = value) / UNKNOWN |
One plan is acceptable for all | Some values get a mediocre plan |
Query Store hint (sp_query_store_set_hints) |
Can't change the code (EF Core, vendor app) | Managed outside source control |
| Split procedures / branch by value | Known 'big' vs 'small' tenants | More code |
| Covering index | Both plan shapes can become cheap | Write cost |
| PSP optimisation (2022, compat 160) | Equality predicates on skewed columns | Automatic; up to 3 plan variants |
Forcing the old plan restored p95 from 28 s to 350 ms within ten minutes. The covering index then made the 'small customer' plan cheap even for large customers (logical reads 1.9 million to 22,000), and we unforced the plan a week later after Query Store showed stable duration.
Checks whether the candidate can diagnose the most common production SQL performance incident methodically and pick a proportionate fix.
Green flags
Red flags
At compile time the optimiser can see parameter values (stored procedure parameters, sp_executesql parameters, which is what EF Core, Dapper and SqlClient send). It uses them to look up the histogram and estimate rows. The plan is then cached and reused for every value.
first call: @CustomerId = 17 (11 rows)
-> estimate 11 rows -> Index Seek + Key Lookup + Nested Loops -> cached
later call: @CustomerId = 3 (1.8M rows)
-> cache hit -> same plan -> 1.8M key lookups, tiny memory grant, spills
The opposite also happens: a plan compiled for a big value (scan, hash, big grant) makes every small lookup slow and memory-hungry.
Plans are recompiled when statistics update past the threshold, an index is rebuilt, the plan is evicted under memory pressure, the instance restarts or fails over (Azure SQL reconfigurations included), or someone runs sp_recompile. Whoever calls first decides the plan.
Plan cache entries are keyed by text and plan-affecting SET options. Check them:
SELECT pa.attribute, pa.value
FROM sys.dm_exec_cached_plans cp
CROSS APPLY sys.dm_exec_plan_attributes(cp.plan_handle) pa
WHERE pa.attribute = 'set_options';
SSMS and SqlClient differ in ARITHABORT, so you see two entries. To reproduce the app, run SET ARITHABORT OFF; in SSMS first, then call it with sp_executesql and the same parameter values.
In the plan XML (root SELECT properties in SSMS, 'Parameter List'):
<ColumnReference Column="@CustomerId"
ParameterCompiledValue="(17)" ParameterRuntimeValue="(3)" />
Runtime values appear only in actual plans. Query Store stores the compiled values with each plan.
WHERE (@p IS NULL OR col = @p) patterns with separate variants.FORCE_LAST_GOOD_PLAN, on by default for new Azure SQL servers): detects plan-choice regressions and forces the last good plan, verifying the result.None of them cover every case (ranges, multiple skewed predicates, catch-all procedures).
EF Core and Dapper send sp_executesql, so sniffing applies. You can't put OPTION (RECOMPILE) in LINQ directly; use a DbCommandInterceptor scoped by a query tag (TagWith) or a Query Store hint on the query_id. Tags also make the query easy to find in Query Store.
SET ARITHABORT OFF, and list the cache entries with sys.dm_exec_plan_attributes.sp_query_store_force_plan, and confirm with is_forced_plan.sp_query_store_set_hints @query_id, N'OPTION (RECOMPILE)' and observe compile counts.Find the regression, mitigate it, and fix it.
-- 1. Queries whose recent duration is much worse than before, with plan counts
SELECT TOP (10)
q.query_id,
qt.query_sql_text,
COUNT(DISTINCT p.plan_id) AS plan_count,
MAX(rs.avg_duration) / 1000.0 AS worst_avg_ms,
MIN(rs.avg_duration) / 1000.0 AS best_avg_ms
FROM sys.query_store_query q
JOIN sys.query_store_query_text qt ON qt.query_text_id = q.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 rs.last_execution_time > DATEADD(day, -2, SYSUTCDATETIME())
GROUP BY q.query_id, qt.query_sql_text
HAVING COUNT(DISTINCT p.plan_id) > 1
ORDER BY MAX(rs.avg_duration) / NULLIF(MIN(rs.avg_duration), 0) DESC;
-- 2. Mitigate: force the previously good plan (reversible)
EXEC sys.sp_query_store_force_plan @query_id = 4711, @plan_id = 902;
-- Or, for a query you can't edit (EF Core), attach a hint to it
EXEC sys.sp_query_store_set_hints @query_id = 4711, @query_hints = N'OPTION (RECOMPILE)';
-- 3. Code-level fixes in a procedure
CREATE OR ALTER PROCEDURE dbo.GetOrderHistory @CustomerId int
AS
SELECT OrderId, OrderDate, Total
FROM dbo.Orders
WHERE CustomerId = @CustomerId
ORDER BY OrderDate DESC
OPTION (RECOMPILE); -- fine at tens of calls per second; not at thousands
For EF Core, tag the query so you can find it and target it with an interceptor:
namespace Shop.Data;
using System.Data.Common;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
public sealed class RecompileInterceptor : DbCommandInterceptor
{
public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(
DbCommand command, CommandEventData eventData,
InterceptionResult<DbDataReader> result, CancellationToken ct = default)
{
// Only queries explicitly tagged by the developer get the hint
if (command.CommandText.Contains("-- order-history", StringComparison.Ordinal))
command.CommandText += " OPTION (RECOMPILE)";
return base.ReaderExecutingAsync(command, eventData, result, ct);
}
}
public sealed class OrderHistoryQuery(ShopDbContext db)
{
public Task<List<OrderRow>> RunAsync(int customerId, CancellationToken ct) =>
db.Orders
.TagWith("order-history")
.Where(o => o.CustomerId == customerId)
.OrderByDescending(o => o.OrderDate)
.Select(o => new OrderRow(o.OrderId, o.OrderDate, o.Total))
.ToListAsync(ct);
}
public sealed record OrderRow(long OrderId, DateTime OrderDate, decimal Total);
DBCC FREEPROCCACHE on the server to fix it. Why it is wrong: It flushes every plan, spikes CPU and the bad plan may come back on the next unlucky compile. Instead: Force the good plan or evict the single plan with DBCC FREEPROCCACHE (plan_handle).ARITHABORT ON gives a separate cache entry and a fresh plan. Instead: SET ARITHABORT OFF and call sp_executesql with the app's values.OPTION (RECOMPILE) on a query that runs thousands of times a second. Why it is wrong: Every call pays compile CPU (milliseconds each, far more for complex queries) and the plan isn't kept in the cache for DMV analysis. Instead: Use plan forcing, OPTIMIZE FOR, or a better index; keep RECOMPILE for infrequent, highly skewed queries.ARITHABORT ON in the app 'to match SSMS'. Why it is wrong: It changes nothing about sniffing; it just moves which session gets which plan. Instead: Fix the plan's sensitivity..Where(o => customerId == null || o.CustomerId == customerId) for search screens. Why it is wrong: One cached plan has to serve 'all rows' and 'one customer', so it is wrong for one of them. Instead: Compose the IQueryable conditionally so each filter combination is its own statement, or rely on OPPO only after testing on compat 170.TagWith (or TagWithCallSite) on important queries so the comment appears in the SQL text.OPTIMIZE FOR UNKNOWN as a universal fix. Why it is wrong: It plans for the average from the density vector, which is wrong for both tails of skewed data. Instead: Use it only when an average plan is measurably acceptable for all values.Parameter sniffing is the default behaviour and usually a win; the problem is skew combined with plan shapes that are very sensitive to row counts. The most durable fix is often to make the cheap plan safe for every value (a covering index removes the key lookups that made the small plan dangerous) rather than adding a hint.
Every fix is a trade-off between compile CPU, plan quality and visibility. RECOMPILE buys a perfect plan per call at the price of CPU and lost plan-cache history; forcing buys stability at the price of a plan that ages; hints in Query Store buy speed of mitigation at the price of living outside source control. I want mitigation fast, visible and reversible, recorded in the incident notes, with a follow-up ticket for the real fix. On Azure SQL, automatic plan correction may already have acted; check sys.dm_db_tuning_recommendations, Query Store and Azure SQL Intelligent Insights before acting, and keep an Application Insights alert on dependency p95 per query tag.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Force plan in Query Store | Incident mitigation | Needs review; can fail after schema change | Permanent fix without monitoring |
OPTION (RECOMPILE) |
Low frequency, high skew | Compile CPU per call; no cached plan stats | Hot paths |
OPTIMIZE FOR UNKNOWN |
Average plan is acceptable to all | Mediocre for extremes | Highly skewed data |
| Query Store hints | ORM or vendor SQL | Lives outside source control | When you can fix the code |
| Index change | Plan shapes can converge | Write cost | Write-heavy tables with many indexes |
| Separate statements per filter combination | Search screens, catch-all queries | More plans in cache | Hundreds of combinations |
In .NET a string becomes an nvarchar parameter by default (ADO.NET AddWithValue, Dapper sends nvarchar(4000), EF Core when the property is Unicode). nvarchar has higher data type precedence than varchar, so SQL Server converts the column, not the parameter: CONVERT_IMPLICIT(nvarchar, AccountNo). With a SQL collation that means a scan of every row; with a Windows collation you may get a dynamic seek, but with worse estimates. SSMS was fast because the literal there was varchar.
Diagnose with the plan warning ('Type conversion may affect seek plan'), Query Store and a plan cache search. Fix at the mapping layer: EF Core IsUnicode(false)/HasColumnType("varchar(20)"), Dapper DbString { IsAnsi = true }, ADO.NET SqlDbType.VarChar with a size. Trade-off: changing the column to nvarchar also works but doubles storage.
First I confirm it's the release: Application Insights with the deployment annotation, comparing p95 by operation before and after. Then I check where the time goes: in the slow operation, are SQL dependencies longer (a worse query) or more numerous (N+1)? Next, Query Store on Azure SQL: Regressed Queries and Top Resource Consuming Queries show which statement got worse and whether its plan changed. I map that SQL back to code with TagWith comments (or the text), then read the LINQ diff: typical culprits are a non-sargable predicate, a new collection Include, a lost projection, or a parameter type change. I mitigate first: roll back or flag the change off; force the old plan only if it's purely a plan regression. Then fix the LINQ, verify the plan, and add query tags, a perf test and Query Store alerts. The trade-off: rollback is fastest, but only the root cause stops it recurring.
At compatibility level 160 (SQL Server 2022, Azure SQL), when a parameterised query has an equality predicate on a column whose histogram shows heavy skew, the optimiser compiles a dispatcher plan instead of one plan. At run time the dispatcher looks up the parameter value's cardinality in the statistics, puts it in a low, medium or high bucket, and runs the matching query variant, each with its own cached plan. It considers up to three such predicates. It does not handle range predicates, catch-all @p IS NULL OR col = @p queries (SQL Server 2025's Optional Parameter Plan Optimisation, OPPO, targets those), skew the statistics can't see, or estimation problems that aren't about the parameter.
How to tell it (STAR)
**S:** Our order history API went from [300 ms] to [28 seconds] overnight with no deployment, and only some customers were timing out. **T:** I was on call and needed to restore service, then stop it recurring. **A:** Query Store showed a new plan right after a statistics update, compiled for a customer with 11 orders. SSMS looked fine because of the ARITHABORT difference, so I reproduced with the app's settings and saw 1.8 million key lookups. I forced the old plan to stop the bleeding, then added a covering index so one plan was cheap for every customer, and unforced the plan a week later. **R:** p95 was back under [350 ms] within ten minutes, logical reads for the big accounts fell from [1.9 million] to [22,000], and we added skewed tenants to our load tests.
Last updated 23 Nov 2026.