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

📚 Interview question

What is Query Store in SQL Server and Azure SQL? Explain what it captures, how you use it to find regressed or expensive queries, how plan forcing and Query Store hints work, the settings that matter, and what's on by default in Azure SQL.

Covers Query Store: captured query text, plans, runtime and wait statistics per interval, built-in reports, finding regressions, plan forcing and its failure modes, Query Store hints, key settings (capture mode, size, interval, cleanup, READ_ONLY flip) and Azure SQL defaults including automatic plan correction.

Mid-Level Theory Intermediate automatic-tuning azure-sql plan-forcing query-performance query-store sql-server

🎯 Key points

  • Persists query text, every plan, runtime stats (duration, CPU, reads, memory, rows) and wait stats per time interval inside the user database
  • Survives restarts and failovers, unlike plan cache DMVs
  • Reports: Regressed Queries, Top Resource Consuming, Queries With High Variation, Query Wait Statistics
  • Plan forcing (sp_query_store_force_plan) pins a plan; review forced plans and check last_force_failure_reason after schema changes
  • Query Store hints (SQL Server 2022 / Azure SQL) attach OPTION hints to a query_id without code changes
  • Monitor actual_state_desc and storage: it flips to READ_ONLY when MAX_STORAGE_SIZE_MB is reached and silently stops collecting
  • On by default in Azure SQL Database and new SQL Server 2022+ databases, but databases upgraded or restored from older versions keep their old setting; FORCE_LAST_GOOD_PLAN on by default for new Azure SQL servers
  • Use before/after comparisons for releases and compatibility-level upgrades

⏱ 30-second answer

Query Store is a flight recorder inside each database. It saves query text, every plan a query has used, and runtime statistics (duration, CPU, logical reads, memory, waits) aggregated per time interval, and it survives restarts and failovers.

I use the Regressed Queries and Top Resource Consuming reports to see which query got slower and whether its plan changed. If it did, I can force the previous plan, or attach a Query Store hint without touching code.

It's on by default in Azure SQL Database and for new databases in SQL Server 2022, and Azure SQL's automatic plan correction can force the last good plan for you. The trade-off is a little overhead and storage; the settings to watch are size, capture mode and the flip to read-only when full.

🗣 Full answer (senior)

How I would answer this in an interview

"Before Query Store, plan cache DMVs were all we had, and they forget everything on restart, failover or eviction, and only keep the current plan. Query Store fixes that. It writes to the user database the text of each query, every plan it has used, and runtime statistics aggregated per interval, an hour by default: execution count, duration, CPU, logical and physical reads, memory grant, row counts, and since 2017 wait categories. Because it's in the database, it survives failovers and goes with the database when you restore it.

I use it in three ways. First, regressions: the Regressed Queries report compares a recent window with a baseline, and if a query has a new plan that's slower I can force the old one with sp_query_store_force_plan. That's a reversible, visible mitigation during an incident. Second, finding the biggest consumers by total CPU or reads, which is where tuning effort pays off. Third, releases and upgrades: I compare before and after windows, and when raising the compatibility level I keep the old level for a while to capture a baseline, then switch and force any regressions. Since SQL Server 2022 and in Azure SQL there are Query Store hints, so I can attach OPTION (RECOMPILE) or MAXDOP 1 to an EF Core query by query_id without a deployment.

In Azure SQL Database it's on by default, and automatic plan correction (FORCE_LAST_GOOD_PLAN) is on by default for new servers, which detects plan regressions, forces the last good plan and verifies it helped. The mistake I see is forgetting it can fill up: when it reaches its size limit it flips to READ_ONLY and silently stops collecting. Query Store is the first place I look, so I make sure it's actually recording."


What Query Store captures

Catalog view Contents
sys.query_store_query_text / sys.query_store_query Text, query_hash, context settings
sys.query_store_plan Each plan, forced flag, force failures, compiled parameter values in the XML
sys.query_store_runtime_stats Per plan per interval: count, avg/min/max/stdev of duration, CPU, reads, memory, rows
sys.query_store_wait_stats Waits per plan per interval by category
sys.query_store_query_hints Hints attached with sp_query_store_set_hints

