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

📚 Interview question

Tell me about a time a query was fast when you ran it in SSMS but slow when the application ran it. How did you work out why, what was the actual cause, and how did you fix it so it stayed fixed?

A STAR story for the fast-in-SSMS, slow-in-app problem: different SET options and cached plans, parameter sniffing, implicit conversions, Query Store evidence and lasting fixes.

Mid-Level RealWorldScenario Intermediate ef-core parameter-sniffing query-store real-world sql-server star-story

🎯 Key points

  • SSMS and the app get separate plan cache entries because SET options differ (ARITHABORT most often; ANSI_NULLS, QUOTED_IDENTIFIER, DATEFORMAT also form the key)
  • Reproduced the app's plan: same SET options, sp_executesql with the app's parameter types, or Query Store's plan
  • Cause named: parameter sniffing on skewed data, or implicit conversion (nvarchar vs varchar)
  • Query Store: duration jump, several plans for one query id, regressed-queries report
  • Mitigation: force the good plan; structural fix: covering index or query change, then unforce
  • Considered workload: frequency, concurrency and data growth decide index vs RECOMPILE vs separate queries
  • Measured before and after with Application Insights dependency p95 and Query Store reads/CPU

⏱ 30-second answer

The trick is that SSMS and the app aren't running the same plan. SSMS sets ARITHABORT ON by default and ADO.NET doesn't, so they get separate plan cache entries, and SSMS often compiles a fresh plan with your literal values. The app was reusing a plan sniffed for [a small customer], which was terrible for [a large one]. I proved it in Query Store: one query, two plans, duration jump on [date]. I forced the good plan to stop the bleeding, then fixed it properly with [a better index / OPTIMIZE FOR UNKNOWN / correct parameter types]. Result: [12 s to 150 ms]. The trade-off: OPTION (RECOMPILE) fixes sniffing reliably but costs CPU on every call, so I use it only for infrequent, skewed queries.

🗣 Full answer (senior)

How I would answer this in an interview

"At [company], support reported that the [order history] page timed out for [some large customers]. A developer pasted the query into SSMS and it ran in under a second, so it was blamed on the network. I wasn't convinced, because the app's telemetry showed the SQL dependency itself taking [20 seconds].

I knew SSMS and ADO.NET use different SET options, mainly ARITHABORT, so they get separate cached plans, and SSMS was also running it with literal values instead of parameters. In Query Store the query had two plans: a seek with nested loops that was perfect for small customers, and a hash join that suited big ones. The cached app plan had been compiled for a customer with [12] orders after a [statistics update / restart], and it was being reused for customers with [200,000]. That's parameter sniffing.

I forced the hash-join plan in Query Store as a quick mitigation, and the timeouts stopped within minutes. Then I fixed the cause: the plan only needed nested loops because the index didn't cover the query, so I added a covering index; with that, one plan was good for every customer size, and I unforced the plan. I also added a Query Store regressed-queries check to our weekly review. P95 for that endpoint went from [8 s] to [150 ms]. What I learnt is to never trust an SSMS timing until you run it the way the app does."


Why the same query behaves differently

Difference Effect
SET ARITHABORT (ON in SSMS, OFF in ADO.NET) Different plan cache key, so a different plan
Literals in SSMS vs parameters in app SSMS compiles for those exact values
Parameter type (nvarchar from .NET vs varchar column) CONVERT_IMPLICIT, index scan
Cold vs warm cache First run in app reads from disk

Fix options for parameter sniffing

Option When it fits Cost
Better index Plan choice flips because the index doesn't cover Write overhead
Force plan in Query Store Quick mitigation; known good plan Can silently stop applying after schema changes
OPTION (RECOMPILE) Infrequent, highly skewed query Compile CPU every execution
OPTIMIZE FOR UNKNOWN Want an average plan Average can be bad for both ends
SQL Server 2022 PSP optimisation Compatibility level 160; equality predicates Only some patterns; check it's kicking in

Production example

Template: [order history] endpoint, p95 [8 s] for [large customers]; Query Store showed [2] plans; forced plan in [10] min; covering index made one plan good for all; p95 [150 ms], logical reads down [95%].

🔍 What the interviewer is checking

Checks whether you understand plan caching and parameter sniffing well enough to explain why SSMS misleads, prove the cause and fix it durably.

Green flags

  • Mentions ARITHABORT / separate cache entries
  • Uses Query Store or actual plans as evidence
  • Mitigates with plan forcing, then fixes structurally
  • Gives before/after numbers

Red flags

  • Blames the network or the app without evidence
  • FREEPROCCACHE or RECOMPILE everywhere
  • Can't explain why the plan changed

📚 Learn in depth

1. What the interviewer is really assessing

This is a classic mid-level SQL story. It checks whether you know that plans are cached and reused, that SET options are part of the cache key, and that you go from a hunch to evidence (Query Store, actual execution plans) before changing things. Bonus marks for not stopping at a forced plan.

