Microsoft AzureDatabaseSQLIntermediate27 min read

What Is Query Store in Databases?

Also known as: Query Store, SQL Server Query Store, DP-300 exam, Azure SQL performance monitoring, database monitoring tool

Reviewed byJohnson Ajibi· Senior Network & Security Engineer · MSc IT Security
On This Page

Quick Definition

Query Store is a tool inside Microsoft SQL Server and Azure SQL Database that automatically records every query that runs and how long it takes. It keeps a history of these queries so you can see when performance changed or got worse. Think of it as a black box flight recorder for your database queries.

Must Know for Exams

Query Store appears in the DP-300 exam, which focuses on administering relational databases on Microsoft Azure. The exam objectives include monitoring and optimizing performance, and Query Store is explicitly mentioned as a key tool for this. You need to understand not only what Query Store does but also how to enable it, configure it, interpret its data, and use its features like plan forcing.

The exam will test your ability to analyze performance scenarios and choose the right approach. For example, a question might present a scenario where a critical report query runs slowly after a maintenance window. You need to know that Query Store can show you the previous plan and the current plan, and that you can force the previous plan to restore performance.

The exam also tests your understanding of Query Store’s limitations, such as its size limit and impact on database performance when capturing every query. You should know that Query Store can be configured to capture only expensive queries to reduce overhead. Another common exam scenario involves using Query Store to identify parameter sniffing issues.

Parameter sniffing happens when a query’s plan is optimized for a specific parameter value, causing poor performance for other values. Query Store can reveal that the same query used different plans for different parameter values, and you can then use plan forcing or query hints to resolve it. The DP-300 exam also covers Query Store in the context of Azure SQL Database, where it is always enabled.

You should know how to access Query Store reports via SQL Server Management Studio and via the Azure portal. Additionally, the exam may ask about the relationship between Query Store and the Database Engine Tuning Advisor or Automatic Tuning. Understanding that Query Store feeds data to Automatic Tuning is important.

Finally, the exam may present questions where you need to interpret Query Store DMV results, such as identifying which queries have the highest cumulative duration or which plans have regressed. You must be comfortable with the view names like sys.query_store_query and sys.

query_store_plan. Mastering Query Store not only helps you pass the exam but also provides a practical skill that you will use daily as a database administrator.

Simple Meaning

Imagine you are a school librarian trying to figure out why students are taking longer to find books this month compared to last month. You have no record of which books they looked for, how they searched, or which routes they took. Query Store is like installing a small camera and a logbook at the library entrance that records every student’s search path, the time it took them to find a book, and whether they had to ask for help.

Every day, the logbook is stored safely, and the librarian can flip back through the pages to see exactly what happened on any given day. If a student suddenly started taking twice as long to find a book on ancient history, the librarian can look at the logbook from last week and this week, compare the two search routes, and discover that three new shelves were moved, causing confusion. In the world of databases, the librarian is the database administrator, the students are the queries, the search routes are the execution plans, and the time taken is the performance metric.

Query Store automatically captures this data without anyone having to set up complex monitoring tools. It stores the execution plan for each query and the runtime statistics, keeping a historical record that can be queried later. This makes it possible to answer questions like: which query suddenly became slow?

What changed in its plan? Was it a new version of the plan that used a different index? The best part is that Query Store works continuously and requires no manual intervention. It is like having a diligent assistant that never forgets to write down the details.

For a beginner preparing for the DP-300 exam, understanding Query Store is essential because it is Microsoft’s recommended solution for query performance troubleshooting and it integrates deeply with Azure SQL Database and SQL Server 2016 and later versions. It helps you move from guessing why performance changed to actually seeing the evidence.

Full Technical Definition

Query Store is a feature introduced in SQL Server 2016 and available in Azure SQL Database and Azure SQL Managed Instance. It functions as a flight data recorder for a database, persistently storing query text, execution plans, and runtime statistics. The feature is implemented at the database level and consists of two main stores: the plan store and the runtime stats store.

The plan store captures the execution plan for each query that gets compiled or recompiled. The runtime stats store captures metrics such as CPU time, duration, logical reads, and memory consumption for each query execution, aggregated into time intervals. Query Store operates by enabling it on a specific database using ALTER DATABASE SET QUERY_STORE = ON.

