Covers the SQL Server query processing pipeline: parse, bind/algebrise, trivial plan and cost-based optimisation phases, plan caching and reuse, and execution, with what the optimiser's estimates depend on.
SQL Server parses the statement (syntax), binds it (the algebriser resolves tables, columns, types and permissions into a query tree), then checks the plan cache. On a miss the optimiser runs: simple statements get a trivial plan; everything else goes through cost-based optimisation, exploring alternative join orders, join types and access paths using cardinality estimates derived from statistics. It picks the cheapest plan it finds within a time budget, caches it, and the execution engine runs it.
The trade-off: plan reuse saves CPU on compilation, but one cached plan serves every later parameter value, good or bad.
"When a statement arrives, SQL Server first parses it into a tree and checks syntax. The algebriser then binds names to real objects, resolves data types and implicit conversions, and checks permissions. Before doing any expensive work it hashes the batch text and looks in the plan cache; if there's a reusable plan for that exact text and the same SET options, it just executes it.
On a cache miss the optimiser takes over. If the query is trivial, such as a single-table lookup on a unique key, it produces a trivial plan immediately. Otherwise it simplifies the tree, loads statistics, and runs cost-based optimisation in phases. It applies transformation rules (join reordering, pushing predicates down, choosing seek versus scan, nested loops versus hash versus merge) and stores alternatives in a structure called the memo. Each alternative is costed from cardinality estimates: how many rows each operator will produce, which comes from statistics histograms and density. When it finds a plan that's cheap enough, or runs out of its time budget, it stops. That's why the plan properties show 'Reason For Early Termination: Good Enough Plan Found' or 'Time Out'.
The chosen plan goes into the plan cache and the execution engine runs it, pulling rows operator by operator (or in batches for batch mode). The mistake I see is people treating a bad plan as an optimiser bug and reaching for hints. Nine times out of ten the optimiser made a sensible choice from a wrong row estimate: stale statistics, a non-SARGable predicate, a table variable, or a sniffed parameter. Fix the estimate and the plan usually fixes itself."
| Stage | What happens | What can go wrong |
|---|---|---|
| Parse | Syntax check, parse tree | Syntax errors only |
| Bind (algebrise) | Name resolution, types, permissions, implicit conversions | CONVERT_IMPLICIT added when parameter types don't match columns |
| Plan cache lookup | Hash of text + SET options + database | Ad-hoc text never matches, so the cache fills with single-use plans |
| Simplification | Contradiction detection, predicate push-down, join elimination | Missing trusted FKs block join elimination |
| Trivial plan | Simple queries skip full optimisation | — |
| Cost-based search | Search 0 (transaction processing), 1 (quick plan), 2 (full, parallel considered) | Time out on very complex queries; wrong estimates |
| Execution | Row mode or batch mode operators, memory grant | Spills when the grant was too small |
'Estimated subtree cost' is a unitless number from a cost model calibrated decades ago. It is useful for comparing alternatives within one compilation, not for comparing two different queries or predicting seconds. A plan with cost 0.5 can run for a minute if the estimate of 1 row was really 2 million.
SQRT(1000 * rows) for large tables since compatibility level 130).ARITHABORT, ANSI_NULLS), which produce a different cache entry.OPTION (RECOMPILE), sp_recompile, or memory pressure evicting plans.On an orders API, a report query with nine joins showed 'Reason For Early Termination: Time Out' and a hash join plan reading 4 million rows. Splitting out the filtered customer set into a temp table gave the optimiser a smaller problem and accurate statistics; logical reads fell from 1.2 million to 18,000 and p95 went from 3.4 s to 120 ms.
Checks whether the candidate understands that plans come from cost estimates built on statistics, and can reason from that to diagnosing bad plans.
Green flags
Red flags
SQL is declarative: you say what rows you want, not how to get them. For a query joining 6 tables there are 6! = 720 join orders, each with three physical join types and several access paths per table. The search space explodes, so SQL Server uses a cost-based, rule-driven search with a time budget instead of exhaustive enumeration.
T-SQL text
|
v
[Parser] --> parse tree
|
v
[Algebriser] --> bound query tree (types, objects, permissions)
|
v
[Plan cache lookup] --hit--> [Execution engine]
| miss
v
[Simplification] -> [Trivial plan?] --yes--> plan
| no
v
[Load statistics, derive cardinality]
|
v
[Search 0] -> [Search 1] -> [Search 2] (stop when cheap enough or time out)
|
v
[Plan cache insert] -> [Execution engine]
The algebriser is where data types are reconciled. If a .NET client sends @p nvarchar(4000) against a varchar(20) column, data type precedence forces the column to be converted, the predicate is no longer SARGable, and you get a scan with a CONVERT_IMPLICIT warning. The optimiser then works faithfully on a tree that was already compromised.
The optimiser keeps groups of logically equivalent expressions in the memo. Exploration rules generate logical alternatives (join commutativity, associativity); implementation rules produce physical operators (Index Seek, Hash Match, Merge Join). Each group remembers the cheapest physical option, so work is shared across alternatives.
Every cost depends on row counts. The cardinality estimator (CE) uses:
The CE version is tied to database compatibility level. Wrong estimates cascade: a 1-row estimate leads to nested loops and no memory grant; reality of 1 million rows means millions of seeks and a spill.
Compiled plans are cached keyed by the hash of the batch text plus attributes such as SET options and database id. Parameterised statements (sp_executesql, stored procedures, EF Core and Dapper commands) reuse one plan compiled for the first parameter values seen: parameter sniffing. SQL Server 2022 adds Parameter Sensitive Plan optimisation (compat level 160) which can keep up to three variants for one equality predicate, and SQL Server 2025 (compat level 170) adds optional parameter plan optimisation for @p IS NULL OR col = @p patterns.
Modern versions adjust plans after the fact: memory grant feedback, adaptive joins (batch mode), interleaved execution for multi-statement TVFs, table variable deferred compilation, DOP and CE feedback (2022). These reduce the damage of bad estimates but don't remove the need to understand them.
SET STATISTICS XML ON on a simple primary-key lookup and find StatementOptmLevel="TRIVIAL" in the plan XML.WHERE AccountNo = N'123' with WHERE AccountNo = '123' on a varchar column and look for CONVERT_IMPLICIT.sys.dm_exec_cached_plans joined to sys.dm_exec_sql_text before and after running the same query with two different literals.A small schema and three queries that show a trivial plan, a full cost-based plan, and how to see what the optimiser decided.
CREATE TABLE dbo.Customers (
CustomerId int IDENTITY PRIMARY KEY,
Email varchar(256) NOT NULL UNIQUE,
State char(3) NOT NULL
);
CREATE TABLE dbo.Orders (
OrderId bigint IDENTITY PRIMARY KEY,
CustomerId int NOT NULL REFERENCES dbo.Customers(CustomerId),
OrderDate datetime2(0) NOT NULL,
Total decimal(12,2) NOT NULL,
INDEX IX_Orders_Customer_Date (CustomerId, OrderDate)
);
-- 1. Trivial plan: unique lookup, no real choice to make
SELECT Email FROM dbo.Customers WHERE CustomerId = 42;
-- 2. Full optimisation: join order, join type and access path all chosen by cost
SELECT c.State, SUM(o.Total) AS Revenue
FROM dbo.Orders o
JOIN dbo.Customers c ON c.CustomerId = o.CustomerId
WHERE o.OrderDate >= '2026-07-01'
GROUP BY c.State;
-- 3. See how each cached plan was optimised and whether it timed out
SELECT TOP (20)
qs.execution_count,
qs.total_worker_time / qs.execution_count AS avg_cpu_us,
qp.query_plan.value('declare namespace p="http://schemas.microsoft.com/sqlserver/2004/07/showplan";
(//p:StmtSimple/@StatementOptmLevel)[1]', 'varchar(20)') AS optm_level,
qp.query_plan.value('declare namespace p="http://schemas.microsoft.com/sqlserver/2004/07/showplan";
(//p:StmtSimple/@StatementOptmEarlyAbortReason)[1]', 'varchar(50)') AS early_abort,
st.text
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp
ORDER BY qs.total_worker_time DESC;
From .NET, typed parameters keep the bound tree SARGable and the plan reusable:
namespace Shop.Data;
using Microsoft.Data.SqlClient;
using System.Data;
public sealed class CustomerReader(string connectionString)
{
public async Task<string?> GetEmailAsync(int customerId, CancellationToken ct)
{
await using var conn = new SqlConnection(connectionString);
await conn.OpenAsync(ct);
await using var cmd = new SqlCommand(
"SELECT Email FROM dbo.Customers WHERE CustomerId = @id", conn);
// Explicit type: one cached plan, no implicit conversion at bind time
cmd.Parameters.Add("@id", SqlDbType.Int).Value = customerId;
return (string?)await cmd.ExecuteScalarAsync(ct);
}
}
SET STATISTICS IO, TIME ON, Query Store).FORCE ORDER, LOOP JOIN or index hints first. Why it is wrong: Hints freeze a plan that may be wrong when data changes. Instead: Fix the estimate: statistics, SARGable predicates, matching data types.UPDATE STATISTICS ... WITH FULLSCAN or a larger sample where data is skewed) and compare estimated vs actual rows.sp_executesql or ORM parameters.The senior framing is that the optimiser is an estimator first and a searcher second. If you can explain a bad plan as 'it thought 1 row, it got 800,000', you've found the real problem; hints are a last resort and should be applied through Query Store hints or plan forcing so they're visible and reversible, not buried in code.
Know what the platform already gives you: Query Store (on by default in Azure SQL Database and for new databases in SQL Server 2022+), automatic plan correction (FORCE_LAST_GOOD_PLAN, on by default for new Azure SQL servers), PSP optimisation (2022), optional parameter plan optimisation (SQL Server 2025, compat level 170) and the IQP feedback features. Upgrades and compatibility-level changes alter the CE and those features, so treat them as plan-changing deployments: baseline in Query Store first, then compare. Measure with actual plans and logical reads, not cost percentages.
| Lever | When it fits | Cost | When not to |
|---|---|---|---|
| Update statistics / add multi-column stats | Estimates far from actuals | Cheap, some I/O | Estimates already accurate |
| Rewrite predicate / fix types | Scans from functions or CONVERT_IMPLICIT |
Code change | Never wrong to do |
| Split query with temp table | Many joins, optimiser time-outs | Extra tempdb writes | Simple OLTP lookups |
| Query Store hint / forced plan | Urgent regression, can't change code | Plan may age badly | As a permanent fix without review |
| Join or index hints in code | Proven, stable data shape | Hidden, brittle | Default choice |
Selectivity is the fraction of rows a predicate returns: OrderId = 5 is highly selective, IsActive = 1 matching 95% of rows is not. Density is 1 / distinct values for a column (or column prefix); a column with 4 statuses has density 0.25.
SQL Server keeps both in statistics: a header, a density vector for each key prefix, and a histogram of up to 200 steps on the leading column. The optimiser uses the histogram for literals and sniffed parameters and falls back to density for local variables and unknown values.
An index on a low-selectivity column is often ignored because a seek plus thousands of key lookups costs more than one scan. Trade-off: such columns are useful as part of a composite or filtered index, rarely alone.
AddWithValue infers the parameter type from the .NET value: a string becomes nvarchar(n) where n is that value's length, so 'Smith' is sent as nvarchar(5) and 'Nguyen' as nvarchar(6). The parameter declaration is part of the statement text, so SQL Server compiles and caches a separate plan per length. On a busy system that means extra compile CPU, plan cache memory taken from the buffer pool, and useful plans evicted sooner. If the column is varchar, the same call also causes a CONVERT_IMPLICIT scan.
Detect it as many rows sharing one query_hash with different plan_handles in sys.dm_exec_query_stats, or many query ids for one query in Query Store. Fix with Parameters.Add("@p", SqlDbType.VarChar, 20); Dapper and EF Core already send fixed sizes.
The optimiser doesn't search for the best plan forever: each search phase gets a budget of optimisation work, scaled to how expensive the query looks. Time Out means it used that budget before finishing exploration and returned the best plan found so far. It isn't an error, and the plan may be fine — so I first check actual performance. If the plan is poor or unstable, the cause is usually too many alternatives: many joins, views over views, complex OR logic, or missing indexes that leave only expensive options. I simplify the query, split it with a temp table, remove redundant joins, make foreign keys trusted so join elimination works, and give it good indexes. Hints and plan forcing are last resorts.
Last updated 23 Nov 2026.