2. The mechanism

First execution: @CustomerId = 42 (12 orders)
  -> optimiser sniffs 42, estimates 12 rows -> nested loops + key lookups
  -> plan cached
Later: @CustomerId = 7 (200,000 orders)
  -> same cached plan reused -> 200,000 key lookups -> 20 s

The cache key includes the query text, the database and SET options such as ARITHABORT, ANSI_NULLS and QUOTED_IDENTIFIER. SSMS runs with ARITHABORT ON, the .NET SqlClient with OFF, so SSMS compiles its own plan for whatever values you typed.

3. Getting the app's plan

  • Query Store: Top Resource Consuming and Regressed Queries reports; the plan summary shows multiple plans and when each was used.
  • sys.dm_exec_query_stats with sys.dm_exec_query_plan for the cached plan.
  • In SSMS, SET ARITHABORT OFF and run with sp_executesql and the same parameter types the app sends; EF Core logging (LogTo or EnableSensitiveDataLogging in development only) shows them.

4. Frameworks for telling it

STAR works well; the twist ("SSMS lies") is the hook, so put it in the first sentence of the Action. For a short CAR version: context (timeouts for big customers), action (Query Store, two plans, index), result (numbers).

5. How it is scored

Weak: "we added an index". Good: names parameter sniffing. Strong: explains ARITHABORT, proves it in Query Store, mitigates with plan forcing. Excellent: replaces the forced plan with a structural fix and adds monitoring.

6. Adapting the story

