Blog
AdvancedReferenceSQL Server Performance Internals

SELECT - diagnosis and optimisation

Making reads fast under load - the plan's access path, SARGability, covering and filtered indexes, join choice, spills and memory grants, parameter sensitivity, pagination, and the evidence that tells a plan problem from an estimate problem.

Applies to
SQL Server2016-2025 (13.x-17.x)parameter-sensitive-plan optimisation is 2022 (16.x) and later
matureUpdated Reviewed
advancedAssumes production experience with the basics.

What you will be able to do

  • Walk a SELECT diagnosis flowchart from symptom to named cause.
  • Rewrite a non-SARGable predicate so an index seek becomes possible.
  • Design a covering or filtered index for a real query and state its write cost.
  • Diagnose a sort or hash spill to a memory-grant or estimate cause.
  • Choose the pagination pattern for a large result set and say why OFFSET costs what it does.

Concepts covered

A slow SELECT is not a slow query - it is a plan making a choice under an assumption, and the diagnosis is finding which assumption was wrong. The mechanism course covers what the optimiser is; this lesson is what you do with one when it is slow.

The analogy that makes access paths stick is the index at the back of a book. A covering index is one that prints the answer beside the entry, so you never leave the index itself; a non-covering one gives only a page number, and every row you want costs a second trip into the text - that trip is the key lookup. The most common beginner mistake is creating an index and declaring the query fixed without a baseline or an after measurement: if the logical reads did not fall, the plan never used it, and the index is a write tax with no refund.

The SELECT diagnosis flowchart

Slow SELECT - from symptom to cause

  1. Elapsed vs CPU?

    elapsed >> cpu means waiting; equal means working

    dm_exec_requests compares the two clocks - waiting is a contention problem, go to cross-operation

  2. Wait type

    PAGEIOLATCH = I/O; LCK_M = blocked; CXCONSUMER = parallel skew

    The wait names which part of the machine holds the request

  3. Actual plan

    Estimated vs actual rows on each edge

    A divergence is an estimate problem; a match is a design problem

  4. The costly operator

    Scan, lookup, spill, or sort owns the time

    The fix targets this operator - not the whole query

  5. Fix + validate

    Before/after: logical reads, elapsed, p95

    If the reads did not fall, the fix was cosmetic

The first fork is working-versus-waiting; it splits a plan problem from a contention problem before the plan is even opened.

Access paths - seek, scan, lookup

A clustered index is the table sorted on its key; a nonclustered index is a separate B+ tree whose leaves hold the key columns plus a pointer back to the row. Three access patterns follow:

  • Seek - descend the tree on the key’s leftmost columns. Scales with depth, not size.
  • Scan - read every leaf. Honest when most rows are needed; a symptom when few are.
  • Key lookup - the index found the pointer but not the columns; a second read per row.
-- Inefficient: nonclustered index on (status) alone
SELECT order_id, total FROM orders WHERE status = 'shipped';
-- Plan: seek ix_status, then one key lookup per row for order_id, total.

-- Optimised: covering index - the leaf carries every column the query reads
CREATE NONCLUSTERED INDEX ix_orders_status
ON dbo.orders (status) INCLUDE (order_id, total);
-- Plan: seek only - the lookup disappears, logical reads collapse.

A filtered index narrows further when the workload is a subset - WHERE status = 'open' on a table where 2 percent is open:

CREATE NONCLUSTERED INDEX ix_open_orders ON dbo.orders (created_at)
INCLUDE (total) WHERE status = 'open';
-- Smaller, hotter, cheaper to maintain - but it serves only queries that
-- prove the same WHERE clause, so it is a scalpel, not a general index.

SARGability - whether the key can be used at all

A predicate is sargable when the optimiser can use an index seek on it. Wrap the column in a function or arithmetic and the histogram becomes useless - the seek collapses to a scan:

-- Non-sargable: the function hides the column
WHERE YEAR(created_at) = 2025

-- Sargable rewrite: the column is naked, a range uses the key
WHERE created_at >= '20250101' AND created_at < '20260101'

-- Non-sargable: implicit conversion wraps the column
WHERE varchar_col = 12345            -- int literal on a varchar column

-- Sargable: match the types
WHERE varchar_col = '12345'

Other non-sargable shapes: leading-wildcard LIKE '%x', col + 1 = x, NOT/<> on a skewed column, column-to-column arithmetic. The test is always the actual plan - did the seek appear?