Settings that matter

Setting Default (SQL Server 2022) What I check
OPERATION_MODE READ_WRITE actual_state_desc is still READ_WRITE
QUERY_CAPTURE_MODE AUTO (skips trivial, infrequent queries) ALL only for short investigations
MAX_STORAGE_SIZE_MB 1,000 Usage vs limit
INTERVAL_LENGTH_MINUTES 60 Shorter (15) for faster incident detail
STALE_QUERY_THRESHOLD_DAYS 30 Long enough for monthly jobs
SIZE_BASED_CLEANUP_MODE AUTO Keep on

Production example

After a release, Azure SQL CPU went from [35%] to [90%]. Query Store's Top Resource Consuming report ranked one query first by total CPU; it had a new plan using a parallel scan. Forcing the old plan took CPU back to [40%] in minutes, and the root cause (a LINQ change that dropped a filter on an indexed column) was fixed in the next deployment.

🔍 What the interviewer is checking

Checks whether the candidate uses Query Store as the primary production performance tool and understands its limits.

Green flags

  • Knows what's captured and that it survives failovers.
  • Uses Regressed Queries / Top Resource Consuming and plan forcing.
  • Mentions Query Store hints and automatic plan correction.
  • Checks it hasn't flipped to READ_ONLY.

Red flags

  • Has never used it, relies only on SSMS reruns.
  • Treats forcing as a permanent fix.
  • Doesn't know it's on by default in Azure SQL.

📚 Learn in depth

1. How it records

query compiles/executes
      |
      v
[in-memory Query Store buffers] --async flush (DATA_FLUSH_INTERVAL_SECONDS, default 900)--> [user database tables]
      |
      v
runtime stats aggregated per plan per interval (INTERVAL_LENGTH_MINUTES)

Collection is asynchronous, so overhead is typically low single-digit percent CPU. A crash can lose the last unflushed minutes of statistics.

2. Queries, plans and variants

A query is identified by its text and context settings (SET options, schema). Each distinct plan gets a plan_id. With PSP optimisation (2022), one parent query has a dispatcher plan and up to three variant queries, which appear as separate query_ids linked by sys.query_store_query_variant.

3. Plan forcing internals

Forcing stores the plan's shape; at the next compile the optimiser is asked to produce that shape. It can fail if an index the plan used is dropped or renamed (last_force_failure_reason_desc, e.g. NO_INDEX), and then the query compiles normally. SQL Server 2022 adds optimised plan forcing, which stores a replay script to reduce compile time for forced plans.

4. Automatic plan correction

FORCE_LAST_GOOD_PLAN watches for plan-choice regressions (a new plan with significantly worse CPU), forces the previous plan, then verifies it actually helped and unforces it if not. Recommendations are in sys.dm_db_tuning_recommendations. It is on by default for new Azure SQL Database servers; on SQL Server it must be enabled per database (Enterprise edition feature).

5. Query Store hints

sys.sp_query_store_set_hints @query_id, N'OPTION (...)' applies hints like RECOMPILE, MAXDOP, USE HINT('...'), OPTIMIZE FOR UNKNOWN to a query without changing its text. Ideal for ORM-generated or vendor SQL. Remove with sp_query_store_clear_hints.

6. Operational gotchas

  • Flip to READ_ONLY when MAX_STORAGE_SIZE_MB is reached; check readonly_reason.
  • Ad hoc, unparameterised workloads produce huge numbers of query texts; AUTO capture mode and size-based cleanup help, but parameterising is the fix.
  • Query Store data is per database: queries spanning databases are recorded in the database where they execute.

Try it yourself

  1. Check SELECT actual_state_desc, current_storage_size_mb, max_storage_size_mb FROM sys.database_query_store_options;.
  2. Create a regression by dropping an index, run the query, then use the Regressed Queries report to find it.
  3. Force a plan with sp_query_store_force_plan, drop the index it uses, and read last_force_failure_reason_desc.
  4. Attach OPTION (MAXDOP 1) to a query with sp_query_store_set_hints and confirm with the plan's degree of parallelism.
  5. In Azure SQL, query sys.dm_db_tuning_recommendations and sys.database_automatic_tuning_options.

