Execution plans in SQL Server
A query execution plan is a set of instructions generated by a database engine that describes how it will execute a SQL query to access or modify data. For database developers, DBAs, and performance engineers, query profiling with execution plans helps identify bottlenecks, understand how SQL Server retrieves and processes data, and spot inefficient operations such as full table scans, expensive JOINs, and missing indexes. In this article, we explore how execution plans support SQL performance optimization and how dbForge Studio for SQL Server helps you analyze query execution and find ways to improve performance.
Understanding execution plans
Key takeaway: An execution plan represents all the steps SQL Server takes to execute a query and provide the requested result. It describes how the database engine processes the query: how it accesses tables and indexes, joins data, filters rows, and sorts results.
By analyzing an execution plan, you can understand why your query runs slowly. If you only measure the time required to complete the query, you may see some deviations, but the time alone does not show the root cause. An execution plan, however, can reveal bottlenecks like excessive scans or JOINs that take up excessive resources. This information suggests optimization opportunities that you can use to accelerate performance.
Components of execution plans
Execution plans typically consist of the following key components.
- Operators: These represent individual operations SQL Server performs to execute a query. Examples include table scans, index scans, JOINs, sorts, and aggregations. Analyzing operators allows you to identify expensive operations, such as full table scans.
- Data flow and operation order: In an execution plan, arrows show how data moves between operations, helping you understand their sequence and how intermediate results are processed.
- Data access methods: These indicate how SQL Server retrieves data from tables, for example, through index seeks, index scans, or table scans. They help determine whether SQL Server accesses data efficiently or reads more rows than necessary.
- Estimated vs actual metrics: Execution plans include estimates of the resources (such as CPU, memory, and disk I/O) required for each step based on statistics about the data distribution and database configuration. An actual execution plan also includes runtime details, such as actual rows processed, execution counts, and warnings where applicable. Differences between the estimated and actual results indicate estimation problems that affect the profiler results.
- Cost estimates: Execution plans include cost estimates associated with each step based on the model of resource consumption, primarily CPU and I/O. Graphical plans often display each operator's estimated cost as a percentage of the total estimated plan cost. This information helps you prioritize operations for investigation.
- Warnings: Execution plans may show warnings about inefficiencies, such as implicit conversions or missing indexes. Warnings should be used as clues for analyzing query performance.
Estimated vs. actual execution plans
An estimated query execution plan is intended to show what SQL Server would most likely do if it were to execute the query.
SQL Server estimates the number of rows that may be returned from tables. It also decides what operators to use for data retrieval: Index Scan, which scans index entries, or Index Seek, which uses index keys to locate rows within a specified range. It decides what to use to join tables together: nested loops, merge JOINs, or hash JOINs. Ultimately, you get the detailed plan of action that SQL Server will implement while executing an SQL query.
You can get an estimated plan for a specific query, stored procedure, or function. The plan comes in three different formats: text, XML, and graphical. If you need the text or XML formats, use the following commands: SET SHOWPLAN_TEXT ON and SET SHOWPLAN_XML ON, respectively.
Once the query is executed, you can get the actual query execution plan. This plan provides exact information about how many reads SQL Server performed, how many rows were read, and what joins were used.
There are some cases when SQL Server cannot create an estimated execution plan. For example, if you execute a query with parameters and the literal values are not passed in, SQL Server is unable to create the estimated plan. If the query references a temporary table that is not declared, the execution plan also cannot be created.
Comparing an estimated plan to an actual one can provide useful information. For example, an estimated execution plan can contain elements that are absent from the actual plan. For instance, the estimated plan shows a scalar-valued function call, while the actual plan does not.
Best tools to visualize and compare SQL Server execution plans
Key takeaway: While native tools like SSMS and Azure Data Studio provide basic plan viewing, specialized query profilers offer deep graphical analysis and plan comparison. Depending on your database environment, you can use dedicated SQL Server profilers like dbForge Studio and SQL Sentry Plan Explorer, cross-database IDEs like DBeaver for execution plan visualization, or dedicated web visualizers such as pgMustard for PostgreSQL EXPLAIN queries.
| Tool | Type | Plan features | Best For |
|---|---|---|---|
| dbForge Studio for SQL Server | GUI IDE | Query Profiler with a visual execution plan | Plan analysis inside an IDE |
| SSMS execution plan | Built-in | Estimated and actual plans, operator costs | Ad-hoc plan viewing |
| SQL Sentry Plan Explorer | Free tool | Rich plan visualization and plan comparison | Deep analysis and comparing plans |
| Azure Data Studio (discontinued) | Free, cross-platform | Execution plan viewer | Lightweight, cross-platform use |
| pgMustard / explain.dalibo | Web tools (PostgreSQL) | Visual EXPLAIN ANALYZE | PostgreSQL plan analysis |
| DBeaver | Cross-DB IDE | Execution plan visualization | Cross-database developers |
Generating execution plans
Key takeaway: Modern profiling tools, such as Query Profiler in dbForge Studio for SQL Server, allow you to create a visual diagram of your query execution, suggesting optimization opportunities.
Let's see how execution plans can be generated with a simple example. We will use dbForge Studio for SQL Server, a database management IDE that provides Query Profiler, a tool for profiling and analyzing SQL queries.
On the Start page, click Query Profiler. A new SQL document window opens.
Now, let's query the database for a list of employees whose job title is "Secretary". Enter the following query into the SQL editor window and click Execute.
SELECT
*
FROM HumanResources.Employee e
WHERE e.JobTitle = 'Secretary';
Query Profiler displays a Plan Diagram showing how the query is executed. The SELECT icon displays an exclamation mark indicating that certain shortcomings exist. Point to the exclamation mark to display full information. The tooltip contains a missing index warning.
A missing index forces the engine to perform a full table scan instead of searching for the requested data. To improve query performance, let's add a nonclustered index, as the warning suggests.
Open the Database Explorer and expand the Employee table. Right-click the Indexes folder and select New Index > Nonclustered Index.
In the Table Editor, navigate to the General tab of the index properties grid and select JobTitle in the Name column. This is the column to which we need to add an index.
Click Apply Changes to save the new index.
Now, let's see if the index we added has an impact on the query execution. Return to Query Profiler and click Get New Results. As you can see, the warning is no longer there.
Each time you get profiling results for the executed query, they appear in the tree view as a new node with the time and date of query execution. To compare results, hold the Ctrl key and select both plan diagrams.
This is a very simple example showing how you can profile queries in dbForge Studio for SQL Server. More complex queries that contain multiple JOINs, sorting, filtering, and nested subqueries can display significant performance improvements when the appropriate changes have been made.
Filtered indexes: Best practices and tools
Key takeaway: Filtered indexes speed up queries that repeatedly target a well-defined subset of rows.
Following SQL Server filtered indexes best practices can improve query performance and make index tuning more effective. As part of a broader performance tuning strategy, database administrators should evaluate filter conditions, index selectivity, and maintenance overhead.
In the previous example, we saw how a nonclustered index can be used to improve query performance. A filtered nonclustered index can improve it even further by reducing the scans only to the rows that specify a certain condition.
For example, if you need to frequently retrieve a list of active customers, create a filtered index as follows.
CREATE NONCLUSTERED INDEX IX_Customers_Active
ON dbo.Customers (CustomerID)
WHERE Status = 'Active';
This index contains only rows where Status = 'Active', making it smaller than a comparable unfiltered index when active customers represent a small portion of the table.
Then, query the database as follows:
SELECT CustomerID
FROM dbo.Customers
WHERE Status = 'Active';
Best practices for filtered index usage
- Watch for parameterization. A parameterized query such as WHERE Status = @Status may prevent SQL Server from using a filtered index for Status = 'Active', because the optimizer may not be able to guarantee that the parameter matches the filter at compilation time.
- Use filtered indexes for small, frequently queried subsets. The best use cases are active accounts, pending orders, or rows where a column is NOT NULL.
- Avoid creating many overlapping filtered indexes. Such indexes may cause maintenance overhead.
- Test performance with actual execution plans. Compare results and adjust the indexes as necessary.
Filtered index tuning tools
Below is a brief comparison of the most popular SQL Server filtered indexes tools for index tuning. They represent different types of tools designed for different purposes: GUI-based index management (dbForge Studio for SQL Server), built-in filtered index tuning tools (Query Store with the Database Engine Tuning Advisor), third-party tools (SQL Sentry, Redgate SQL Index Manager).
| Tool | Type | What it does for filtered indexes | Best For |
|---|---|---|---|
| dbForge Studio for SQL Server | GUI IDE | Create and manage filtered indexes visually | GUI creation and management |
| sp_BlitzIndex | Free script | Finds unused / missing indexes to filter | Index health analysis |
| Query Store + Database Engine Tuning Advisor | Built-in | Monitors usage and recommends indexes | Tuning and monitoring |
| SQL Sentry / Redgate SQL Index Manager | Third-party | Index management and monitoring | Enterprise tuning |
How to read a SQL Server execution plan
Key takeaway: To read an execution plan, start from the rightmost operator, follow the arrows to the left, and focus on the operators with the highest cost percentage.
Follow the steps below for more details on how to interpret execution plans provided by Query Profiler in dbForge Studio or other profiling tools.
Step 1. Read the plan from right to left
In a graphical execution plan, data typically flows from the rightmost operators toward the leftmost operator, where the final results are returned by the SELECT statement.
- Rightmost operators access the data, for example, through an Index Seek or Index Scan.
- Intermediate operators process the data through JOINs, filters, or sorts.
- Leftmost operator returns the final result and is typically represented by a SELECT statement.
Step 2. Find operators with high estimated costs
Look for operators with a high estimated operator cost (%). SQL Server's graphical plan shows each operator's estimated cost as a percentage of the total estimated cost of the plan. Specifically, pay attention to the following:
- Expensive scans over large tables or indexes.
- JOINs that process many rows.
- Sort operations that handle large data sets.
- Key Lookups that execute many times.
Step 3. Check for performance red flags
Evaluate operators that process large amounts of data. They are not necessarily suboptimal, but still deserve closer attention, for example:
- Table Scan: Full table scans may be too expensive when only a few rows are to be retrieved.
- Index Scan: Some indexes may need to be revised for better performance.
- Key Lookup: SQL Server retrieves additional columns not available in the nonclustered index. Many repeated lookups can increase I/O.
- Sort: Large sorts may consume too much memory.
- Spool: SQL Server stores intermediate results in a worktable or workfile, which may be expensive.
Step 4. Compare estimated and actual row counts
SQL Server estimates how many rows each operator will process. During execution, the actual plan records the number of rows processed. Significant differences can indicate that the optimizer's assumptions were inaccurate, which may lead SQL Server to choose an inefficient join strategy, allocate insufficient memory, or underestimate the cost of subsequent operations.
Compare estimates with actual row counts at multiple operators to locate where the discrepancy first appears. A mismatch does not automatically mean statistics are outdated; investigate the underlying cause before updating them.
Step 5. Check operator warnings
Look for warning icons on operators and inspect their properties for details. Common issues include:
- Spills to tempdb: A sort or hash operation could not complete entirely in memory.
- Implicit conversions: SQL Server converts data types during comparisons or other operations, potentially affecting index usage or cardinality estimates.
- Missing indexes: SQL Server identifies a possible index that could improve a particular query.
- Other execution warnings: Depending on the operator, the plan may expose additional runtime or optimization issues.
Step 6. Examine JOINs and data access together
If a query joins multiple tables, inspect the JOIN operators and the amount of data they process:
- Nested Loops: These may be effective when the outer input is small and the inner input can be accessed efficiently.
- Hash Match: They are suitable for larger inputs when the join condition supports hashing.
- Merge Join: Such JOINs can be efficient when both inputs are suitably ordered.
Then check how each input obtains its data. A costly JOIN may be caused by excessive rows entering it, a poor access method, or inaccurate estimates rather than the JOIN operator itself.
Step 7. Test one change at a time
Once you identify a likely cause, make a targeted change and compare the resulting execution plan and runtime metrics. If the result is still suboptimal, test another change.
Tuning queries using execution plans
Key takeaway: An execution plan shows potential improvements, while comparing the plans before and after a rewrite shows whether the change helped.
In the previous section, we reviewed how to generate an execution plan for a rather simple query that only requires a little optimization. Now, let's profile a more complex query and try to improve its performance with the help of dbForge Studio.
Open Query Profiler and execute the following query.
DECLARE @Name NVARCHAR(50)
SET @Name = 'll Crankarm'
SELECT
Name
,ProductNumber
,ListPrice
,SafetyStockLevel
FROM Production.Product
WHERE SafetyStockLevel > 500
UNION ALL
SELECT
Name
,ProductNumber
,ListPrice
,SafetyStockLevel
FROM Production.Product
WHERE UPPER(Name) = UPPER(@Name);
The Plan Diagram window opens:
According to the plan, SQL Server will first perform a clustered index scan to query the Production.Product table twice. Let's try to optimize it by removing the UNION ALL operator and the UPPER function, since we are querying the case-insensitive database.
As you can see, the second plan involves a single clustered index scan on the Production.Product table. Thus, we use fewer resources while performing only one scan.
Advanced topics in execution plans
Key takeaway: Query Profiler can help you not only optimize basic SQL query performance but also resolve more advanced tasks. It allows you to track differences in profiling results when executing the query several times.
With the tool, you can detect slow-running queries, examine the workload, and analyze bottlenecks to resolve performance issues in SQL databases. Profiling can also be used to investigate unexpected behavior of SQL queries and much more:
| Task | Description |
|---|---|
| Query analysis and optimization | Profiling helps analyze the performance of complex queries by providing detailed insights into their execution plans. This way, developers can identify inefficiencies, such as missing or inefficient indexes, suboptimal join strategies, or excessive resource consumption, and optimize the queries accordingly. |
| Visual representation | It is easier to comprehend and interpret complex query execution logic in a visual format. This visual representation helps developers identify areas for optimization more effectively. |
| Stored procedure and function profiling | Query Profiler supports profiling of stored procedures and functions. This allows for a thorough analysis of their execution plans and performance metrics. You can identify performance limitations, optimize resource usage, and improve overall database performance—all in one IDE. |
| Parameter sniffing analysis | Parameter sniffing is a common issue that can affect the performance of stored procedures and functions. dbForge Studio's Query Profiler can help identify instances of parameter sniffing by analyzing execution plans and providing recommendations for optimizing parameterized queries. |
| Real-time monitoring | The real-time monitoring capabilities of dbForge Studio can capture and analyze query execution plans and performance metrics as queries are executed. This enables developers to identify and address performance issues as they occur, rather than after the fact. |
Conclusion
The execution plan is an essential tool when developing SQL code. It will help you to understand why a specific query is slow or why one query runs faster than another. Both the graphical plans and the XML plans will give you all the data you need, and it's up to you to decide what to use and when. For those looking for a convenient solution to work with execution plans, dbForge Studio for SQL Server stands out as the premier tool. Its advanced features and intuitive interface make it a perfect choice for simplifying database maintenance workflows. To experience the benefits firsthand, download the free 30-day trial version of the Studio and optimize your database management processes today.
FAQ
Read an execution plan as follows:
- Read the plan from right to left to follow the typical data flow.
- Look for expensive operators; the plan shows the costs as percentages.
- Check for performance red flags such as full table scans, key lookups, or sorts.
- Compare estimated and actual row counts to evaluate the optimizer's assumptions.
- Check operator warnings to see improvement options.
- Examine JOINs and data access together to understand how data is obtained and processed.
- Test one change at a time and compare results by regenerating execution plans.
The following tools offer execution plan visualization and comparison features: dbForge Studio for SQL Server, SSMS execution plan, SQL Sentry Plan Explorer, DBeaver, Azure Data Studio, and pgMustard / explain.dalibo (for PostgreSQL databases).
If you are using filtered indexes, use the following best practices:
- Use filtered indexes for small, frequently queried subsets.
- Avoid creating many overlapping filtered indexes.
- Watch for parameterization.
- Test performance with actual execution plans.
For filtered index creation, use the following tools: dbForge Studio for SQL Server with GUI-based object editors, sp_BlitzIndex (an index analyzing tool), Query Store + Database Engine Tuning Advisor, and SQL Sentry / Redgate SQL Index Manager.