Most slow-query investigations start in the wrong place: a CPU alert fires, someone opens the plan cache, and whatever is running right now gets tuned. That finds the loudest query, not necessarily the costliest one, and it says nothing about what changed.

Query Store supplies the missing piece: historical visibility. It records query text, execution plans, and runtime statistics over time intervals. Because this information is persisted in the user database, it survives SQL Server restarts. Execution plans then help explain why a particular query is slow.

This article covers a practical troubleshooting workflow for SQL Server 2016 and later:

  1. Configure Query Store before performance problems occur.
  2. Identify expensive queries using cumulative resource consumption.
  3. Detect plan regressions and compare historical execution plans.
  4. Investigate execution plans to find the underlying problem.
  5. Apply targeted fixes and use plan forcing as a temporary fallback.

Every example uses T-SQL. Replace the sample database names and identifiers with values from your own environment.

Step 1: Configure Query Store Before You Need It

Query Store is available starting with SQL Server 2016. SQL Server 2022 enables it by default for newly created databases, but existing databases and upgraded environments should still be checked.

Enable it explicitly:

ALTER DATABASE SalesDB SET QUERY_STORE = ON; 

Next, configure its operating parameters:

ALTER DATABASE SalesDB SET QUERY_STORE ( OPERATION_MODE = READ_WRITE, QUERY_CAPTURE_MODE = AUTO, MAX_STORAGE_SIZE_MB = 2048, INTERVAL_LENGTH_MINUTES = 30, CLEANUP_POLICY = ( STALE_QUERY_THRESHOLD_DAYS = 30 ), SIZE_BASED_CLEANUP_MODE = AUTO ); 

For SQL Server 2017 and later, enable wait statistics capture separately:

ALTER DATABASE SalesDB SET QUERY_STORE ( WAIT_STATS_CAPTURE_MODE = ON ); 

Why do these settings matter?

  • QUERY_CAPTURE_MODE = AUTO: Avoids capturing every trivial or insignificant query, helping prevent unnecessary Query Store growth.
  • INTERVAL_LENGTH_MINUTES = 30: Provides more granular historical performance information than the default 60-minute interval.
  • MAX_STORAGE_SIZE_MB = 2048: Establishes a storage limit. If Query Store reaches its limit, it can transition to read-only mode and stop collecting new information.
  • STALE_QUERY_THRESHOLD_DAYS = 30: Retains historical information for a defined period.
  • SIZE_BASED_CLEANUP_MODE = AUTO: Allows SQL Server to remove older information when storage pressure occurs.
  • WAIT_STATS_CAPTURE_MODE = ON: Available from SQL Server 2017 onward, this captures wait statistics that help distinguish CPU consumption from waiting on locks, I/O, and other resources.

These values are starting points, not universal production recommendations. Adjust the storage limit and retention period according to workload volume, query diversity, and monitoring requirements.

A useful habit is to verify Query Store's state periodically:

SELECT actual_state_desc, desired_state_desc, readonly_reason, current_storage_size_mb, max_storage_size_mb, query_capture_mode_desc FROM sys.database_query_store_options; 

If actual_state_desc differs from desired_state_desc, investigate why Query Store is not operating as expected.

Step 2: Rank Queries by Total Resource Consumption, Not the Worst Single Execution

Start with one question: Which queries consumed the most resources over the last 24 hours?

Consider two queries:

  • Query A executes once and takes 30 seconds.
  • Query B executes two million times and takes 40 milliseconds per execution.

Query A looks worse when examining individual execution time. However, Query B may consume considerably more cumulative resources.

Query Store records average runtime statistics and execution counts for individual intervals. Multiplying the averages by execution counts provides an estimate of cumulative consumption.

The following query identifies the top 10 queries by total execution duration:

DECLARE @Since DATETIME2 = DATEADD(HOUR, - 24, SYSUTCDATETIME()); SELECT TOP (10) q.query_id ,LEFT(qt.query_sql_text, 80) AS query_text ,SUM(rs.count_executions) AS executions ,SUM(rs.avg_duration * rs.count_executions) / 1000.0 AS total_duration_ms ,SUM(rs.avg_cpu_time * rs.count_executions) / 1000.0 AS total_cpu_ms ,SUM(rs.avg_logical_io_reads * rs.count_executions) AS total_logical_reads FROM sys.query_store_query AS q JOIN sys.query_store_query_text AS qt ON qt.query_text_id = q.query_text_id JOIN sys.query_store_plan AS p ON p.query_id = q.query_id JOIN sys.query_store_runtime_stats AS rs ON rs.plan_id = p.plan_id JOIN sys.query_store_runtime_stats_interval AS i ON i.runtime_stats_interval_id = rs.runtime_stats_interval_id WHERE i.end_time >= @Since AND rs.execution_type = 0 GROUP BY q.query_id ,LEFT(qt.query_sql_text, 80) ORDER BY total_duration_ms DESC; 