Joins, sorts, spills, and grants

The optimiser picks nested loops (cheap for few outer rows, each inner is a seek), hash match (builds a table from the bigger side; memory-hungry), or merge join (both inputs sorted). The choice is driven by the estimated row count - an underestimate can pick nested loops for millions of outer rows and the plan melts.

Spills are the memory-grant failure made visible: a sort or hash granted less memory than the actual rows need writes the overflow to tempdb - a warning on the operator in the actual plan, and tempdb I/O where CPU was expected. Causes: an underestimate (grant sized for the estimate) or a genuinely huge sort. Fixes: fix the estimate, let memory-grant feedback learn the grant (row mode from 2019, persisted through Query Store on 2022+), or reduce rows before the operator. Parallelism is a grant-and-worker question too - the CXCONSUMER wait means the coordinator sits on one slow thread, usually a skewed plan.

Parameter sensitivity and pagination

Parameter sniffing is covered in the mechanism course; the operation-level rule: when the same procedure is fast for one value and slow for another, compare the two plans in Query Store and pick OPTIMIZE FOR, RECOMPILE, or on 2022+ let PSP keep two plans.

Pagination has an honest cost model:

-- OFFSET: reads and discards all preceding rows - page 10,000 pays for 500,000 skips
SELECT * FROM t ORDER BY id OFFSET 500000 ROWS FETCH NEXT 50 ROWS ONLY;

-- Keyset (seek) pagination: seeks to the last key and reads forward - O(page size)
SELECT * FROM t WHERE id > @last_id ORDER BY id OFFSET 0 ROWS FETCH NEXT 50 ROWS ONLY;

OFFSET is fine for shallow pages; keyset is the only pattern that stays flat as depth grows.

Index-tuning validation flowchart

Did the index fix actually work

  1. Baseline first

    Before: logical reads, cpu, elapsed, p95 on the real query

    SET STATISTICS IO, TIME ON, or Query Store - the same instrument as the after-run

  2. Apply the index

    Create it on a test copy if the table is hot

    Note the write cost it just added - it is not free

  3. Measure after

    Same query, same data, same instrument

    Logical reads down and p95 down = the seek happened

  4. Keep or revert

    Reads fell and write cost acceptable = keep

    Reads unchanged = the plan did not use it - the index is dropped, not tolerated

A new index that did not move the measurement is a write tax with no refund - validate against the baseline, then keep or revert.

Readers and writers

Under locking READ COMMITTED, a SELECT takes shared locks and a writer’s exclusive lock queues behind them - and the reader queues behind the writer’s lock too. RCSI removes both directions by serving the reader a row version from tempdb; the reader never blocks and is never blocked, at the cost of version-store traffic. On a mixed read/write OLTP box this is usually the single highest-leverage read-side change - and the cross-operation lesson quantifies when it is not.

The diagnostic toolkit

-- Who is waiting right now, on what
SELECT session_id, wait_type, wait_time_ms, blocking_session_id, cpu_time, total_elapsed_time
FROM sys.dm_exec_requests
WHERE session_id > 50 AND status <> 'background';
-- Expected: the slow request's wait_type names the resource; blocking_session_id names a holder.

-- Per-query cost across executions - find the expensive shape, not one run
SELECT TOP 10 qs.execution_count, qs.total_logical_reads, qs.total_worker_time,
  qs.total_elapsed_time, SUBSTRING(st.text, 1, 120) AS query_text
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st
ORDER BY qs.total_logical_reads DESC;
-- Expected: the top logical-read consumer is the plan to open in the actual execution plan.

What to measure, before and after

Metric Instrument The pass criterion
Logical reads SET STATISTICS IO ON Falls by the expected factor when a scan becomes a seek
Elapsed / CPU SET STATISTICS TIME ON Both fall; a drop in elapsed alone can hide a wait change
p95/p99 The application or a timed loop The tail improves, not only the median
Plan shape Actual execution plan The seek appears; the lookup or spill disappears

Advanced exercise and answer key

Exercise. A query WHERE order_date >= @from on a 10M-row table uses a nonclustered index on order_date and is still slow. The actual plan shows a seek and millions of key lookups. Propose two fixes with different trade-offs; state which you would deploy first and why.