💻 Code

Health check, top consumers, and forcing.

-- Is Query Store actually recording?
SELECT actual_state_desc, readonly_reason, current_storage_size_mb,
       max_storage_size_mb, query_capture_mode_desc, interval_length_minutes
FROM sys.database_query_store_options;

-- Top 10 queries by total CPU in the last 24 hours
SELECT TOP (10)
    q.query_id,
    SUM(rs.count_executions)                                   AS executions,
    SUM(rs.avg_cpu_time * rs.count_executions) / 1000000.0     AS total_cpu_s,
    SUM(rs.avg_logical_io_reads * rs.count_executions)         AS total_reads,
    COUNT(DISTINCT p.plan_id)                                  AS plans,
    MIN(qt.query_sql_text)                                     AS query_text
FROM sys.query_store_runtime_stats rs
JOIN sys.query_store_runtime_stats_interval i ON i.runtime_stats_interval_id = rs.runtime_stats_interval_id
JOIN sys.query_store_plan p   ON p.plan_id = rs.plan_id
JOIN sys.query_store_query q  ON q.query_id = p.query_id
JOIN sys.query_store_query_text qt ON qt.query_text_id = q.query_text_id
WHERE i.start_time > DATEADD(hour, -24, SYSUTCDATETIME())
GROUP BY q.query_id
ORDER BY total_cpu_s DESC;

-- Force the good plan, and later check it is still being honoured
EXEC sys.sp_query_store_force_plan @query_id = 1234, @plan_id = 56;

SELECT plan_id, is_forced_plan, force_failure_count, last_force_failure_reason_desc
FROM sys.query_store_plan WHERE query_id = 1234;

-- Sensible settings for a busy OLTP database
ALTER DATABASE CURRENT SET QUERY_STORE = ON
    (OPERATION_MODE = READ_WRITE, QUERY_CAPTURE_MODE = AUTO,
     MAX_STORAGE_SIZE_MB = 4096, INTERVAL_LENGTH_MINUTES = 15,
     SIZE_BASED_CLEANUP_MODE = AUTO);

Tag EF Core queries so they're easy to find in query_sql_text:

namespace Shop.Data;

using Microsoft.EntityFrameworkCore;

public sealed class DashboardQueries(ShopDbContext db)
{
    public Task<decimal> RevenueSinceAsync(DateTime from, CancellationToken ct) =>
        db.Orders
          .TagWith("dashboard:revenue-since") // appears as a SQL comment in Query Store
          .Where(o => o.OrderDate >= from)
          .SumAsync(o => o.Total, ct);
}

⚠ Common mistakes

  • Mistake: Assuming Query Store is recording because it was turned on once. Why it is wrong: It flips to READ_ONLY when full and stops collecting, so the history is missing exactly when an incident needs it. Instead: Alert on actual_state_desc and on usage above about 80% of MAX_STORAGE_SIZE_MB; raise the limit and keep size-based cleanup on.
  • Mistake: Assuming an upgraded database has Query Store on. Why it is wrong: The 'on by default' rule in SQL Server 2022 applies to new databases; a database upgraded or restored from 2016–2019 keeps whatever it had. Instead: After any upgrade or migration, run ALTER DATABASE ... SET QUERY_STORE = ON (OPERATION_MODE = READ_WRITE) and verify settings, ideally before changing compatibility level so you have a baseline.
  • Mistake: Using QUERY_CAPTURE_MODE = ALL permanently. Why it is wrong: Captures every trivial and one-off query, inflating size and overhead. Instead: AUTO or CUSTOM; ALL only briefly.
  • Mistake: Forcing a plan and forgetting about it. Why it is wrong: The plan was good for last month's data. As the table grows, a forced nested-loops plan can end up doing millions of lookups, a forced serial plan can't use parallelism for a much larger scan, and a dropped or renamed index makes forcing fail silently so the query is back on whatever plan the optimiser picks. Instead: Keep a reviewed list of forced plans with owners and dates, check force_failure_count and last_force_failure_reason_desc, and unforce once the root cause is fixed.
  • Mistake: Treating forcing as the fix. Why it is wrong: It masks the underlying estimate or code problem. Instead: Use it as mitigation and fix the cause.
  • Mistake: Relying on plan cache DMVs for historical analysis. Why it is wrong: They lose history on restart, failover and eviction. Instead: Use Query Store intervals.
  • Mistake: Upgrading compatibility level without a Query Store baseline. Why it is wrong: You can't tell which queries regressed. Instead: Capture at the old level, switch, compare, force regressions.
  • Mistake: Not knowing automatic plan correction may already have acted in Azure SQL. Why it is wrong: You may misread a forced plan as your own. Instead: Check sys.dm_db_tuning_recommendations.