The same story answers "a time you challenged an assumption" (it wasn't the network) and "a time you used data to solve a problem". For a non-technical audience: "The database reused a shortcut planned for small customers on our biggest ones; I gave it an index so one approach works for everyone."

Try it yourself

  1. Create a table with heavily skewed data (one customer with 100,000 rows, others with 10).
  2. Run a parameterised query first with a small customer, then a large one, and compare actual plans.
  3. Toggle SET ARITHABORT and watch a new plan appear in sys.dm_exec_cached_plans.
  4. Enable Query Store, force a plan, then add a covering index and unforce it.
  5. Write and time your STAR version.

💻 Code

Reproducing the app's plan, the mitigation and the structural fix.

-- Reproduce what the app runs (ADO.NET defaults, parameterised)
SET ARITHABORT OFF;
EXEC sp_executesql
    N'SELECT o.Id, o.CreatedAt, o.Total FROM dbo.Orders o WHERE o.CustomerId = @p0 ORDER BY o.CreatedAt DESC',
    N'@p0 int', @p0 = 7;

-- Mitigation: force the known-good plan (ids from Query Store)
EXEC sys.sp_query_store_force_plan @query_id = 4711, @plan_id = 9;

-- Structural fix: covering index so one plan suits every customer size, then unforce
CREATE INDEX IX_Orders_CustomerId_CreatedAt ON dbo.Orders (CustomerId, CreatedAt DESC) INCLUDE (Total);
EXEC sys.sp_query_store_unforce_plan @query_id = 4711, @plan_id = 9;
namespace Orders.Data;

// The related trap: a varchar column mapped as nvarchar makes SQL convert every row.
public sealed class CustomerConfiguration : IEntityTypeConfiguration<Customer>
{
    public void Configure(EntityTypeBuilder<Customer> b) =>
        b.Property(c => c.AccountNumber).HasColumnType("varchar(20)").IsUnicode(false);
}
STAR template
S: [Endpoint] timed out for [which users]; SSMS showed [<1 s].
T: I [investigated / was asked to] find why.
A: Knew SSMS uses different SET options; Query Store showed [N plans]; cause [sniffing / implicit conversion];
   forced plan, then [index / types / hint]; added [monitoring].
R: p95 [X s -> Y ms]; [reads / CPU] down [N%].

Illustrative only: order history, plan sniffed for a 12-order customer reused for 200k; covering index; 8 s -> 150 ms.

⚠ Common mistakes

  • Mistake: Concluding "it's the network" because SSMS is fast. Why it is wrong: SSMS compiles its own plan with different SET options and literal values. Instead: Reproduce the app's plan.
  • Mistake: Clearing the whole plan cache (DBCC FREEPROCCACHE). Why it is wrong: Every cached plan is discarded, so the next call of each query compiles again; on a busy server that is a CPU spike proportional to how many distinct queries run, and the bad plan can be sniffed again. Instead: Evict one plan (DBCC FREEPROCCACHE(plan_handle)) or force a good one in Query Store.
  • Mistake: Adding OPTION (RECOMPILE) everywhere. Why it is wrong: Compile CPU on every call. Instead: Use it for infrequent skewed queries only.
  • Mistake: Leaving a forced plan as the permanent fix. Why it is wrong: It can stop applying after schema changes and hides the cause. Instead: Fix the index or query, then unforce.
  • Mistake: Ignoring parameter types from EF Core. Why it is wrong: nvarchar against varchar causes scans. Instead: Map column types explicitly.
  • Mistake: Treating it as a one-user problem. Why it is wrong: A bad cached plan is shared, so every concurrent caller of that query gets it; under load the slow executions hold locks, memory grants and connections, and pool exhaustion follows. Instead: Describe the blast radius and why it mattered under concurrency.
  • Mistake: Rambling about plan operators. Why it is wrong: Interviewers want the cause and outcome. Instead: One sentence on the two plans.
  • Mistake: No result, or "we" throughout. Why it is wrong: Impact and your contribution are unclear. Instead: Before/after duration and reads; say what you checked and changed.

🏛 Senior insight: trade-offs

What lifts this answer is challenging the obvious conclusion with evidence and not stopping at the mitigation. Explain why the plan flipped (estimate-driven choice between seek-plus-lookups and a scan or hash join) and why the structural fix makes one plan good for all inputs. Mention that on SQL Server 2022 (compatibility level 160) and Azure SQL, Parameter Sensitive Plan optimisation can cache several plans for one query, but only for some predicate patterns, so you still check Query Store.

Structural fix or plan mitigation? Prefer the structural fix when the query is frequent, the data keeps growing, or the skew is permanent (a few enterprise tenants): an index or rewritten query keeps working as data changes, while a forced plan is tied to today's statistics and schema. Use a forced plan or hint when you need relief in minutes, when the table is too write-heavy to afford another index, or as a bridge until the next release. Then measure: Application Insights dependency p95 for the endpoint, Query Store duration, logical reads and CPU per execution before and after, and watch the regressed-queries report for a few weeks as data grows.

Approach When it fits Cost When not to
Covering index Plan flips because of lookups; frequent query Writes, storage Very write-heavy table
Filtered or composite index for the big tenants Extreme skew concentrated in known values Maintenance, more indexes to reason about Skew isn't predictable
Query Store forced plan Immediate relief Fragile; hides cause As the permanent answer
RECOMPILE hint Rare, skewed queries CPU per call Hot, frequent queries
Separate queries for large vs small Known extreme skew (one giant tenant) Code complexity Skew isn't predictable

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions parameter sniffing or Query Store. Why: Checks the technical drill-down and the full set of fix options.
    How to answer

    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.

  2. When: Candidate mentions CONVERT_IMPLICIT or nvarchar parameters from EF Core. Why: Checks they can diagnose implicit conversions across EF Core, Dapper and ADO.NET.
    How to answer

    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.

  3. When: Candidate mentions SQL Server 2022 or Azure SQL handling sniffing automatically. Why: Checks they know what PSP optimisation does and doesn't fix.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Order history times out for big customers but is instant in SSMS
Situation
[Customer portal] on [Azure SQL], [Orders] table [~60M] rows, data highly skewed: most customers have under [100] orders, [a few enterprise accounts] have [200,000+]. The order history page was used by [account managers daily].
Signals
Support tickets from [enterprise customers]; Application Insights showing the SQL dependency for that query at [8–20 s] for some calls and [~50 ms] for others; timeouts (SqlException -2) after [30 s]; developers reporting the same query runs in under a second in SSMS.
Investigation
Ruled out network and app code: the SQL dependency duration itself was long. Reproduced the app's execution with `SET ARITHABORT OFF` and `sp_executesql` with an int parameter: slow for large customers. Query Store showed two plans for the query id, with the slow nested-loops plan in use since [a statistics update on date]; its estimated rows were [12] against [200,000] actual. Checked parameter types in EF Core logging: no implicit conversion. Conclusion: parameter sniffing with a non-covering index.
Resolution
Mitigation: forced the hash-join plan in Query Store; timeouts stopped within [10] minutes. Real fix: added a covering index on (CustomerId, CreatedAt DESC) INCLUDE (Total), which made a seek-plus-range-scan plan good for every customer size; unforced the plan and confirmed Query Store kept choosing the new plan across sizes.
Prevention
Weekly review of Query Store's regressed-queries report; an alert on dependency duration p95 for the endpoint; a team note on reproducing app plans (ARITHABORT, parameters) instead of trusting SSMS timings; a test dataset with realistic skew for performance tests.

How to tell it (STAR)

**S:** At [company], our [order history page] timed out for [our biggest customers], but the same query ran in under a second in SSMS, so people blamed the network. **T:** I [picked it up] to find the real cause. **A:** I knew SSMS uses different settings and gets its own plan, so I reproduced what the app actually sends. Query Store showed two plans: one built for a customer with [12] orders was being reused for customers with [200,000]. I forced the good plan to stop the timeouts within [ten] minutes, then added a covering index so one plan works for every customer size and removed the forced plan. **R:** P95 for that page dropped from [8 seconds] to [150 milliseconds], and we added a weekly Query Store regression check that has caught [N] issues since.

More in Production Incidents

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me