Skip to content

Execution Plans in SQL Server

When a query is slow, the first question is not "how do I rewrite it?" but "what is SQL Server actually doing?". The answer is the execution plan: the step-by-step recipe SQL Server chooses to get your data. It shows which tables and indexes are read, how rows are joined and sorted, how many rows flow between steps, and where the cost is.

In this lesson you build a 100,000-row table, look at its execution plans, measure the work with STATISTICS IO and STATISTICS TIME, add an index, and watch the plan change. Every output on this page comes from a real run on SQL Server 2025.

Think of a GPS. You give the destination (your SELECT); the GPS (the query optimizer) picks a route: highway or side streets. The execution plan is that route. A slow query is often a bad route, for example reading the whole city (a scan) when you only needed one street (a seek).

How SQL Server runs a query

Your SQL  ->  Parse (syntax check)
          ->  Bind (do the tables and columns exist?)
          ->  Optimize (the optimizer compares possible plans using statistics
                        and picks the cheapest ESTIMATED one)
          ->  Execute the plan  ->  Results

The optimizer is cost-based: it estimates how many rows each step will produce, using statistics about your data, and picks the plan with the lowest estimated cost. Plans are cached and reused, so the same query does not have to be optimised every time.

Estimated vs actual execution plan

Estimated planActual plan
SSMS shortcutCtrl + L (Display Estimated Execution Plan)Ctrl + M (Include Actual Execution Plan), then run the query
Runs the query?NoYes
Row countsEstimated onlyEstimated and actual rows for every operator
Use it forLong or dangerous queries (big UPDATE/DELETE) you don't want to runReal tuning: compare estimated and actual rows, see warnings

Ctrl + M is a toggle: once switched on, every query you run in that window also opens an Execution plan tab next to Results and Messages.

Step 1: Create the demo table

USE EmployeeDB;
GO

CREATE TABLE EmployeePerformanceDemo
(
    EmployeeId INT IDENTITY(1,1) PRIMARY KEY,
    EmployeeName VARCHAR(100),
    City VARCHAR(50),
    Department VARCHAR(50),
    Salary DECIMAL(18,2)
);
GO

The PRIMARY KEY creates a clustered index on EmployeeId: the table's rows are stored in EmployeeId order. There is no index on City yet.

Step 2: Insert 100,000 rows

INSERT INTO EmployeePerformanceDemo
(
    EmployeeName,
    City,
    Department,
    Salary
)
SELECT TOP (100000)
    CONCAT('Employee', ROW_NUMBER() OVER (ORDER BY (SELECT NULL))),
    CASE
        WHEN ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) % 100 = 0
        THEN 'Indore'
        ELSE 'Mumbai'
    END,
    CASE
        WHEN ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) % 3 = 0
        THEN 'IT'
        WHEN ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) % 3 = 1
        THEN 'HR'
        ELSE 'Finance'
    END,
    30000 + (ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) % 70000)
FROM sys.all_objects a
CROSS JOIN sys.all_objects b;
GO

sys.all_objects is a system view with a few thousand rows; joining it to itself (CROSS JOIN) produces millions of row combinations, and TOP (100000) keeps the first 100,000. Every 100th employee lives in Indore, the rest in Mumbai, so a search for Indore returns just 1% of the table. That's exactly the kind of query an index helps.

On a laptop with little free memory this insert can take a few minutes. It's a one-time setup step.

Step 3: Check the data

SELECT COUNT(*) AS TotalEmployees
FROM EmployeePerformanceDemo;

SELECT City, COUNT(*) AS Employees
FROM EmployeePerformanceDemo
GROUP BY City;
Output
TotalEmployees
100000
CityEmployees
Indore1000
Mumbai99000

Step 4: Turn on the execution plan

  • Ctrl + L: show the estimated plan for the selected query without running it.
  • Ctrl + M: include the actual plan, then press F5 to run the query.

Step 5: The query we will tune

SELECT
    EmployeeId,
    EmployeeName,
    City
FROM EmployeePerformanceDemo
WHERE City = 'Indore';
Output (first rows of 1,000)
EmployeeIdEmployeeNameCity
100Employee100Indore
200Employee200Indore
300Employee300Indore

