📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you read a SQL Server execution plan? Explain estimated versus actual plans, the main operators (index seek, index scan, key lookup, nested loops, hash match and merge join), the warnings you look for, and what you check first when a query is slow.

Covers reading SQL Server execution plans: estimated vs actual plans, right-to-left data flow, seek, scan, key lookup, nested loops, hash match, merge join, sort, warnings, and estimated vs actual rows as the first check.

Intermediate Theory Intermediate execution-plans index-seek joins query-performance query-tuning sql-server

🎯 Key points

  • Estimated plan is compiled without running; actual plan adds runtime rows, executions, memory grant and warnings
  • Read data flow right to left; arrow width reflects actual rows in an actual plan (estimated rows in an estimated plan), so check which you are looking at
  • Compare estimated vs actual rows per operator: a 10x+ gap points to the root cause, often stale statistics
  • Seek vs scan: a seek navigates the index key, but check rows read vs returned for residual predicates
  • Key lookup = extra clustered index read per row; expensive when executed thousands of times
  • Nested loops for small outer inputs, hash match for large unsorted inputs, merge join for two sorted inputs
  • Adaptive join (batch mode, 2017+) picks hash or nested loops at runtime from a row threshold
  • Warnings (CONVERT_IMPLICIT, spills, missing index) and logical reads from SET STATISTICS IO matter more than cost percentages

⏱ 30-second answer

An estimated plan is what the optimiser would do; an actual plan is the same plan plus runtime numbers: actual rows, number of executions, memory grant used and runtime warnings. Data flows right to left; thick arrows mean many rows.

The first thing I check is estimated vs actual rows on each operator: a big gap means a bad estimate, and almost every bad plan follows from one. Then I look for scans where I expected seeks, key lookups executed thousands of times, the join type (nested loops with a huge outer input is a red flag), and warnings such as CONVERT_IMPLICIT, spills and residual predicates.

Cost percentages are estimates too, so I confirm with logical reads from SET STATISTICS IO.

🗣 Full answer (senior)

How I would answer this in an interview

"I always get the actual execution plan if I can, because the estimated plan only tells me what the optimiser thought would happen. The actual plan adds actual rows, number of executions per operator, the memory grant and runtime warnings. I read it right to left: the leaf operators on the right fetch data, it flows left through joins, sorts and aggregates to the SELECT. Arrow thickness shows row counts, so a fat arrow going into a nested loops join is something I look at straight away.

My first check is always estimated versus actual rows. If an operator estimated 12 rows and produced 400,000, everything to its left was costed for the wrong world: nested loops instead of hash, a tiny memory grant, a key lookup chosen because it looked cheap. Then I look at access methods. An index seek navigates the B+ tree by key; an index scan reads the whole index, which is fine for a small table but not for a 50-million-row one. A key lookup means the non-clustered index didn't cover the query, so SQL Server goes back to the clustered index for every row; that's cheap for 20 rows and terrible for 200,000. For joins, nested loops suits a small outer input with an indexed inner side, hash match suits large unsorted inputs, and merge join needs both inputs sorted on the join key.

Finally I check warnings: the yellow triangle for CONVERT_IMPLICIT, spills to tempdb on sorts and hashes, and residual predicates where the seek only uses part of the key. The mistake I see is people tuning by cost percentage. Those are estimates too; a 2% operator can be the one doing 90% of the reads. I confirm with SET STATISTICS IO, TIME ON and judge a fix by logical reads and CPU."


Estimated vs actual

Estimated plan Actual plan Live query statistics
Runs the query No Yes Yes, shows progress
Actual rows / executions No Yes Yes, as it runs
Memory grant used, spills No Yes Partly
Use when Query too slow or dangerous to run Normal tuning Query runs for minutes

In production, the last actual plan can come from Query Store (estimated plans with runtime stats) or sys.dm_exec_query_plan_stats with LAST_QUERY_PLAN_STATS enabled.

The operators that matter most