Once enabled, it automatically begins collecting data. The data is stored inside the user database itself in internal tables, not in a separate system database. This design ensures that the data persists across server restarts and can be queried using system catalog views such as sys.

query_store_query, sys.query_store_plan, and sys.query_store_runtime_stats. A critical component is the wait stats capture, which records why a query waited (e.g., for I/O, locks, or CPU).

This helps identify bottlenecks. Query Store also includes a feature called Plan Forcing, which allows an administrator to force a specific execution plan for a query, overriding the query optimizer’s choice. This is useful when a new plan causes regression.

In Azure SQL Database, Query Store is enabled by default and cannot be disabled for single databases. The feature has configurable settings like data flush interval, max size, and capture mode (capture all or capture by query cost). Query Store also provides a set of built-in reports in SQL Server Management Studio and Azure portal dashboards, including Top Resource Consuming Queries, Queries with Forced Plans, and overall resource consumption by time.

For exam purposes, you need to know that Query Store is compatible with both on-premises SQL Server and Azure SQL and is a cornerstone of intelligent performance troubleshooting. It supports the Query Store hints feature in SQL Server 2022, allowing adjustments without changing code. The data retention and cleanup are managed via the STALE_QUERY_THRESHOLD_DAYS setting.

Understanding Query Store’s internal architecture, its two stores, and how to query the views is part of the DP-300 exam objective 3.1 Monitor and Optimize Performance.

Real-Life Example

Think of a public library that has a massive collection of books. Every day, hundreds of visitors come to find specific titles. Each visitor approaches the information desk, gets a route card, and walks through the aisles to find their book.

The librarian wants to understand which routes people take, how long they search, and whether the new shelving layout is causing longer waits. So, the librarian installs a system. Every time a visitor checks in, the system records their starting time, the book they are looking for, and a map of the path they took.

This map is the execution plan. The system also records the total time from start to finish. This is the runtime statistics. Now suppose a visitor named Anna comes on Monday and finds her book in 3 minutes.

The system stores that the plan involved going straight to aisle 7 and grabbing the book from the top shelf. On Wednesday, Anna comes again looking for a different book, but the shelves have been rearranged. The system records a new plan: she took a longer path, walked past aisles 5 and 9, and finally found the book after 10 minutes.

The system keeps both records. The librarian can now compare Monday and Wednesday. She sees that Anna’s query (looking for a book) used two different plans on different days, and the second plan was slower.

The librarian can even force Anna to use Monday’s plan again if that plan is better, even if the system would normally choose the longer path. This is exactly what Query Store does. It records each query’s execution plan and its performance metrics over time.

It keeps a history so that when performance degrades, a database administrator can identify which queries regressed, what plan they used before, and what plan they use now. The administrator can then force the old, better plan back into use if necessary. In real life, the library system corresponds to the SQL Server database engine.

The visitors are the queries. The route cards are the execution plans. The clock at the entrance and exit is the runtime stats. The librarian’s ability to compare days is exactly how Query Store’s reports and DMVs work.

The analogy holds well because Query Store, like the library system, is passive and automatically captures everything without manual setup. It gives you a time machine for query performance.

Why This Term Matters

Query Store matters because it solves one of the most frustrating problems in database administration: unexplained performance degradation. Before Query Store, when a query suddenly slowed down, a DBA had to rely on guesswork, manual logs, or external monitoring tools. They might have a backup of the execution plan from a week ago, but only if they remembered to capture it.

Query Store automates this entirely. It continuously captures both the plan and the performance, creating a historical record that can be queried at any time. This is critical in production environments where thousands of queries run per second and performance changes can happen due to updated statistics, index changes, schema modifications, or parameter sniffing.

Without Query Store, finding the root cause of a performance regression could take hours of manual analysis and might require reproducing the issue under load, which is risky. With Query Store, you can run a simple query to find all queries that have regressed in the last 24 hours, see which plan they used before and after, and even force the old plan to restore performance immediately. This reduces downtime and troubleshooting time significantly.

In cloud environments like Azure SQL Database, where you cannot access the underlying operating system or run a profiler easily, Query Store is often the only built-in performance troubleshooting tool available. It also supports reporting in the Azure portal, giving DevOps teams a quick dashboard of database health. For organizations that need to meet service level agreements, Query Store provides evidence and data to prove that performance was met or to justify tuning efforts.