In the Execution plan tab, SSMS draws the plan as icons connected by arrows. This plan has one operator: a Clustered Index Scan. You can see the same plan as text (which is what we use on this page, so you can compare exactly):

SET SHOWPLAN_TEXT ON;
GO
SELECT EmployeeId, EmployeeName, City
FROM EmployeePerformanceDemo
WHERE City = 'Indore';
GO
SET SHOWPLAN_TEXT OFF;
GO
Output
  |--Clustered Index Scan(OBJECT:([...].[dbo].[EmployeePerformanceDemo].[PK__Employee__7AD04F11...]),
       WHERE:([...].[dbo].[EmployeePerformanceDemo].[City]=[@1]))

A Clustered Index Scan reads every row of the table and checks City = 'Indore' on each one. With no index on City, SQL Server has no other choice. ([@1] means SQL Server auto-parameterised the literal 'Indore' so the plan can be reused.)

How to read a graphical plan

  • Read from right to left (and top to bottom). The rightmost operators read data; the leftmost (SELECT) returns it.
  • Arrow thickness shows how many rows flow between operators. A very thick arrow into an operator that outputs few rows means a lot of wasted reading.
  • Cost % under each operator shows its share of the estimated cost. Start with the most expensive one.
  • Hover over an operator to see estimated vs actual rows, logical reads and the predicate. A big difference between estimated and actual rows usually means outdated statistics.
  • Yellow warning triangles flag problems such as implicit conversions or spills to tempdb. Green text above the plan is a missing-index suggestion.

Step 6: Measure the work with STATISTICS IO and TIME

The plan shows how; these two settings show how much. The numbers appear in the Messages tab.

SET STATISTICS IO ON;
SET STATISTICS TIME ON;

SELECT *
FROM EmployeePerformanceDemo
WHERE City = 'Indore';

SET STATISTICS IO OFF;
SET STATISTICS TIME OFF;
Messages (warm cache)
Table 'EmployeePerformanceDemo'. Scan count 1, logical reads 657, physical reads 0, read-ahead reads 0, ...

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 6 ms.
ValueMeaning
logical reads8 KB pages read from memory. The most useful number for tuning: it doesn't change with server load or cache state. 657 pages = the whole table.
physical reads / read-ahead readsPages that first had to be read from disk. These are high on the first run and 0 once the data is cached.
Scan countHow many times the table or index was accessed
CPU time / elapsed timeProcessor time and wall-clock time. They vary from run to run, so compare several runs.

Why logical reads matter more than time: on our test laptop, the very first run of this query (with an empty cache and the machine short of memory) took 222 seconds to read 653 pages from disk. The same query on a warm cache took 6 ms. Both read exactly 657 logical pages. Tune for fewer logical reads, and time improves everywhere.

Step 7: The plan as XML (SHOWPLAN_XML)

SET SHOWPLAN_XML ON;
GO

SELECT *
FROM EmployeePerformanceDemo
WHERE City = 'Indore';
GO

SET SHOWPLAN_XML OFF;
GO

Instead of running the query, SQL Server returns the full estimated plan as one XML document (133 KB here). In SSMS, click the XML link to open it as a graphical plan. This is the same file you get from right-click the plan > Save Execution Plan As (.sqlplan), which is the best way to share a plan with a colleague. Key parts of the real XML:

Output (excerpt)
<ShowPlanXML ... Version="1.599" Build="17.0.1000.7">
...
<RelOp NodeId="0" PhysicalOp="Clustered Index Scan" LogicalOp="Clustered Index Scan"
       EstimateRows="1000" EstimatedRowsRead="100000" EstimatedTotalSubtreeCost="0.596245"
       TableCardinality="100000" ...>

EstimatedRowsRead="100000" for EstimateRows="1000": SQL Server expects to read 100 rows for every row it returns. That ratio is a classic sign of a missing index.

The missing-index suggestion

When the optimizer thinks an index would help, it writes a suggestion into the plan (shown as green text in SSMS). For a query on WHERE Department = 'HR' AND Salary = 99999 the real plan contained:

Output (excerpt)
<MissingIndexes>
  <MissingIndexGroup Impact="99.435">
    <MissingIndex Database="[...]" Schema="[dbo]" Table="[EmployeePerformanceDemo]">
      <ColumnGroup Usage="EQUALITY">
        <Column Name="[Department]" ColumnId="4" />
        <Column Name="[Salary]" ColumnId="5" />

"Impact 99.4" means the optimizer estimates the query would be 99.4% cheaper with that index. Treat suggestions as hints, not orders: they ignore your other queries, the cost of maintaining the index during INSERT/UPDATE, and similar existing indexes.

Step 8: Add an index and compare

CREATE NONCLUSTERED INDEX IX_Employee_City
ON EmployeePerformanceDemo(City);
GO

A nonclustered index on City is a separate, sorted list of City values, each with the row's EmployeeId (the clustered key) as a pointer back to the table.

A query that only needs index columns: Index Seek

SET STATISTICS IO ON;
SELECT EmployeeId, City
FROM EmployeePerformanceDemo
WHERE City = 'Indore';
Plan and Messages
  |--Index Seek(OBJECT:([...].[IX_Employee_City]), SEEK:([...].[City]=[@1]) ORDERED FORWARD)

Table 'EmployeePerformanceDemo'. Scan count 1, logical reads 6, ...

6 logical reads instead of 657. An Index Seek jumps straight to the Indore entries in the sorted index and reads only those. Everything the query needs (EmployeeId and City) is in the index.

The surprise: the original query still scans

Run the Step 5 query again, which also returns EmployeeName:

Plan and Messages
  |--Clustered Index Scan(OBJECT:([...].[PK__Employee__...]), WHERE:([...].[City]='Indore'))

Table 'EmployeePerformanceDemo'. Scan count 1, logical reads 657, ...

The index exists, but SQL Server ignores it. Why? EmployeeName is not in the index, so for each of the 1,000 matching rows SQL Server would have to jump back into the table to fetch it. That jump is called a Key Lookup. Let's force the index to see what it would cost:

SELECT EmployeeId, EmployeeName, City
FROM EmployeePerformanceDemo WITH (INDEX(IX_Employee_City))
WHERE City = 'Indore';
Plan and Messages
  |--Nested Loops(Inner Join, OUTER REFERENCES:([...].[EmployeeId]) WITH UNORDERED PREFETCH)
       |--Index Seek(OBJECT:([...].[IX_Employee_City]), SEEK:([...].[City]='Indore') ORDERED FORWARD)
       |--Clustered Index Seek(OBJECT:([...].[PK__Employee__...]),
            SEEK:([...].[EmployeeId]=[...].[EmployeeId]) LOOKUP ORDERED FORWARD)

Table 'EmployeePerformanceDemo'. Scan count 1, logical reads 5055, ...

5,055 logical reads, almost eight times more than the scan. The seek is cheap, but 1,000 separate lookups (the "LOOKUP" seek, shown as Key Lookup in the graphical plan) cost about 5 pages each. The optimizer correctly predicted this and chose the scan. This point, where lookups become more expensive than scanning, is called the tipping point. It is often surprisingly low: here just 1% of the rows.

Lesson: an index on the WHERE column is not enough if the query needs other columns. Don't force indexes with hints; fix the index instead.

The fix: a covering index

CREATE NONCLUSTERED INDEX IX_Employee_City_Covering
ON EmployeePerformanceDemo(City)
INCLUDE (EmployeeName);
GO

INCLUDE stores EmployeeName in the index's leaf level (not in the sort key). Now the index "covers" the query: everything it needs is in the index.

Plan and Messages
  |--Index Seek(OBJECT:([...].[IX_Employee_City_Covering]), SEEK:([...].[City]='Indore') ORDERED FORWARD)

Table 'EmployeePerformanceDemo'. Scan count 1, logical reads 8, ...

 SQL Server Execution Times:
   CPU time = 16 ms,  elapsed time = 2 ms.

From 657 to 8 logical reads, with no key lookups. And with SET STATISTICS PROFILE ON (the text version of the actual plan) the estimated and actual row counts match exactly: 1000 estimated, 1000 actual.

And SELECT *?

Plan and Messages
  |--Clustered Index Scan(OBJECT:([...].[PK__Employee__...]), WHERE:([...].[City]='Indore'))

Table 'EmployeePerformanceDemo'. Scan count 1, logical reads 657, ...