A few details matter when interpreting these results:

  • avg_duration and avg_cpu_time are measured in microseconds. Dividing by 1,000 converts the calculated totals into milliseconds.
  • avg_logical_io_reads represents average logical pages read per execution.
  • count_executions represents the number of executions recorded for the interval.
  • Query Store timestamps are in UTC, which is why the example uses SYSUTCDATETIME().

The time filter uses interval boundaries, so it can include executions from an interval that began before the exact 24-hour cutoff. The results are therefore an interval-based approximation rather than an exact rolling 24-hour measurement.

Run the query three times, changing the final ordering:

ORDER BY total_duration_ms DESC; 

ORDER BY total_cpu_ms DESC; 

ORDER BY total_logical_reads DESC; 

Queries appearing in multiple lists deserve closer investigation.

The SSMS Top Resource Consuming Queries report provides a graphical view of similar information. However, keeping a reusable SQL script makes it easier to automate reporting and compare workload trends over time.

Step 3: Find Query Regressions and Execution Plan Changes

A query that suddenly becomes slower without an application code change often deserves a plan investigation.

Possible causes include:

  • Statistics updates.
  • Parameter sniffing.
  • Changes in data distribution.
  • Index creation or removal.
  • Query recompilation.
  • Database compatibility-level changes.

Query Store allows you to compare execution plans associated with the same query. First, identify the relevant query_id from the previous step. Then examine its historical plans.

DECLARE @QueryId BIGINT = 42; DECLARE @Since DATETIME2 = DATEADD(HOUR, - 24, SYSUTCDATETIME()); SELECT p.plan_id ,p.is_forced_plan ,p.initial_compile_start_time ,p.last_compile_start_time ,p.last_execution_time ,SUM(rs.count_executions) AS executions ,SUM(rs.avg_duration * rs.count_executions) / NULLIF(SUM(rs.count_executions), 0) / 1000.0 AS avg_duration_ms ,SUM(rs.avg_logical_io_reads * rs.count_executions) / NULLIF(SUM(rs.count_executions), 0) AS avg_logical_reads FROM sys.query_store_plan AS p JOIN sys.query_store_runtime_stats AS rs ON rs.plan_id = p.plan_id JOIN sys.query_store_runtime_stats_interval AS i ON i.runtime_stats_interval_id = rs.runtime_stats_interval_id WHERE p.query_id = @QueryId AND i.end_time >= @Since AND rs.execution_type = 0 GROUP BY p.plan_id ,p.is_forced_plan ,p.initial_compile_start_time ,p.last_compile_start_time ,p.last_execution_time ORDER BY p.initial_compile_start_time DESC; 

This query calculates execution-count-weighted average duration and logical reads for each plan over the selected interval window.

Suppose the results show two plans:

Metric

Plan 17

Plan 23

Average duration

180 ms

2,400 ms

Average logical reads

1,200

85,000

Executions

12,000

3,500

These numbers are illustrative, but they show the kind of regression worth investigating.

Plan 23 takes considerably longer and performs significantly more logical reads.

The next step is to establish when the change occurred and correlate it with:

  • Application deployments.
  • Statistics updates.
  • Index maintenance.
  • Database configuration changes.
  • Changes in parameter values or workload distribution.

SQL Server Management Studio also provides the Regressed Queries report, which helps visualize performance changes and compare execution plans side by side. An important distinction: a different plan is not automatically a bad plan. The objective is to identify whether the plan change explains the observed performance degradation.

Step 4: Read the Execution Plan to Find the Actual Cause

Query Store preserves compiled execution plans, but these plans generally contain estimated row counts rather than actual runtime row counts. For actual execution information, capture an actual execution plan by rerunning the query with Include Actual Execution Plan enabled in SSMS.

On SQL Server 2019 and later, you can also enable last-query-plan statistics:

ALTER DATABASE SCOPED CONFIGURATION SET LAST_QUERY_PLAN_STATS = ON; 

The sys.dm_exec_query_plan_stats function can then provide the last known actual execution plan for a cached plan handle.

Remember that this is last-execution information, not a complete historical collection of actual execution plans.

When examining an execution plan, I recommend following this order.

1. Compare estimated rows with actual rows.

One of the most useful indicators is the difference between estimated and actual row counts.

For example:

Operator

Estimated rows

Actual rows

Index Seek

100

12,000

Nested Loops

100

12,000

Key Lookup

100

12,000

The optimizer expected approximately 100 rows but encountered 12,000.

That difference can influence downstream decisions, including join selection, memory grants, and parallelism.

Investigate:

  • Statistics freshness.
  • Statistics sampling.
  • Data distribution.
  • Predicate selectivity.
  • Parameter sniffing.

A significant estimation difference is a diagnostic clue, not automatic proof that statistics are the problem.

2. Investigate parameter sniffing.

Parameter sniffing occurs when SQL Server compiles a parameterized query using particular parameter values and reuses the resulting execution plan for subsequent executions. This can become problematic when parameter values have highly different data distributions.

For example, consider an orders table where:

  • One customer has 500,000 orders.
  • Another customer has only 15 orders.

An execution plan optimized for the second customer may perform poorly when reused for the first. In an actual execution plan, inspect the parameter information, including:

  • Parameter Compiled Value.
  • Parameter Runtime Value.

A significant difference between these values, combined with skewed data and inconsistent performance, can indicate parameter sensitivity.

3. Investigate scans and key lookups.

An Index Seek is not always better than an Index Scan. SQL Server chooses an access method based on estimated cost, cardinality, available indexes, and the amount of data required. However, certain patterns deserve investigation.

For example:

  • A Key Lookup executed thousands of times may indicate that a covering index could help.
  • A scan on a large table with a highly selective predicate may indicate a missing index or non-SARGable expression.
  • Repeated lookups may create substantial random I/O.

Before creating an index, evaluate existing indexes, write overhead, storage consumption, and whether the proposed index would actually improve the workload.

4. Look for execution plan warnings.

Pay particular attention to:

  • Implicit conversions in predicates.
  • Sort and hash spills to tempdb.
  • Excessive memory grants.
  • Missing join predicates.
  • Warnings involving cardinality estimates.

For example, comparing an integer column with a string parameter can introduce an implicit conversion and prevent an efficient index access path in some circumstances. Similarly, spills to tempdb can indicate that an operator received an insufficient memory grant. These warnings help identify where further investigation is needed.

5. Treat missing index suggestions as recommendations, not instructions.

SQL Server may suggest missing indexes in execution plans. However, these suggestions do not understand the entire indexing strategy of your application.

Before creating a suggested index, consider:

  • Whether an existing index can be modified.
  • Whether the index duplicates another index.
  • Whether additional indexes will increase write overhead.
  • Whether the query is important enough to justify the storage cost.

The goal is not to maximize the number of indexes. It is to improve the overall workload.

Step 5: Fix the Root Cause Before Forcing an Execution Plan

Once you understand the problem, address the underlying cause. A reasonable troubleshooting order is:

  1. Correct outdated or insufficient statistics.
  2. Review missing, redundant, or poorly designed indexes.
  3. Remove unnecessary implicit conversions.
  4. Rewrite non-SARGable predicates where appropriate.
  5. Investigate parameter sniffing and parameter sensitivity.
  6. Reevaluate execution plans after applying the changes.

Sometimes the root cause cannot be fixed immediately. For example, a vendor application may generate SQL that cannot be modified without a lengthy release process. SQL Server 2022 introduced Query Store hints, which allow administrators to apply supported query hints without changing application code.

Consider the following example:

EXEC sys.sp_query_store_set_hints @query_id = 42, @query_hints = N'OPTION (RECOMPILE)'; 

This applies a recompilation hint to the selected Query Store query.

It is important to understand that OPTION (RECOMPILE) is not plan forcing. It instructs SQL Server to compile a new plan for each execution, which can help with parameter-sensitive workloads but also introduces compilation overhead.

Another option is to force a previously successful execution plan.

EXEC sys.sp_query_store_force_plan @query_id = 42, @plan_id = 17; 

This tells SQL Server to use the selected historical plan when possible. Plan forcing should be treated as a temporary mitigation rather than a permanent solution. A forced plan may become less efficient as data distributions and workloads change. It may also fail to apply if required database objects or indexes are no longer available.