Answer. The lookup is the cost, not the seek. (1) Add the selected columns as INCLUDE to make it covering - kills the lookup, charges every write on order_date a wider leaf. (2) Leave the index and reduce rows before output - a narrower WHERE or a different key. Deploy (1) first if reads dominate; the include cost is paid once per write, the lookup cost per read, so the read:write ratio decides - a write-hot table may favour (2).

Guided practice

A beginner exercise, worked step by step in a scratch database. It builds a small orders table and then walks the access-path and SARGability points from the lesson against real plans. Work each step and check yourself before moving on.

  1. Build the orders table. Create dbo.orders (order_id INT IDENTITY PRIMARY KEY, status VARCHAR(20) NOT NULL, total DECIMAL(10,2) NOT NULL, created_at DATETIME2 NOT NULL) and fill it with rows, most of them status = 'shipped' and a small number 'open' - a few INSERT ... SELECT batches off sys.all_objects is enough. Check: SELECT status, COUNT(*) FROM dbo.orders GROUP BY status; shows the split. The skew is a convenience for the later steps, not a requirement - a table you can plan against is.
  2. Watch the key lookup happen. Create CREATE NONCLUSTERED INDEX ix_status ON dbo.orders (status);, turn on the actual execution plan and SET STATISTICS IO ON, then run SELECT order_id, total FROM dbo.orders WHERE status = 'shipped'; Check: the plan seeks ix_status and then does a key lookup per row for order_id and total - the index found the pointer but not the columns. If it scanned the clustered index instead, the table may be small enough that the scan is honestly cheaper - add rows, or revisit the access-path definitions.
  3. Make the index covering. Replace it with CREATE NONCLUSTERED INDEX ix_orders_status ON dbo.orders (status) INCLUDE (order_id, total); and rerun the same query. Check: the lookup disappears and logical reads fall - the leaf now carries every column the query reads. If the reads did not fall, the plan did not use the new index, which is exactly the keep-or-revert stage of the validation flowchart - revisit it.
  4. Break the predicate, then repair it. With an index on created_at, run the query with WHERE YEAR(created_at) = 2025, then with WHERE created_at >= '20250101' AND created_at < '20260101', comparing the plans. Check: the function-wrapped form scans and the range form seeks - wrapping the column hides it from the histogram. If the rewrite still scans, check the rest of the predicate against the non-sargable list - a leading-wildcard LIKE or a mismatched type does the same damage.
  5. Feel the OFFSET cost. Order by order_id and compare OFFSET 500 ROWS FETCH NEXT 50 ROWS ONLY with the keyset form WHERE order_id > @last_id ORDER BY order_id OFFSET 0 ROWS FETCH NEXT 50 ROWS ONLY, watching logical reads as you deepen the offset. Check: keyset reads about one page of rows at any depth, while OFFSET keeps reading and discarding everything before the page. If OFFSET looked cheap, deepen it until the skip cost shows - revisit the pagination cost model.

Check your understanding

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

  1. What makes a predicate sargable? The column is naked - no function, arithmetic or implicit conversion wrapping it - so the optimiser can use the index key and the histogram for a seek. If you answered “it uses an index” without the seek, revisit the SARGability section - a scan through an index is not the point.
  2. Why does a covering index remove the key lookup? The nonclustered leaf already carries every column the query reads, so no second read per row goes back to the clustered row. The INCLUDE columns are what make it covering. If you said “it is just a bigger index”, revisit the access paths - the mechanism is the second read disappearing.
  3. An actual plan shows estimated rows far below actual rows at one operator. Which kind of problem is that? An estimate problem - the divergence between estimated and actual rows is the evidence, and it misleads every join, grant and spill decision downstream. A match would point at a design problem instead. Revisit the diagnosis flowchart’s third stage.
  4. Why does OFFSET pagination degrade with depth while keyset stays flat? OFFSET reads and discards every row before the page, so deep pages pay for all the skipped rows; keyset seeks to the last key and reads forward, so cost tracks the page size, not the depth. Revisit the pagination cost model if you concluded OFFSET is fine at any depth.
  5. The same stored procedure is fast for one parameter value and slow for another. What is happening, and what are the honest options? Parameter sensitivity - the cached plan was compiled for one value and is a bad shape for the other. Compare the two plans in Query Store, then OPTIMIZE FOR, RECOMPILE, or on 2022+ the parameter-sensitive-plan optimisation. If your first move was “add an index”, revisit the parameter-sensitivity rule - the index is the same; the plan shape is what differs per value.

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