It also helps in capacity planning by showing which queries consume the most resources over time. Moreover, Query Store is used by Azure SQL Database’s automatic tuning features, which can automatically identify and fix query plan regression issues if configured. This moves performance management from reactive to proactive.

In short, Query Store matters because it gives DBAs a reliable, always-on, historical record of query performance, enabling faster root cause analysis, better decision making, and more stable applications.

How It Appears in Exam Questions

In the DP-300 exam, Query Store questions often come in scenario-based and configuration-based formats. One common pattern is a scenario where a user reports that a specific report has become slow after a recent maintenance operation, such as rebuilding indexes or updating statistics. The question then asks which tool or feature you should use to identify the cause.

The correct answer typically involves Query Store, because it can show plan changes over time. Another pattern involves multiple-choice questions about Query Store configuration settings. For example, you might be asked which setting controls how often data is written to disk, and you need to pick DATA_FLUSH_INTERVAL_SECONDS.

Another type of question presents a result set from a Query Store DMV and asks you to interpret it. You may see a list of queries with their plan IDs, execution counts, and average duration. The question might ask: which query shows signs of plan regression?

You would look for a query where the same plan ID has widely different durations or where a plan change occurred and the new plan is slower. Configuration questions may ask you to enable Query Store on a database, set a maximum size, or configure the capture mode to reduce overhead. For example, a question might describe a busy OLTP database where enabling Query Store is causing performance overhead, and you need to choose a suitable capture mode, such as CAPTURE_AUTO or setting a query cost threshold.

Architecture questions may ask about the two internal stores of Query Store: the plan store and the runtime stats store. You might be asked which store holds the wait statistics. Troubleshooting questions often involve parameter sniffing.

A typical question: a stored procedure runs fast for most parameters but slow for one specific value. Using Query Store, you see two different plans for the same query, generated based on different parameter values. The question asks what the likely issue is and how to fix it.

The fix could be to use the RECOMPILE hint or to force a plan. Another common trap is confusing Query Store with the Database Engine Tuning Advisor. The exam may present a question where both are listed as options, and you need to know that Query Store is for historical monitoring and plan forcing, while the Tuning Advisor is for indexing recommendations.

Understanding these nuances will help you avoid mistakes. Finally, the exam may include questions about Azure SQL Database limitations. For instance, Query Store is always enabled in Azure SQL, but it has a maximum size.

If that size is reached, the feature may automatically change capture mode to none or auto. You need to know this behavior.

Study dp-300

Test your understanding with exam-style practice questions.

Practise

Example Scenario

A company called Contoso Books runs a large e-commerce website. The database is hosted on Azure SQL Database. One morning, the support team gets complaints that the product search page is taking over 10 seconds to load, compared to 2 seconds previously.

The database administrator, Priya, is asked to find the root cause. Priya knows that Query Store is enabled by default in Azure SQL Database. She opens SQL Server Management Studio, connects to the database, and navigates to the Query Store reports.

She selects the Top Resource Consuming Queries report for the last 24 hours. She sees that the most resource-intensive query is the product search query, and its average duration jumped from 2 seconds to 12 seconds about six hours ago, around the time a new index was added to the product table. She clicks on the query and looks at the plan summary.

She sees that the query has two different plans: Plan A, used before the index was added, and Plan B, used after. She examines Plan B and notices that the optimizer is using an inefficient scan of the new index instead of the previously efficient seek on the old index. Priya now has clear evidence of plan regression.

She can either report this to the development team to rewrite the query, or she can use Query Store’s plan forcing feature to force the database to keep using Plan A until the code is fixed. She chooses plan forcing. Immediately, the product search page returns to its previous performance of 2 seconds.

Priya then adds a note in the incident log referencing the Query Store data. This scenario demonstrates how Query Store enables fast, data-driven troubleshooting without guesswork. It directly maps to the kind of real-world problem DBAs face daily, and it shows exactly how Query Store’s features work in practice.

Common Mistakes

Thinking Query Store is only for on-premises SQL Server and does not apply to Azure SQL Database.

Query Store is a core feature of Azure SQL Database. In fact, it is enabled by default on all Azure SQL single databases and cannot be disabled. It works the same way as on-premises, with some additional cloud-specific management capabilities.

