Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    SQL Server for .NET Developers: back to the course
    Lesson2 / 17

    Reading Actual Execution Plans: Operators, Estimates vs Actuals and Logical Reads

    Read an actual SQL Server execution plan by following row flow, comparing estimates with actual rows, and checking logical reads and warnings.

    An execution plan describes the steps SQL Server uses to run a query. It helps you connect a slow query to the work behind it: reading rows, finding matches, sorting, and returning results.

    This lesson builds on heaps, clustered indexes and B+ trees. You will learn which plan properties to inspect and how to check whether a change really reduces work.

    How do you capture an actual SQL Server execution plan?

    An estimated execution plan shows the plan SQL Server chooses without executing the query. Its row counts describe what SQL Server expects.

    An actual execution plan shows the plan SQL Server used, with runtime information such as actual resource usage metrics and runtime warnings. SQL Server generates it after execution.

    To capture an actual plan in SQL Server Management Studio (SSMS):

    1. Open a query window connected to a safe test database.
    2. Select Query → Include Actual Execution Plan.
    3. Execute the query.
    4. Open the Execution Plan tab. Select an operator and open Properties to inspect its details.

    Capturing an actual plan executes the SQL, including writes. It is not a safe preview of an UPDATE, DELETE, or stored procedure.

    Alternatively, SET STATISTICS XML ON returns plan information after execution. In SSMS, turn off Include Actual Execution Plan when using this alternative; otherwise the XML result is not returned separately.

    Run this T-SQL example in SQL Server, not the C# console runner. Keep the query window open for the later example.

    Before running it, predict how many orders have CustomerId = 7. Do not predict a particular operator yet.

    SQL
    CREATE TABLE #Orders
    (
        OrderId int NOT NULL PRIMARY KEY CLUSTERED,
        CustomerId int NOT NULL,
        Total decimal(10, 2) NOT NULL
    );
    
    ;WITH Digits AS
    (
        SELECT n
        FROM (VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) AS d(n)
    )
    INSERT #Orders (OrderId, CustomerId, Total)
    SELECT number.n,
           number.n % 25,
           CAST(number.n AS decimal(10, 2))
    FROM Digits AS a
    CROSS JOIN Digits AS b
    CROSS JOIN Digits AS c
    CROSS APPLY
    (
        VALUES (1 + a.n + 10 * b.n + 100 * c.n)
    ) AS number(n);
    
    CREATE INDEX IX_Orders_CustomerId ON #Orders(CustomerId);
    
    SET STATISTICS IO ON;
    SET STATISTICS TIME ON;
    SET STATISTICS XML ON;
    
    SELECT OrderId, Total
    FROM #Orders
    WHERE CustomerId = 7;
    
    SET STATISTICS XML OFF;
    SET STATISTICS TIME OFF;
    SET STATISTICS IO OFF;

    The insert creates 1,000 orders. The remainder calculation assigns 40 orders to each of 25 customer IDs. The SELECT therefore returns 40 rows.

    In an interview, say: “An estimated plan does not execute the query. An actual plan describes the executed plan with runtime rows, executions, and warnings. Capturing it executes writes too. Its displayed costs are still estimates.”

    How do you read execution plan operators?

    A physical operator is an implementation of one step, such as reading an index or sorting rows. In a graphical SQL Server plan, arrows show rows flowing right to left.

    This sketch is illustrative, not a promised plan for the sample:

    flowchart TD
        S["Index access"] -->|supplies rows| O["Sort"]
        O -->|supplies ordered rows| T["Top"]
        T -->|returns rows| R["Query result"]

    Use this vocabulary when inspecting operators:

    OperatorWhat it does
    Index SeekNavigates to an index key or range, then reads qualifying index entries.
    Index Scan / Clustered Index ScanReads the index from start to end, or a large part of it, instead of jumping to the needed keys.
    Table ScanReads rows from a heap.
    Key LookupGoes back to the clustered index to fetch columns that a nonclustered index does not contain.
    RID LookupFetches a heap row using its row identifier.
    SortArranges rows in the required order, using working memory and potentially disk space.
    TopReturns only the requested number or percentage of rows.
    Stream AggregateCalculates group totals from rows already sorted by the GROUP BY columns.
    Hash Match (Aggregate)Uses an in-memory hash table to collect groups, without requiring ordered input.
    ParallelismExchanges rows between worker threads, splitting, redistributing, or gathering them.

    A scan is not automatically bad. If the query needs most rows, scanning may cost less than many separate accesses. A Top can stop a scan once enough rows arrive, unless intervening work requires reading everything first.

    A seek is not automatically small. It can seek to the start of a wide range and read many rows. Where available, compare Actual Number of Rows Read with rows returned. A large difference means the access examined many rows it did not pass onward.

    In an interview, say: “An index scan is not always bad. It can be cheaper when many rows are needed, and Top can stop it early. A seek can still read many rows. I compare rows read, rows returned, and logical reads.”

    The next lesson explains lookups and covering indexes.

    Nested Loops vs Hash Match vs Merge Join

    A SQL join describes which rows should match. SQL Server chooses a physical join operator to perform that work.

    Nested Loops takes a row from its outer input and searches its inner input for matches. For example, 10 customers might cause 10 searches in an orders index. This often works well for a small outer input and an efficient inner search. It needs no sorted inputs or large hash table, but repeated searches become costly as the outer input grows.

    Hash Match builds a hash table from one input, then probes it with rows from the other input. It does not require sorted inputs and can suit large, unordered inputs. The hash table needs memory. If its working data does not fit, SQL Server may write some of it to disk, called a spill.

    Merge Join walks two inputs ordered by the join keys, advancing through matching values. Existing index order can make this efficient. If either input needs a Sort first, that preparation can outweigh the benefit.

    In an interview, say: “Nested Loops repeatedly probes the inner input and often suits a small outer input. Hash Match builds and probes a hash table, needs memory, and can spill. Merge Join needs ordered inputs; sorting them may outweigh its benefit.”

    How do you compare estimated rows with actual rows?

    Start at the data-access ends of the plan and follow rows toward the result. Look for the first important gap between expected and actual row counts, rather than only a large difference near the result.

    For example, an access estimated at 10 rows might return 100,000. A join above it then receives far more input than expected. The join's workload may be a consequence, not the first problem.

    Before comparing two numbers, check whether each one counts one execution or all executions together. In SSMS, look for Estimated Number of Rows Per Execution and Actual Number of Rows for All Executions.

    Consider this illustrative serial lookup example, where serial means it does not use parallel worker threads:

    Lookup propertyValue
    Estimated rows per execution1
    Estimated executions40
    Actual rows across all executions40
    Actual executions40

    Here, 40 / 40 = 1 actual row per execution. The row estimate agrees with the observation. Comparing 1 directly with 40 would invent a problem.

    Separately compare estimated and actual execution counts. If SQL Server expected one execution but performed 40, the repeated-work estimate was wrong even if each lookup returned exactly one row.

    For parallel operators, inspect the per-thread runtime counters separately. Row distribution can be uneven.

    In an interview, say: “I follow row flow, find expensive accesses using logical reads, and locate the first significant estimate-versus-actual gap. I check executions and warnings too. Inside loops, 40 total rows over 40 executions agrees with one estimated row per probe.”

    For the causes of poor row estimates, continue with statistics and cardinality estimates. Cardinality means the number of rows an operation produces.

    What do logical reads, CPU and duration tell you?

    SET STATISTICS IO ON reports:

    • Logical reads: number of pages read from the data cache.
    • Physical reads: pages read from disk.
    • Read-ahead reads: pages brought into the cache in anticipation of use.

    Return to the 40-row #Orders query. In SSMS, open Messages and find its STATISTICS IO message. An illustrative excerpt is Table '#Orders...'. Scan count 1, logical reads 6, physical reads 0, read-ahead reads 0. The temporary table's full name and your counts can differ.

    • Scan count 1 means one seek or scan started at the index's lowest level, where its row entries are stored. It does not mean one row was read.
    • Logical reads 6 means six page reads from the data cache, not six returned rows or necessarily six distinct pages.

    Now inspect the plan for that same SELECT, rather than the insert or index creation. Select each data-access operator and open Properties:

    PropertyWhat to check in this sample
    Actual Number of RowsThe query returns 40 rows. A scan with the filter inside it may return those 40; a scan followed by a separate Filter may pass all 1,000 rows to that Filter.
    Estimated Number of Rows Per ExecutionRecord SQL Server's prediction.
    Number of ExecutionsCheck how often the access ran. If the plan uses a serial Key Lookup once for each matching order, expect 40 lookup executions and 40 total lookup rows.

    Your plan may choose a scan instead of a seek and lookups.

    In recent versions, an actual plan's operator Properties also show Actual I/O Statistics and Actual Time Statistics, including per-thread counters. Look for Actual Logical Reads, Actual Elapsed Time, and Actual CPU Time where available.

    SET STATISTICS TIME ON adds CPU time, the processor time used, and elapsed time, the wall-clock duration.

    The percentage displayed on a plan operator is different. It is the optimizer's estimated relative cost. Even in an actual plan, that percentage is not measured runtime.

    When testing a change, keep the query parameters and returned results comparable. Check logical reads, CPU, and elapsed time together; one faster run is weak evidence.

    In an interview, say: “Logical reads count cached-page accesses, including repeats, by object—not unique pages or elapsed time. A warm cache can reduce physical reads without reducing logical reads. Plan cost percentages are estimates, so I investigate with actual rows, executions, warnings, reads, CPU, and duration.”

    What do execution plan warnings and memory grants mean?

    Warnings are clues to inspect, not diagnoses to accept without context.

    Warning or clueWhat to investigate
    Implicit conversionSQL Server changes a value's type automatically. Inspect whether the conversion affects index access or row estimation. Not every conversion is harmful.
    Missing statisticsStatistics describe data distribution for estimation. Missing information can leave SQL Server with a weaker row-count estimate.
    Sort or hash spillSome working data was written to tempdb, SQL Server's database for temporary work. Inspect the spill details and memory use.

    Inspect the plan's memory grant by comparing the memory requested, granted, and actually used, where those properties are available. Too little usable memory can contribute to spills. An excessive grant can reserve memory other queries need.

    A missing-index suggestion is a guess made during optimization, not proof that the index helps the whole workload.

    In an interview, say: “I inspect warning details for conversions, missing statistics, and sort or hash spills. Spills use tempdb, so I check memory grants and estimates. Missing-index suggestions are evidence to validate, not instructions to accept automatically.”

    Continue with index design or implicit conversions when those are your next clues.

    How do you capture an actual plan for an EF Core query?

    First capture the SQL EF Core actually executes, its parameter values, and the matching parameter definitions. Use the existing lesson on EF Core SQL capture and logging for that step.

    Preserve parameter types, lengths, precision, and scale. Replacing a parameter with a literal or declaring a different type can change the plan you are investigating.

    sp_executesql executes SQL text with separately declared parameters. Here, int matches the CustomerId column.

    SQL
    SET STATISTICS XML ON;
    
    EXEC sys.sp_executesql
        N'SELECT OrderId, Total
          FROM #Orders
          WHERE CustomerId = @CustomerId;',
        N'@CustomerId int',
        @CustomerId = 7;
    
    SET STATISTICS XML OFF;

    Query Store automatically captures a history of queries, plans, and runtime statistics for later review. Finding a stored plan there is useful, but it is not the same as capturing an actual plan with per-operator runtime counters for one execution.

    In an interview, say: “I capture the executed EF Core SQL and matching parameter definitions, then collect an actual plan for a controlled replay. Query Store helps me find historical plans and runtime trends, but a stored plan is not a per-execution actual plan.”

    The course's tuning workflow continues from these observations to testing a fix.

    Check yourself

    A serial lookup estimates one row per execution. It produces 40 actual rows across 40 executions. What should you conclude first?

    A Its estimate is 40 times too low: the plan expected 1 row and the lookup returned 40.
    B The 40 executions show Nested Loops was a poor choice that should be forced to Hash Match.
    C Its rows per execution agree; compare estimated and actual execution counts separately.
    D The lookup read exactly 40 pages, so its logical reads equal its actual row count.
    Show answer

    Correct answer: C

    Forty total rows across forty executions averages one row per execution. Execution-count estimates and page accesses are separate questions.

    An operator shows 80% cost in an actual execution plan. What does that percentage mean?

    A It is an estimated relative cost from the optimizer, not measured runtime.
    B It is the share of elapsed time the operator used, measured while the query ran.
    C It is the operator's share of the physical reads recorded during that execution.
    D It marks the operator to tune first, because it did 80% of the query's actual work.
    Show answer

    Correct answer: A

    Actual plans retain estimated costs. Use runtime counters, warnings, logical reads, CPU, and elapsed time to investigate the work.

    Going deeper

    Batch mode processes groups of rows together instead of processing one row at a time. It can reduce CPU work for suitable queries.

    An Adaptive Join can choose between Hash Match and Nested Loops during execution, using the observed input row count and a threshold shown in the plan. This is a batch-mode feature, not a promise that every join adapts.

    A database's compatibility level selects a set of query-processing behaviors independently of the installed SQL Server version.

    FeatureSQL Server and Azure SQL Database availability
    Batch-mode Adaptive JoinsSQL Server 2017 and later, including 2022 and 2025, at compatibility level 140 or higher; also supported in Azure SQL Database at level 140 or higher.
    Batch mode on rowstoreSQL Server 2019 and later, including 2022 and 2025, at compatibility level 150 or higher; also supported in Azure SQL Database at level 150 or higher.

    In SQL Server 2017, batch mode, and therefore Adaptive Join, needs a columnstore index in the query. From SQL Server 2019 at compatibility level 150, batch mode on rowstore can also give Adaptive Joins on ordinary tables.

    Edition matters too. In SQL Server 2017 through 2025, Adaptive Joins and batch mode on rowstore are Enterprise-edition features (also in the Developer and Evaluation editions that include Enterprise features). Check edition support for your installed release; version and compatibility level alone are not enough.

    The features must be enabled, and the optimizer must judge batch processing worthwhile. Large inputs, joins, and aggregates are examples of work that can benefit; a small query may still use row mode.

    Check the operator's Actual Execution Mode property, which shows Row or Batch. For an Adaptive Join, also inspect its runtime join choice rather than assuming either choice from the server version.

    Sources

    Sign in to mark lessons done and keep your place in the course.Sign in

    Checked before publishing: links opened, reviewed while it was written and read in full. How lessons are checked

    Updated 30 Nov 2026 ·