Monitor plan-forcing status using:

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

Since SQL Server 2017, automatic plan correction is also available on supported SQL Server configurations.

It can be configured using:

ALTER DATABASE SalesDB SET AUTOMATIC_TUNING ( FORCE_LAST_GOOD_PLAN = ON ); 

Check edition and platform support before enabling automatic tuning.

Even when automatic correction is available, monitor its decisions and validate that the forced plans continue to perform well.

A Practical Troubleshooting Scenario

Consider an e-commerce application where the order history endpoint starts responding slowly. Initially, the endpoint responds in approximately 200 milliseconds. After a deployment and a change in workload distribution, response times increase to several seconds. The development team initially suspects application code. However, Query Store reveals something different.

Investigation 1: Identify the expensive query

The query appears near the top of the total-duration report. Its execution count has increased, and its average duration is substantially higher than its historical baseline.

Investigation 2: Compare execution plans

Query Store shows that the query has two historical plans. The newer plan performs significantly more logical reads.

Investigation 3: Inspect the actual execution plan

The team finds that a parameter-sensitive query is using an inefficient plan for customers with large order histories. The actual row counts differ significantly from the estimates.

Investigation 4: Apply the fix

The team evaluates the available indexes, reviews statistics, and tests a suitable parameter-sensitive query optimization. If an immediate application change is not possible, a Query Store hint or a previously successful plan may provide a temporary mitigation.

Investigation 5: Validate the result

After the change, the team compares:

  • Average execution duration.
  • Total CPU consumption.
  • Logical reads.
  • Execution count.
  • Plan stability.

The objective is not simply to make one execution faster. It is to restore predictable performance across the workload.

Common Query Store Pitfalls

Even with Query Store enabled, several issues can affect the accuracy of your investigation.

1. Query Store stops collecting information

A full Query Store can transition into read-only mode.

Check sys.database_query_store_options regularly, especially actual_state_desc, desired_state_desc, and readonly_reason.

2. Ad hoc workloads inflate storage consumption

Applications that generate many unparameterized queries can create large numbers of distinct query entries. Use an appropriate capture mode and investigate parameterization opportunities.

3. Averages hide performance variations

A reasonable average duration can hide occasional executions that take several seconds. Examine maximum duration, standard deviation, execution counts, and individual runtime intervals before deciding that a plan is healthy.

4. Time zones create misleading correlations

Query Store timestamps are stored in UTC. Convert timestamps appropriately before comparing them with application logs, deployment records, or monitoring dashboards.

5. Historical statistics are not necessarily actual execution plans

Query Store provides valuable plan history and aggregated runtime statistics, but it should not be mistaken for a complete historical record of actual execution plans with actual row counts. Use actual execution plans and appropriate runtime diagnostics when deeper investigation is necessary.

SQL Server Feature Compatibility

The examples in this article target different SQL Server versions.

Feature

Minimum SQL Server version

Query Store

SQL Server 2016

Query Store wait statistics

SQL Server 2017

Automatic plan correction

SQL Server 2017

LAST_QUERY_PLAN_STATS

SQL Server 2019

Custom Query Store capture mode

SQL Server 2019

Query Store hints

SQL Server 2022

Always verify the feature's availability and configuration requirements for your SQL Server edition and deployment environment.

Key Takeaways

Diagnosing slow SQL queries requires more than identifying expensive operators in an execution plan. The most effective approach combines historical workload information with detailed execution-plan analysis.

Here are the main lessons:

  1. Enable Query Store before performance incidents occur, and configure storage and retention deliberately.
  2. Rank queries by cumulative duration, CPU, and logical reads rather than focusing exclusively on the slowest individual execution.
  3. Compare historical execution plans to identify regressions and establish when they started.
  4. Investigate estimated versus actual rows, parameter sensitivity, lookups, scans, and execution-plan warnings.
  5. Fix underlying statistics, indexing, and query design issues before relying on plan forcing.
  6. Monitor Query Store itself to ensure that it continues collecting useful information.

The tooling is not the hardest part of SQL Server performance troubleshooting. What separates a ten-minute diagnosis from a three-day investigation is having the historical evidence to understand what changed. Query Store provides that evidence. Execution plans help explain it. Together, they give database engineers a repeatable approach to diagnosing and resolving SQL Server performance problems.