Remember that Query Store is available and recommended for both SQL Server (2016 and later) and Azure SQL Database. The DP-300 exam covers both environments.

Assuming that enabling Query Store will solve all performance problems without any additional analysis.

Query Store is a monitoring and troubleshooting tool, not a fix. It helps identify problems like plan regression, but it does not automatically tune queries. You still need to understand the data and apply fixes like updating statistics, rewriting queries, or forcing plans.

Use Query Store to find the problem, then use other tools like index tuning, query hints, or code changes to resolve it.

Confusing Query Store with Query Editor or the Query Performance Insight in Azure portal.

Query Editor is a tool for writing and running SQL queries interactively. Query Performance Insight is a separate Azure feature that provides aggregated query performance data, but it is not the same as Query Store, which stores detailed plan and runtime data at the database level.

Understand that Query Store is a low-level database feature that captures plans and stats. Query Performance Insight is a higher-level dashboard built on top of Query Store data.

Believing that Query Store captures statistics only when a query is compiled, not on every execution.

Query Store captures runtime statistics for every execution of a query, not just during compilation. It aggregates these statistics into intervals (default 60 minutes) and stores them in the runtime stats store. This includes metrics like CPU time, duration, and logical reads for each execution.

Know that Query Store monitors each execution and compiles the data over time. It is a continuous monitoring tool, not a one-time snapshot.

Thinking that plan forcing works immediately and permanently without any conditions.

Plan forcing works by storing a hint that the optimizer should always use a specific plan. However, if the plan becomes invalid (e.g., the underlying index is dropped), the force is ignored and the optimizer chooses a new plan. Also, plan forcing may not work for distributed queries or queries with certain features like CURSOR.

Check that the plan you are forcing is still valid and that the query type supports plan forcing. Monitor forced plans regularly to ensure they are still in use.

Exam Trap — Don't Get Fooled

A question states that Query Store is consuming too many resources and asks you to disable it to improve performance. The answer choices include disabling Query Store or configuring it to capture only expensive queries. Remember that Query Store has configuration options like CAPTURE_AUTO, which only captures queries that exceed a certain cost threshold.

You can also adjust the maximum size and data flush interval to reduce disk I/O and memory usage. Never disable Query Store to fix performance without first trying these settings. In Azure SQL, disabling is not an option anyway, so you must use configuration to manage overhead.

Commonly Confused With

Query StorevsDatabase Engine Tuning Advisor

The Database Engine Tuning Advisor analyzes a workload and recommends indexes, indexed views, or partitioning strategies to improve performance. Query Store, on the other hand, is a monitoring tool that captures query performance history and provides plan forcing. The Tuning Advisor is proactive, while Query Store is reactive and diagnostic.

If you need to find out why a query slowed down after an index change, use Query Store. If you need recommendations on which indexes to create to speed up queries, use the Database Engine Tuning Advisor.

Query StorevsSQL Server Profiler / Extended Events

SQL Server Profiler and Extended Events also capture query execution data, but they require manual setup, are session-based, and can be expensive to run continuously. Query Store is always on (once enabled), stores historical data in the database itself, and is designed for ongoing lightweight monitoring. Extended Events are better for ad-hoc deep analysis, while Query Store is meant for persistent monitoring.

Use Query Store to monitor all queries over time. Use Extended Events to trace a specific stored procedure or session for a few minutes during a targeted investigation.

Query StorevsAutomatic Tuning

Automatic Tuning is a feature in Azure SQL Database and SQL Server 2017+ that can automatically fix performance issues using data from Query Store. While Query Store provides the data, Automatic Tuning takes action, such as forcing a plan, creating or dropping indexes. Query Store is the information source, and Automatic Tuning is the automated solution.

Query Store shows that a query regressed. Automatic Tuning can automatically force the better plan if configured to do so. You can think of Query Store as the detective and Automatic Tuning as the police officer who acts on the detective's findings.

Query Storevssys.dm_exec_query_stats

sys.dm_exec_query_stats is a dynamic management view that shows aggregated performance statistics for cached query plans. It does not persist historical data after a server restart or plan eviction. Query Store persists data even after plan evictions and restarts, providing a longer history.

Use sys.dm_exec_query_stats for a quick snapshot of currently cached queries. Use Query Store when you need to look at query performance from last week or compare plans before and after a change.

Step-by-Step Breakdown

