SQL Server execution plan analysis

A SQL Server execution plan is a tree of operators, and internally it is XML (Showplan XML). The estimated execution plan shows the plan the optimizer chose, with estimated row counts and costs, without running the statement. The actual execution plan runs the statement and then attaches the actual row count, number of executions, logical reads, and elapsed time to each operator. Tuning means finding, in the actual execution plan, the operators that did a lot of work and the operators whose estimates were far off.

Summary

ItemDescription
Estimated planSET SHOWPLAN_XML ON (does not run the statement). Ctrl+L in SSMS
Actual planRun after SET STATISTICS XML ON. Ctrl+M in SSMS
During executionLive Query Statistics (SSMS), sys.dm_exec_query_profiles
Plan cachesys.dm_exec_query_stats + sys.dm_exec_query_plan(plan_handle). Execution statistics are cumulative, and the plan has no actual values
HistoryQuery Store (sys.query_store_*). From 2022, on by default for new databases. Plan forcing (sp_query_store_force_plan)
Text statisticsSET STATISTICS IO ON (logical, physical, and read-ahead reads per table), SET STATISTICS TIME ON (compile and execution CPU and elapsed time)
SandboxShows the actual plan from SET STATISTICS XML ON as a table. Buffers = the operator's ActualLogicalReads + the sum of its children

Reading direction

This is the actual plan from the sandbox for a query of the last 7 days of orders for VIP customers (the table in the sandbox Plan tab is indented from top to bottom, like Oracle).

OperatorExecutionsEstimated rows (per execution)Actual rows (total)Buffers
Nested Loops (Inner Join)11401443,605
├ Clustered Index Scan customers_pk11,0001,000601
└ Nested Loops (Inner Join)1,00011443,004
  ├ Compute Scalar ← Constant Scan1,00011,0000
  └ Index Seek orders_x11,00011443,004
  • In the SSMS diagram, data flows from right to left. The leftmost node (SELECT) is the result, and the operator at the far right produces rows first.
  • The upper input of a join operator is the outer input and the lower input is the inner input. The inner side of an NL join runs once per outer row, so its number of executions equals the number of outer rows.
  • Constant Scan + Compute Scalar is the part that produces the range values for the Seek. It has no cost.
  • In the plan above, orders_x1(cust_id, ord_dt) also contains ord_id (the clustered key), so there is no Key Lookup.

Operator properties

When you click an operator in SSMS, the properties window shows the values below. The sandbox shows the same values as table columns.

PropertyMeaningWhat to look for
Number of ExecutionsNumber of executions (Oracle's Starts)Large on the NL inner side and in Key Lookup
Estimated Number of RowsEstimated rows per single execution (shown as "Estimated Number of Rows Per Execution" from SSMS 18)When comparing, multiply by the number of executions
Actual Number of RowsSum over all executionsCompare with estimated × number of executions
Estimated / Actual Rows to be ReadNumber of rows read (2016 SP1+)If much larger than the actual rows, the Predicate discards a lot
Actual Logical ReadsPages the operator readThe operator's own share of the sandbox Buffers
Seek PredicatesConditions that set the index seek range (Oracle's access)
PredicateConditions filtered after reading (Oracle's filter)The gap between Rows to be Read and Actual Rows is the amount discarded
Probe Residual / Hash KeysThe hash join's keys and the remaining non-key conditions
Ordered / Scan DirectionWhether the index was read in order / FORWARD or BACKWARDSkipping the sort for Top-N

Statement-level properties and warnings

The SELECT operator at the top of the plan (QueryPlan and StmtSimple in Showplan XML) holds information for the whole statement.

PropertyMeaning
CardinalityEstimationModelVersionCardinality estimator version. 70 means the old estimator, 120 or above means the new estimator (Statistics)
StatementOptmLevel / StatementOptmEarlyAbortReasonTRIVIAL means the plan was chosen without cost comparison. GoodEnoughPlanFound or TimeOut means the search stopped partway
MemoryGrantInfo (GrantedMemory, MaxUsedMemory)Memory granted for sorts and hashes, and the memory actually used. A large gap indicates an estimation error
QueryTimeStats (CpuTime, ElapsedTime)The statement's CPU and elapsed time (ms)
OptimizerStatsUsage (2017+)The statistics objects used to build this plan and their update times
ParameterListThe value sniffed at compile time (ParameterCompiledValue) and the value at execution time (ParameterRuntimeValue). If they differ, suspect parameter sniffing

Warnings appear as the yellow triangle on an operator icon or as Warnings elements. The sandbox shows them at the top of the Raw tab.

WarningMeaning
PlanAffectingConvertAn implicit conversion blocked a Seek or blurred the estimate (Scenario 21)
SpillToTempDb (Sort, Hash)Exceeded the granted memory and spilled to tempdb
MemoryGrantWarningThe granted memory is excessively large or small
NoJoinPredicateA join with no join condition (Cartesian product)
ColumnsWithNoStatisticsThe estimate was made on a column that has no statistics

SET STATISTICS IO, TIME

SET STATISTICS IO, TIME ON;
SELECT …;
-- Table 'orders'. Scan count 1000, logical reads 3004, physical reads 0, read-ahead reads 0, …
-- Table 'customers'. Scan count 1, logical reads 601, …
--  SQL Server Execution Times: CPU time = 5 ms,  elapsed time = 5 ms.
ItemMeaning
Scan countNumber of times that table (index) was seeked or scanned. On the NL inner side, the number of outer rows
logical readsPages read from the buffer pool
physical reads / read-ahead readsPages read from disk / pages read ahead
WorktableReads of the work table that a spool, sort, or hash creates in tempdb

The order to check in practice

  1. Find the operator with the most logical reads. Even within the same table, look at places like Key Lookup where the cost grows to number of executions × 3 pages.
  2. Find the rightmost operator (the one that runs first) where estimated rows × executions and actual rows diverge by 10 times or more. Look at the statistics it used (OptimizerStatsUsage).
  3. Use the gap between Rows to be Read and Actual Rows to see how much the Predicate discarded. Look for a way to move it into the Seek Predicate (index column order, shape of the condition).
  4. Check the memory grant, SpillToTempDb, and conversion warnings.
  5. If the statement has parameters, compare the compile value with the execution value. Run it again with several representative values.

Comparison with other DBMSs

ItemSQL ServerOraclePostgreSQL
Actual planSET STATISTICS XML ONDISPLAY_CURSOR … ALLSTATS LASTEXPLAIN (ANALYZE, BUFFERS)
Number of executionsNumber of ExecutionsStartsloops
Estimated rowsPer executionPer executionPer execution
Actual rowsTotalTotalAverage per execution
ConditionsSeek Predicates / Predicateaccess / filterIndex Cond / Filter
Plan history and pinningQuery StoreAWR, SQL Plan BaselineNone (pg_stat_statements has no plans)

See also: Oracle execution plan analysis, PostgreSQL execution plan analysis, Join methods.

NOTE The SSMS display and the Showplan XML properties grow with each version. The plans in this document are from SQL Server 2022 (compatibility level 160) in the sandbox.

Related pages