Blog
IntermediateReferenceSQL Server Engineering

How a query actually executes

The path from query text to a running plan - parse, bind, optimise, cache, execute - and the storage structures underneath: pages, the buffer pool, and the write-ahead log that decides what a commit costs.

Applies to
SQL Server2016-2025 (13.x-17.x)
matureUpdated Reviewed
intermediateAssumes working familiarity; skips the fundamentals.

What you will be able to do

  • Walk a statement from T-SQL text to a cached plan and say what each phase produces.
  • Explain why the optimiser is a cost estimator, not a truth-teller, and what its two inputs are.
  • Describe the commit path: log first, data later, and which wait type each half produces.
  • Distinguish a page that is in memory from one that is not, and name the wait that tells them apart.

Concepts covered

Every performance problem on SQL Server reduces to a question about one of four things: the plan the optimiser chose, the memory the data sits in, the log the commit waits on, or the concurrency structure two sessions are fighting over. This lesson builds the map those four live on, because you cannot diagnose a wait type you cannot name the owner of.

The analogy that carries the lesson is a desk, an archive and a receipt book. The buffer pool is the desk: the page you need is either already on it - a logical read - or must be fetched from the archive downstairs, which is a physical read and a PAGEIOLATCH_* wait while it travels. The transaction log is the receipt book on the till: a sale is not final until the receipt is written, and the stockroom can be tidied afterwards - that is commit versus checkpoint. The most common mistake is tuning the query while the wait type names the storage - rewriting SQL when WRITELOG dominates is rearranging the desk when the queue is at the till, because a durable commit cannot return faster than the log device can flush.

From text to a running plan

A statement does not execute; it is compiled and then executed. The phases matter because each one can be independently responsible for a regression - the plan cache in particular is where most “it was fine yesterday” stories begin.

One statement through the engine

  1. Parse

    A syntax tree

    Pure grammar. A syntactically valid but meaningless query parses fine - errors here are cheap

  2. Bind (algebrize)

    A logical tree with resolved objects

    Names become real table, column, and type references. This is where permissions and object existence are checked

  3. Optimise

    A physical execution plan, chosen by estimated cost

    Cardinality estimation drives the choice - the optimiser is only as good as the row counts it was handed

  4. Cache + execute

    The plan runs; the plan is stored for reuse

    The cached plan is reused with whatever parameter values arrive next - the root of parameter sniffing

Each phase produces something a later phase trusts. When a query regresses, the fault is almost always in what one phase was given, not in the phase itself.

The optimiser is a cost-based estimator, not an oracle. It costs candidate plans from two inputs: the number of rows it expects each operator to process (cardinality), and a cost model for each operator’s algorithm. Get the cardinality wrong and the cost model confidently picks the wrong algorithm - a nested loop where a hash join belonged, a serial plan where parallelism would have paid. Nothing downstream can rescue that decision at runtime; the engine executes the plan it was given.

The storage you are actually reading

Data lives in 8 kB pages, grouped eight at a time into extents. A page holds rows of one object; every read the engine does is a page read, never a row read. When you request one row, the whole page comes into memory.

That memory is the buffer pool - a cache of data pages that is the dominant consumer of memory in the instance by a wide margin. The physics are simple and the consequences are everywhere:

  • A page already in the buffer pool is a logical read - microseconds, no disk.
  • A page that is not is a physical read - the storage system’s latency, paid in full. The session waits on PAGEIOLATCH_* while the page arrives.

This is the first fork in every diagnosis: the same plan is fast on warm pages and slow on cold ones, and nothing about the plan changed. Buffer hit ratio tells you the shape of your working set; it does not tell you whether the workload is healthy, because a workload that fits in memory and one that thrashes are different problems with different fixes.

The write path, and why commit waits

Writes go to the transaction log first. A change is logged, the log records are hardened to disk, and only then does COMMIT return - the dirty data pages flush to the data files later, at checkpoint. This is write-ahead logging, and it is what makes a committed transaction survive a crash: on restart, the log is replayed to bring the data files to a consistent state.

Stage Waits on The wait type you would see
Modify the page in memory Buffer latch PAGELATCH_*
Harden the log records Storage latency on the log device WRITELOG
Dirty pages flush at checkpoint Storage throughput PAGEIOLATCH on the write side

The consequence that matters for latency: a durable commit cannot return faster than your log device can flush. Every COMMIT in a fully durable transaction pays WRITELOG once. That is the floor under single-statement latency, and it is why micro-batching - committing many changes in one transaction - pays a log-flush cost once instead of per row. The write-path lesson returns to this in depth, including the delayed-durability trade.