1

Enable Query Store

The first step is to enable Query Store on the target database. For SQL Server on-premises, you use ALTER DATABASE database_name SET QUERY_STORE = ON. For Azure SQL Database, it is already enabled by default. This step activates the feature, creating the internal tables that will store plan and runtime data.

2

Capture execution plans

Once enabled, Query Store automatically captures an execution plan each time a query is compiled or recompiled. It stores these plans in the plan store internal table. This includes the query text, query hash, plan hash, and the full plan XML. Every unique plan is stored, even if it is no longer in the cache.

3

Collect runtime statistics

For every query execution, Query Store records runtime metrics like CPU time, duration, logical reads, writes, and memory usage. It aggregates these into fixed time intervals (default 60 minutes) and stores them in the runtime stats store. This gives a historical view of how a query performed over time.

4

Identify plan changes

When a query runs at different times, it may use different execution plans. Query Store keeps all plans and their associated runtime statistics. By comparing the metrics across time intervals, you can see when a plan change occurred and whether it caused performance regression. This step is where the troubleshooting value emerges.

5

Force a specific plan

If a new plan causes slower performance, you can force the query to always use the previous, faster plan. This is done by calling sp_query_store_force_plan with the query ID and plan ID. The optimizer will then use that plan even if it normally would choose a different one. This restores performance instantly while you work on a permanent fix.

6

Monitor and maintain Query Store

Query Store has configurable settings like maximum size (in megabytes), data flush interval, and stale query threshold. You need to monitor its size to avoid filling the database with old data. If it reaches the maximum size, Query Store may automatically change to capture only queries that exceed a cost threshold or switch to read-only mode. Regular maintenance, like clearing old data via sp_query_store_cleanup, is recommended.

7

Analyze reports and DMVs

The final step is to use the built-in reports in SSMS or Azure portal, or query the system DMVs directly (sys.query_store_query, sys.query_store_plan, sys.query_store_runtime_stats). This analysis helps you understand overall database workload, identify top resource consumers, and track plan regressions over time. This step is where you turn raw data into actionable insights.

Practical Mini-Lesson

Query Store is one of the most valuable tools for database professionals because it turns an abstract problem—query performance degradation—into concrete, traceable evidence. As a beginner, your first task is to understand how to think about it. Do not treat Query Store as a magic fix.

Treat it as a camera that records everything. Your job is to review the footage. To get started, focus on the two core concepts: the plan store and the runtime stats store. The plan store is like a photo album of every route a query has ever taken through the database.

The runtime stats store is like a stopwatch that recorded how long each trip took. Together, they give you the full story. In practice, when a user reports a slow query, you do not want to run off and randomly add indexes.

Instead, open SSMS, right-click on the database, go to Reports, and choose Top Resource Consuming Queries from the Query Store section. You will see a chart showing which queries used the most resources in the last hour, the last day, or the last week. The chart is interactive.

Click on a bar to see details. You will see two lines: one representing the plan ID, one representing duration. If the bar is tall, you investigate. If you see that a query used plan ID 42 for three days with a duration of 2 seconds, and then suddenly switched to plan ID 57 with a duration of 15 seconds, you have found the regression.

The DP-300 exam expects you to know the exact DMV queries to run if the reports are not available. For instance, select * from sys.query_store_query to see all queries. Join with sys.

query_store_plan and sys.query_store_runtime_stats to get the full picture. A common real-world mistake is to assume that a longer duration always means a bad plan. It could be that the system was under heavy load at that time.

Query Store captures wait statistics too, so you can check if the query was waiting on I/O or locks. This level of detail is why the exam emphasizes Query Store. The practical lesson here is: when you face a performance issue, start with Query Store.

It is the fastest path to a root cause. Configure it carefully. By default, it captures all queries, which can add overhead on very busy systems. Change the capture mode to CAPTURE_AUTO if you are hitting performance limits.

Set the maximum size to something reasonable, like 200 MB for a moderate workload. This ensures you have enough history without filling the database. Also, remember that Query Store data is stored in the user database.

If you take a backup of the database, the Query Store data is included. That means you can restore the backup on a test server and analyze the performance history from that point in time. This is incredibly useful for post-mortem analysis.

For the exam, understand that Query Store is not just a feature but a methodology. Use it to validate whether changes you make, like adding an index or updating statistics, actually improve performance. Query Store will show you the before and after data, removing guesswork.