Operator What it does Good sign Bad sign
Index Seek B+ tree navigation by key Few rows, low reads Seek with residual predicate filtering most rows
Index / Clustered Index Scan Reads all leaf pages Small tables, need most rows Large table, few rows returned
Key Lookup Fetch missing columns from clustered index Low executions Thousands of executions
Nested Loops For each outer row, probe inner Small outer input Large outer input, inner scan
Hash Match Build hash table on one input, probe with other Large unsorted inputs Spill warning, huge build side
Merge Join Walk two sorted inputs Both already sorted by index Explicit Sort added to feed it
Sort Order rows in memory Small inputs Spill, or sorting millions for TOP

My checklist

  1. Estimated vs actual rows (find the first big divergence, reading right to left).
  2. Scans on big tables; seeks with residual predicates.
  3. Key lookups and their execution counts.
  4. Join types against input sizes.
  5. Warnings: implicit conversion, spills, missing index, no join predicate.
  6. Memory grant vs used.
  7. Confirm with logical reads before and after.

Production example

A customer search endpoint took 2.8 s. The actual plan showed an index seek estimated at 9 rows returning 180,000, feeding a key lookup executed 180,000 times (540,000 logical reads). Stale statistics after a bulk import were the cause; updating them switched the plan to a scan plus hash join at 9,000 reads, and adding two INCLUDE columns brought it to 600 reads and 40 ms.

🔍 What the interviewer is checking

Checks whether the candidate can diagnose a slow query from a plan and turn what they see into a concrete optimisation, rather than guess.

Green flags

  • Prefers actual plans and compares estimated vs actual rows first.
  • Explains seek vs scan, key lookups with execution counts, the three join algorithms and adaptive joins.
  • Names warnings: implicit conversion, spills, residual predicates.
  • Proposes a specific fix (index, statistics, parameter type, rewrite) and confirms it with logical reads.
  • Uses Query Store history to compare plans over time.

Red flags

  • Tunes by cost percentage.
  • 'Scans are always bad.'
  • Creates every missing index suggestion.

📚 Learn in depth

1. A plan is a tree of iterators

Each operator implements open, get-next-row, close (row mode), or processes batches of about 900 rows (batch mode). The root asks its child for rows, which asks its children, so data is pulled from right to left.

SELECT
  └─ Hash Match (Aggregate)            est 50     act 48
       └─ Nested Loops (Inner Join)    est 120    act 210,000   <-- divergence
            ├─ Index Seek  Orders.IX_Date     est 120   act 210,000
            └─ Key Lookup  Orders.PK          executions 210,000

Read the divergence from the right: the seek's estimate was wrong, so the optimiser chose nested loops and a lookup per row.

2. Estimated rows vs actual rows: per execution

In modern SSMS, for the inner side of nested loops, 'Estimated Number of Rows Per Execution' must be compared with 'Actual Number of Rows for All Executions' divided by 'Number of Executions'. Misreading this is a common source of false alarms.

3. Seek predicates vs residual predicates

An index seek has Seek Predicates (used to navigate the B+ tree) and sometimes a Predicate (a residual filter applied after reading each row). An index on (CustomerId, OrderDate) queried with WHERE CustomerId = 5 AND Status = 'Open' seeks on CustomerId and filters Status row by row. If CustomerId 5 has a million orders, that 'seek' reads a million rows.

4. Join algorithms and their costs

  • Nested loops: cost ≈ outer rows × cost of one inner probe. Great when outer is small and inner is indexed.
  • Hash match: builds a hash table on the smaller (build) input in memory, probes with the other. Needs a memory grant; spills to tempdb if the estimate was too low.
  • Merge join: linear in both inputs, but both must be sorted; many-to-many merge uses a worktable.
  • Adaptive join (batch mode): decides between hash and nested loops at runtime based on a row threshold.

5. Warnings worth knowing

Warning Meaning
Type conversion in expression ... may affect CardinalityEstimate / SeekPlan Implicit conversion, often nvarchar parameter vs varchar column
Operator used tempdb to spill data Memory grant too small for sort or hash
Missing Index (green text) The optimiser's per-query suggestion, not a recommendation
No Join Predicate Accidental cartesian product
Excessive Grant Grant much bigger than used, wasting memory

