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

📚 Interview question

How does the SQL Server query optimiser turn a T-SQL statement into an execution plan? Walk me through parsing, binding (algebrisation), cost-based optimisation, the plan cache and execution, and explain why the optimiser looks for a good-enough plan rather than the best one.

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.

Intermediate Theory Intermediate cardinality-estimation execution-plans plan-cache query-optimiser query-performance sql-server

🎯 Key points

  • Parse checks syntax; bind (algebriser) resolves names, types, permissions and adds implicit conversions
  • Plan cache lookup before optimisation; a hit skips compilation entirely
  • Trivial plan for simple queries, otherwise cost-based search phases 0, 1 and 2 using transformation rules and the memo
  • Costs come from cardinality estimates built on statistics (histogram, density), not from real run time
  • Optimiser stops at a good-enough plan or a time-out ('Reason For Early Termination')
  • Statistics kept current by AUTO_UPDATE_STATISTICS (optionally async) plus scheduled UPDATE STATISTICS on skewed or ascending-key tables
  • Cached plan reuse explains parameter sniffing; PSP (2022) and OPPO (2025) reduce it; Query Store records plan changes
  • Fix the estimate (statistics, SARGable predicates, data types) before hinting

⏱ 30-second answer

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 optimiser never runs the query to cost it; every cost is an estimate.
  • Search space grows factorially with joins, so it settles for good enough.

The trade-off: plan reuse saves CPU on compilation, but one cached plan serves every later parameter value, good or bad.

🗣 Full answer (senior)

How I would answer this in an interview

"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."


The pipeline at a glance

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

What cost actually means

'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.

When plans get recompiled

  • Schema change on a referenced object.
  • Statistics updated past the threshold (dynamic: roughly SQRT(1000 * rows) for large tables since compatibility level 130).
  • Different SET options (ARITHABORT, ANSI_NULLS), which produce a different cache entry.
  • OPTION (RECOMPILE), sp_recompile, or memory pressure evicting plans.

Production example

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.

🔍 What the interviewer is checking

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

  • Names parse, bind, cache lookup, optimisation and execution in the right order.
  • Explains that costs depend on cardinality estimates from statistics.
  • Mentions trivial plans, good-enough termination and time-outs.
  • Connects plan reuse to parameter sniffing.

Red flags

  • Thinks the optimiser runs the query or always finds the best plan.
  • Treats cost percentages as real time.
  • Jumps straight to hints.

📚 Learn in depth

1. Why an optimiser exists at all

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]

2. Binding and implicit conversion

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.

3. The memo and transformation rules

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.

4. Cardinality estimation is the input that matters

Every cost depends on row counts. The cardinality estimator (CE) uses:

  • Histograms (up to 200 steps) on the leading column of each statistics object.
  • Density vectors for multi-column statistics and for unknown values (e.g. local variables).
  • Assumptions: independence vs correlation between predicates (the new CE since SQL Server 2014 uses exponential backoff), containment for joins.

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.

5. Plan caching and reuse

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.

6. Intelligent query processing

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.

Try it yourself

  1. Run SET STATISTICS XML ON on a simple primary-key lookup and find StatementOptmLevel="TRIVIAL" in the plan XML.
  2. Write a 6-table join and look at the root operator's properties for 'Reason For Early Termination'.
  3. Compare WHERE AccountNo = N'123' with WHERE AccountNo = '123' on a varchar column and look for CONVERT_IMPLICIT.
  4. Query sys.dm_exec_cached_plans joined to sys.dm_exec_sql_text before and after running the same query with two different literals.
  5. Change the database compatibility level between 150 and 160 and compare estimated rows on a correlated two-predicate query.

💻 Code

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);
    }
}

⚠ Common mistakes

  • Mistake: Treating estimated subtree cost as seconds or comparing costs across different queries. Why it is wrong: Cost is a unitless model output based on estimates. Instead: Compare actual duration, CPU and logical reads (SET STATISTICS IO, TIME ON, Query Store).
  • Mistake: Expecting the optimiser to find the optimal plan, and calling a merely adequate plan a bug. Why it is wrong: Optimisation is a deliberate compromise between compile time and plan quality: it stops at a good-enough plan or on time-out, and its choice is only as good as its statistics. Instead: Check 'Reason For Early Termination', simplify very complex queries and make sure statistics describe the data.
  • Mistake: Reaching for 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.
  • Mistake: Thinking the optimiser runs the query to measure it. Why it is wrong: All costing is from statistics. Instead: Keep statistics current (auto update plus scheduled UPDATE STATISTICS ... WITH FULLSCAN or a larger sample where data is skewed) and compare estimated vs actual rows.
  • Mistake: Ignoring that different SET options create different plan cache entries. Why it is wrong: SSMS and the app can run different plans for the same text. Instead: Match SET options when reproducing.
  • Mistake: Building SQL by string concatenation. Why it is wrong: Every literal is new text, so no reuse and plan cache bloat. Instead: Parameterise with sp_executesql or ORM parameters.
  • Mistake: Changing compatibility level or upgrading versions without a baseline. Why it is wrong: The CE version and IQP features follow compatibility level, so plans can change for better or worse. Instead: Capture a Query Store baseline at the old level, switch, compare and force regressed plans.
  • Mistake: Blaming the optimiser for a scan caused by a function on a column. Why it is wrong: The predicate was non-SARGable before optimisation began. Instead: Rewrite the predicate.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions statistics or histograms as the input to costing Why: Checks depth on how selectivity and density drive row estimates
    How to answer

    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.

  2. When: Candidate mentions plan cache lookup by text hash Why: Checks whether they know how unparameterised or badly typed SQL bloats the plan cache
    How to answer

    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.

  3. When: Candidate says the optimiser settles for a good-enough plan Why: Checks practical handling of complex queries that exhaust the optimiser's budget
    How to answer

    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.

↩ Usually asked after

More in Query Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me