In advanced scenarios, you can use Query Store hints to apply query-level settings like MAXDOP or OPTIMIZE FOR without changing the application code. This is available in SQL Server 2022. For Azure SQL, you can use the Azure portal’s Query Performance Insight blade, which builds on Query Store data and provides additional visualization.

The bottom line is: Query Store is your first line of defense. Master its use, and you will save hours of troubleshooting time. It is not a niche tool; it is a core database administration skill tested on the DP-300 exam and used daily in the field.

Memory Tip

For the exam, remember the acronym QSP: Query Store captures Query plans, then Stats, then Performance history. Think of it as a 'flight recorder' that logs the Plan and the Stopwatch for each query.

Covered in These Exams

Related Glossary Terms

Frequently Asked Questions

Does Query Store work on every edition of SQL Server?

Query Store is available on SQL Server 2016 and later for the Enterprise, Standard, and Developer editions. It is also available on Azure SQL Database and Azure SQL Managed Instance. It is not available on SQL Server Express Edition or earlier versions than 2016.

Will enabling Query Store slow down my database?

Enabling Query Store does add some overhead because it captures and writes data for every query execution. The overhead is usually less than 5% on typical workloads. You can reduce the impact by setting the capture mode to CAPTURE_AUTO, which only captures queries that exceed a certain cost threshold. The default setting is ALL, so consider adjusting it for high-transaction OLTP systems.

How long does Query Store keep historical data?

The default retention period is 30 days, controlled by the STALE_QUERY_THRESHOLD_DAYS setting. You can change this to any value from 1 to 365 days. Data older than the threshold is automatically purged during a cleanup interval. You can also manually clean data using the sp_query_store_cleanup stored procedure.

Can I disable Query Store if I no longer need it?

Yes, you can disable Query Store on an on-premises SQL Server database using ALTER DATABASE SET QUERY_STORE = OFF. However, on Azure SQL Database single databases and Managed Instances, you cannot disable it. It is a required feature for the platform's diagnostic capabilities. You can only reset or configure it.

What is plan forcing and when should I use it?

Plan forcing allows you to tell SQL Server to always use a specific execution plan for a query, regardless of what the optimizer would normally choose. You should use it when Query Store shows that a new plan is causing performance regression and you need a quick fix. It is not recommended as a permanent solution unless the query code itself cannot be changed. Always aim to fix the underlying issue, such as updating statistics or rewriting the query.

How do I see the data collected by Query Store?

You can view Query Store data through several methods: use the built-in reports in SQL Server Management Studio under the database's Query Store folder, query the DMVs like sys.query_store_query and sys.query_store_plan, or use the Azure portal's Query Performance Insight blade for Azure SQL databases. The reports provide graphical views of top queries, plan changes, and resource consumption over time.

Can Query Store help with parameter sniffing problems?

Yes, parameter sniffing is a classic scenario where Query Store excels. When a query with parameters uses different plans for different parameter values, Query Store will show multiple plans for the same query. You can see which plan was used for which parameter value and how the performance differed. Then you can decide to force a plan, use the RECOMPILE hint, or use the OPTIMIZE FOR hint to resolve the issue.

Summary

Query Store is a powerful, built-in database feature that acts like a flight data recorder for SQL Server and Azure SQL Database. It automatically captures execution plans and runtime statistics for every query, storing a historical record that helps database administrators diagnose performance regressions, identify plan changes, and troubleshoot issues like parameter sniffing. For the DP-300 exam, you need to know how to enable Query Store, configure its settings, interpret its data through reports and DMVs, and use plan forcing to quickly restore performance when a query regresses.

Understanding the difference between Query Store and similar tools like the Database Engine Tuning Advisor or Extended Events is critical. Query Store is not a replacement for index tuning or query optimization, but it is the first place to look when performance changes unexpectedly. Remember that it is always enabled on Azure SQL Database, so knowing its configuration options is essential for cloud database administration.

By mastering Query Store, you gain the ability to turn performance problems from mysterious events into documented, solvable incidents. This skill is highly valued in the real world and directly tested on the DP-300 certification exam. Keep in mind the acronym QSP—Query plans, Stats, Performance—and use the built-in reports to make your analysis faster and more accurate.