6. Getting plans in production

  • Query Store: plans and runtime stats per interval (sys.query_store_plan, sys.query_store_runtime_stats).
  • sys.dm_exec_query_plan for cached estimated plans; sys.dm_exec_query_plan_stats for the last actual plan (enable LAST_QUERY_PLAN_STATS).
  • Extended Events query_post_execution_showplan is expensive; use only briefly.

Try it yourself

  1. Run a query with SET STATISTICS IO, TIME ON and the actual plan enabled; match logical reads to operators.
  2. Create an index that doesn't cover a query, look at the key lookup's 'Number of Executions', then add INCLUDE columns and compare reads.
  3. Force a spill by updating statistics with a tiny sample on a skewed column, then sort on it.
  4. Find a seek with a residual predicate by querying on the first and third columns of a three-column index.
  5. Paste the plan XML into a plan viewer and find 'Reason For Early Termination' and the memory grant info.

💻 Code

Turn on runtime measurements, then compare a non-covering index with a covering one.

SET STATISTICS IO, TIME ON;   -- logical reads and CPU per statement

-- Non-covering: seek on CustomerId, then a key lookup per row for Total and Status
CREATE INDEX IX_Orders_Customer ON dbo.Orders (CustomerId);

SELECT OrderId, OrderDate, Total, Status
FROM dbo.Orders
WHERE CustomerId = 1042;
-- Plan:  Nested Loops
--          ├─ Index Seek (IX_Orders_Customer)  act 12,400
--          └─ Key Lookup (PK_Orders)           executions 12,400
-- Table 'Orders'. Scan count 1, logical reads 37,310

-- Covering: everything the query needs is in the index leaf
CREATE INDEX IX_Orders_Customer_Cover
    ON dbo.Orders (CustomerId) INCLUDE (OrderDate, Total, Status);

SELECT OrderId, OrderDate, Total, Status
FROM dbo.Orders
WHERE CustomerId = 1042;
-- Plan:  Index Seek (IX_Orders_Customer_Cover)  act 12,400
-- Table 'Orders'. Scan count 1, logical reads 64

Pull the last actual plan for a query in production without re-running it:

ALTER DATABASE SCOPED CONFIGURATION SET LAST_QUERY_PLAN_STATS = ON;

SELECT st.text, ps.query_plan
FROM sys.dm_exec_cached_plans cp
CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) st
CROSS APPLY sys.dm_exec_query_plan_stats(cp.plan_handle) ps
WHERE st.text LIKE N'%FROM dbo.Orders%CustomerId%';

⚠ Common mistakes

  • Mistake: Tuning from the estimated plan only. Why it is wrong: It hides actual rows, executions, spills and grant usage. Instead: Use the actual plan, Query Store or sys.dm_exec_query_plan_stats.
  • Mistake: Going straight to the operator with the highest cost percentage. Why it is wrong: Percentages are estimated and can be wildly off. Instead: Find the first estimated vs actual divergence and confirm with logical reads.
  • Mistake: Rewriting the query or adding indexes when the plan is wrong only because statistics are stale. Why it is wrong: After bulk loads or on ascending keys (dates, identities) the histogram doesn't cover new rows, so estimates collapse and the plan shape is a symptom. Instead: Check sys.dm_db_stats_properties (last_updated, modification_counter) and update statistics before redesigning.
  • Mistake: Assuming every scan is bad and every seek is good. Why it is wrong: A seek with a residual predicate can read millions of rows; a scan of a 200-row table is fine. Instead: Look at rows read vs rows returned.
  • Mistake: Ignoring 'Number of Executions' on the inner side of nested loops. Why it is wrong: A cheap lookup run 200,000 times is the problem. Instead: Multiply per-execution cost by executions.
  • Mistake: Creating every green missing-index suggestion. Why it is wrong: They are per-query, ignore write cost and duplicate existing indexes. Instead: Treat them as hints and design indexes across the workload.
  • Mistake: Skipping the yellow warning triangles. Why it is wrong: CONVERT_IMPLICIT and spill warnings often are the root cause. Instead: Check operator properties for warnings.
  • Mistake: Reading arrow thickness as proof of a problem. Why it is wrong: In an estimated plan it shows estimated rows, which may be wrong. Instead: Use an actual plan and compare the numbers on the arrow's tooltip.