🏛 Senior insight: trade-offs

Query Store turns 'it was slow yesterday' from guesswork into data, and it should be part of every release and upgrade process: capture, compare, mitigate, fix. The senior habits are making sure it's healthy (size, mode, interval), owning the list of forced plans and hints as operational state, and preferring code fixes once the fire is out.

In Azure SQL Database it's on by default with automatic plan correction on new servers; on SQL Server 2022 it's on for new databases, but upgraded databases may still have it off, so check.

Mitigation When it fits Cost When not to
Force last good plan Clear plan-choice regression Plan may age badly Regression from data growth, not plan change
Query Store hint ORM/vendor SQL needing RECOMPILE, MAXDOP, CE version Outside source control Code you own and can change today
Automatic plan correction Azure SQL baseline protection Occasional unexpected forcing When you need full manual control (document it)
Code / index fix Root cause known Release cycle Mid-incident when minutes matter

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions forcing a plan after a regression Why: Checks the diagnosis that should come before forcing
    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 using Query Store after a release Why: Checks the end-to-end regression workflow from App Insights to code
    How to answer

    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.

  3. When: Candidate says they force plans Why: Checks operational maturity around forced plans
    How to answer

    Forcing only works while the optimiser can still produce that plan. If an index it uses is dropped or renamed, the query text or SET options change (so it is a different query_id), or a schema change makes the plan invalid, forcing fails and SQL Server quietly compiles a normal plan. I notice through force_failure_count and last_force_failure_reason_desc in sys.query_store_plan, the query_store_plan_forcing_failed extended event, or a new plan_id appearing for the query. I also keep Query Store healthy (READ_WRITE, not full) and review forced plans after releases, because plans and data evolve.

🛠 Real-world problems: how you handle them

Query Store silently stopped recording before an incident
Situation
A [payments] database on [Azure SQL, Business Critical] had Query Store on with a small storage limit set years earlier. An incident needed historical plan data.
Signals
During a CPU spike, the Regressed Queries report showed nothing after [three weeks ago]. `sys.database_query_store_options` showed `actual_state_desc = READ_ONLY` with `readonly_reason = 65536` (storage limit reached).
Investigation
Storage usage equalled `MAX_STORAGE_SIZE_MB` ([100 MB]). The query text table held [hundreds of thousands] of near-identical ad hoc queries from a batch job concatenating SQL. The plan cache DMVs gave only the current plan, so the incident was diagnosed from live DMVs and Application Insights instead.
Resolution
Raised the limit to [4 GB], set QUERY_CAPTURE_MODE = AUTO and size-based cleanup, set the database back to READ_WRITE, and parameterised the batch job's SQL. The CPU issue itself was a regressed plan, mitigated by forcing once new data arrived.
Prevention
An Azure Monitor alert on Query Store state and usage over [80%]; a monthly check of forced plans; Query Store settings added to the database's infrastructure-as-code.

How to tell it (STAR)

**S:** During a CPU incident on our [payments] database, I opened Query Store and found no data for the last three weeks. **T:** I needed to work out why so it wouldn't happen during the next incident. **A:** Query Store had flipped to read-only because its 100 MB limit was full of near-duplicate ad hoc queries from a batch job. I raised the limit, set capture mode to auto with size-based cleanup, put it back to read-write and got the batch job parameterised. Then I added an alert on Query Store state and moved its settings into our infrastructure code. **R:** We've had full history for every incident since, and the next regression was found and mitigated in [under 15 minutes].

↩ Usually asked after

More in Query Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me