SELECT * also needs Department and Salary, which neither index contains, so it's back to a full scan. One more reason to select only the columns you need.

Summary of the results

Query and indexPlan operatorLogical reads
No index on CityClustered Index Scan657
IX_Employee_City, query needs only EmployeeId and CityIndex Seek6
IX_Employee_City, query also needs EmployeeNameClustered Index Scan (optimizer's choice)657
Same, index forced with a hintIndex Seek + Key Lookup5,055
Covering index (City) INCLUDE (EmployeeName)Index Seek8
SELECT * with either indexClustered Index Scan657

Common plan operators

OperatorWhat it meansGood or bad?
Clustered Index Scan / Table ScanReads every row (Table Scan when the table has no clustered index)Fine for small tables or when you need most rows; a warning sign for selective filters on big tables
Index SeekJumps directly to matching rows in an indexUsually what you want for selective queries
Index Scan (nonclustered)Reads a whole nonclustered indexCheaper than a table scan, but still reads everything
Key Lookup / RID LookupFetches missing columns from the table for each rowOK for a few rows; expensive for many. Fix with INCLUDE columns
Nested LoopsFor each row of the outer input, searches the inner inputGreat when the outer input is small
Hash MatchBuilds a hash table to join or aggregateGood for large unsorted inputs; needs memory
Merge JoinJoins two inputs already sorted on the join keyVery efficient when both sides are sorted
SortSorts rows (ORDER BY, GROUP BY, merge joins)Expensive on large inputs; an index in the right order can remove it

Joins and their operators are covered in detail in Joins and Join Optimization, and index design in Clustered vs Nonclustered and Composite and Covering Indexes.

A tuning checklist

  1. Turn on the actual plan (Ctrl + M) and SET STATISTICS IO ON.
  2. Find the most expensive operator and the thickest arrows.
  3. Look for scans on big tables with selective filters, key lookups on many rows, and sorts.
  4. Compare estimated and actual rows. Large differences mean outdated statistics: run UPDATE STATISTICS.
  5. Check warnings (yellow triangles), such as implicit conversions when a VARCHAR column is compared to an NVARCHAR value.
  6. Change one thing (an index, the query), then compare logical reads again.

Interview questions

What is an execution plan?

The sequence of operations SQL Server chooses to execute a query: which indexes it reads, how it joins, sorts and aggregates, and the estimated cost of each step. It is produced by the cost-based query optimizer.

What is the difference between an estimated and an actual execution plan?

An estimated plan (Ctrl + L) is produced without running the query and shows only estimates. An actual plan (Ctrl + M) is captured while the query runs and also shows actual row counts and runtime warnings.

What is the difference between an Index Scan and an Index Seek?

A scan reads the whole index or table; a seek navigates the index tree directly to the matching rows. For a selective filter, a seek reads far fewer pages (6 instead of 657 in our test).

What is a Key Lookup and how do you remove it?

When a nonclustered index finds the rows but doesn't contain all the columns the query needs, SQL Server looks up each row in the clustered index. Remove it by adding the missing columns to the index with INCLUDE (a covering index), or by selecting fewer columns.

Why might SQL Server not use an index that exists?

Because the optimizer estimates another plan is cheaper. Commonly: the query needs columns not in the index, so key lookups would cost more than a scan (the tipping point), or the filter matches too many rows. Outdated statistics and functions on the column (WHERE YEAR(Date) = 2026) also prevent seeks.

What does SET STATISTICS IO show?

The number of pages read per table: logical reads (from memory), physical and read-ahead reads (from disk), and scan count. Logical reads are the most reliable measure for comparing query versions.

Summary

  • The execution plan shows how SQL Server runs a query; read it right to left and start with the most expensive operator.
  • Ctrl + L shows the estimated plan; Ctrl + M includes the actual plan with real row counts.
  • Use SET STATISTICS IO ON and compare logical reads; time varies, pages don't.
  • An index on the WHERE column helps only if the query is covered or returns few rows; otherwise key lookups make it more expensive than a scan.
  • A covering index (INCLUDE) turned 657 reads into 8 in our test.

Next: learn to capture the slow queries in the first place with SQL Server Profiler and Extended Events.