🏛 Senior insight: trade-offs

Senior engineers treat the plan as evidence of the optimiser's beliefs. The question isn't 'which operator is expensive?' but 'where did the optimiser's belief about row counts first go wrong, and why?' That leads to statistics, predicates, data types or parameter values, which are durable fixes, and to concrete actions: an index change, a statistics job, a parameter type fix or a rewrite.

In production I rarely have the luxury of running a query in SSMS, and a single plan is a snapshot. Query Store keeps plans and runtime stats per interval, so I look at trends: did duration creep up with data growth, or jump when the plan id changed after a release or statistics update? That history is what lets me compare 'before' and 'after' plans and force the old one while the code is fixed.

Plan source When it fits Cost When not to
Actual plan in SSMS Reproducible query, safe to run Runs the query Destructive or very long queries
Query Store Production regressions, history and trends Small overhead, on by default in Azure SQL Need per-execution detail
sys.dm_exec_query_plan_stats Last actual plan of a cached query Light overhead when enabled Plan already evicted
Extended Events showplan Rare, hard-to-catch queries High overhead Busy production servers for long periods

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions key lookups Why: Checks whether they know when to cover a query with INCLUDE columns
    How to answer

    A key lookup happens when a non-clustered index finds the rows but lacks some columns the query needs, so SQL Server goes back to the clustered index for each row (a RID lookup on a heap). Each one is 3–4 random logical reads.

    A covering index holds every column the query references, so no lookup is needed.

    • Key columns are sorted and searchable: use them for WHERE, JOIN and ORDER BY.
    • INCLUDE columns sit only in the leaf level: not sorted, not counted in the key size limit, cheaper to maintain. Use them for columns that are only selected.

    Lookups hurt when they run for thousands of rows; past the tipping point the optimiser scans instead. Trade-off: covering speeds a query but widens the index and every write.

  2. When: Candidate mentions the CONVERT_IMPLICIT warning Why: Checks the nvarchar vs varchar parameter problem from .NET
    How to answer

    In .NET a string becomes an nvarchar parameter by default (ADO.NET AddWithValue, Dapper sends nvarchar(4000), EF Core when the property is Unicode). nvarchar has higher data type precedence than varchar, so SQL Server converts the column, not the parameter: CONVERT_IMPLICIT(nvarchar, AccountNo). With a SQL collation that means a scan of every row; with a Windows collation you may get a dynamic seek, but with worse estimates. SSMS was fast because the literal there was varchar.

    Diagnose with the plan warning ('Type conversion may affect seek plan'), Query Store and a plan cache search. Fix at the mapping layer: EF Core IsUnicode(false)/HasColumnType("varchar(20)"), Dapper DbString { IsAnsi = true }, ADO.NET SqlDbType.VarChar with a size. Trade-off: changing the column to nvarchar also works but doubles storage.

  3. When: Candidate says they look for the most expensive operator Why: Checks that they know costs are always estimates and how to measure real work
    How to answer

    The cost percentages are the optimiser's estimated costs, even in an actual plan; they are never recalculated from run time. If an operator was estimated at 10 rows and processed a million, it still shows a tiny percentage. Some work is costed close to nothing: scalar UDFs run per row, remote/linked-server calls and multi-statement TVFs get fixed guesses. Parallel plans divide CPU cost by DOP, which can make a heavy branch look cheap. So I compare estimated vs actual rows and executions, read the per-operator actual elapsed time, CPU and logical reads in the actual plan, and confirm with SET STATISTICS IO, TIME.

↩ Usually asked after

More in Query Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me