What this means in practice

  • The plan cache is not optional context - it is where parameter sensitivity lives. A plan compiled for one parameter value serves all later ones, and a RECOMPILE or a cache flush is how a workload suddenly “gets slow” with no code change.
  • Warm versus cold is a real distinction you must state in every measurement. A benchmark that never leaves the buffer pool measures a different system than one that touches storage.
  • Commit latency is a storage problem dressed as a query problem. When WRITELOG dominates, no amount of index tuning will help; the fix is faster log storage or fewer flushes, and the next lessons give you the measurement method to prove which one applies.

Guided practice

A beginner exercise, worked step by step on a scratch database or a developer instance - not a shared one, because the second step empties the buffer pool. The scenario: prove that the same query is two different systems depending on where the pages live, then prove what a commit pays.

  1. Build a table that spans many pages. In the scratch database, create dbo.t with an INT IDENTITY key and a CHAR(4000) filler column, and insert a few thousand rows in a loop. Check: SELECT COUNT(*) returns the number you loaded. If the insert itself was slow, that is the write path already - each row is a page change that must be logged; revisit “the write path”.
  2. Measure a cold read. Run DBCC DROPCLEANBUFFERS, set STATISTICS IO and STATISTICS TIME on, then run a full SELECT over the table and record the physical and logical read counts. Check: physical reads are non-zero and close to the page count - every page came from storage and a live session would have waited on PAGEIOLATCH_* while they arrived. If physical reads are zero, the pages were still cached; clear the pool again.
  3. Measure the same read warm. Run the identical SELECT a second time without clearing anything. Check: physical reads drop to zero and logical reads carry the result - the plan did not change, only where the pages lived. This is why “warm versus cold” must be stated in every measurement; if physical reads stayed high, revisit the buffer-pool bullets.
  4. Watch the commit path. Update a few hundred rows one transaction per row (a loop of UPDATE plus COMMIT pairs), then the same number of updates inside a single BEGIN TRAN/COMMIT, and time both. Check: the single transaction finishes faster - it pays the log flush once while the loop pays a WRITELOG wait per commit. If the loop won, check you timed execution rather than compilation; the difference being measured is the number of flushes, not the statements.
  5. Prove the plan is cached and reused. Run the same parameterised statement twice with two different parameter values (for example through sp_executesql), then inspect the plan cache with sys.dm_exec_cached_plans or compare the actual plans. Check: one compiled plan serves both values - that reuse is the feature, and also the root of parameter sniffing. If each value compiled its own plan, check you passed a parameter rather than embedding a literal; revisit “from text to a running plan”.

Check your understanding

Ordered easy to hard. Answer each before reading the answer; a wrong answer names where to look.

  1. What is the difference between a logical read and a physical read? A logical read is a page already in the buffer pool - microseconds, no disk. A physical read is a page that must come from storage, paid at the storage system’s latency while the session waits on PAGEIOLATCH_*. Both are page reads - the engine never reads a row. If you described a “row read”, revisit “the storage you are actually reading”.
  2. Why is the optimiser a cost estimator rather than an oracle? It prices candidate plans from two inputs - the cardinality it expects each operator to process and a cost model per algorithm - and a wrong cardinality makes it confidently choose the wrong algorithm, with nothing downstream able to rescue the decision. If you said it “finds a good plan”, revisit “from text to a running plan” - it finds the cheapest plan under its assumptions.
  3. A query is slow straight after an instance restart and fast later, on an identical plan. Which component explains the difference? The buffer pool - the pages were cold at restart so every read was physical; once cached, the same plan serves them logically. If you blamed the plan, notice the plan was identical: the location of the data changed, which is exactly the warm-versus-cold distinction.
  4. Why does a durable COMMIT have a latency floor no index can remove? Write-ahead logging - the log records must be hardened before COMMIT returns, and the dirty data pages flush later at checkpoint. Every commit in a fully durable transaction pays WRITELOG once, which is why micro-batching pays. If you said “the data must reach the data file first”, revisit the write path - the data write is exactly what does not block the commit.
  5. A workload gets slow overnight with no code change. Name the two suspects this lesson gives you, and how to tell them apart. The plan cache - a recompile, or a cached plan reused under a parameter value it was not compiled for, the parameter-sniffing case - and the buffer pool, cold pages after a flush or a restart. Compare the cached plan before and after for the first; compare physical against logical reads for the second. If you reached for index changes first, revisit “what this means in practice” - the plan cache is not optional context.

Where SQL Server sits

How this component relates to the rest of the stack. Items without a link are not covered here yet.

Deployed with

Commonly run alongside

  • Windows Failover Clustering

Alternatives

Solves a similar problem differently