Reading a plan. The operators to recognise: a Clustered Index Scan is a table scan, acceptable on small tables and a problem on large ones. A Key Lookup means a nonclustered index found the rows but had to go back to the table for columns it did not have - fix it with INCLUDE. A Hash Match for a join is fine on large unsorted inputs and suspicious on small ones. Sort operators are expensive and frequently avoidable with the right index order. And a thick arrow between operators means many rows; the single most useful thing in a graphical plan is comparing estimated against actual row counts, because a large gap means the optimiser is choosing on bad information.
Indexes. The clustered index is the table. A nonclustered index is a separate structure with its own copy of the key columns, plus INCLUDEd payload columns, pointing back via the clustered key. INCLUDE is the fix for a Key Lookup: the columns are stored at the leaf level only, so they add no cost to the tree. A filtered index indexes a subset and is small and sharp.
Columnstore is a different storage format: columns stored separately, heavily compressed, with batch-mode execution. For an analytical query aggregating millions of rows over a few columns it is frequently ten to a hundred times faster than rowstore. For a point lookup it is much worse. A clustered columnstore index on the fact table with a few nonclustered rowstore indexes for lookups is the standard warehouse shape.
Statistics drive every estimate. They are sampled, auto-updated when roughly 20% of rows change - which on a hundred-million-row table is twenty million rows of drift before anything happens - and they are the most common cause of a plan that was fine last month.
Parameter sniffing is the subtlest problem in this module. SQL Server compiles a procedure's plan using the parameter values of the first execution and caches it. If one customer has ten orders and another has ten million, the plan compiled for the first is catastrophic for the second. The symptom is "the same query is fast for most people and times out for one". The remedies - OPTIMIZE FOR UNKNOWN, RECOMPILE, splitting into separate procedures, or disabling parameter sniffing for one query - each have costs, and the right one depends on the data distribution.
Query Store records query text, plans, and runtime statistics over time. It is the single most valuable diagnostic feature added to SQL Server in a decade, it is on by default from 2022, and it lets you answer "what changed" rather than guess. It can also force a known-good plan.
Laboratory exercise 4 - a measured improvement.
Load at least two million rows with a skewed distribution - some customers with thousands of orders, most with a handful - because uniform data hides exactly the problems this module is about.
Declare a baseline: five queries, with p50, p95 and p99 latency, throughput, logical reads and the execution plan for each.
Apply the techniques one at a time, re-measuring: a covering index chosen from a Key Lookup, a filtered index, a columnstore index on the fact table, and a statistics update. Then demonstrate parameter sniffing: write a procedure, execute it first with the small customer and then the large one, and capture the plan and duration; clear the cache, reverse the order, and capture both again. Apply a remedy and justify your choice.
Deliverable: the benchmark report with all three percentiles at each step, plans before and after, the parameter sniffing demonstration with all four measurements, and at least one change that did not help with an explanation of why.
-- ------------------------------------------------------------------
-- Reading a plan. Turn on the numbers that matter first.
-- ------------------------------------------------------------------
SET STATISTICS IO, TIME ON;
SET SHOWPLAN_XML OFF; -- in SSMS/ADS, Ctrl+M for the actual plan
SELECT c.name, SUM(l.quantity * l.unit_price) AS revenue
FROM sales.customer AS c
JOIN sales.[order] AS o ON o.customer_id = c.customer_id
JOIN sales.order_line2 AS l ON l.order_id = o.order_id
WHERE o.ordered_at >= '2026-01-01'
GROUP BY c.name;
-- STATISTICS IO gives you the number that does not lie:
-- Table 'order_line2'. Scan count 1, logical reads 284,117
--
-- Logical reads is pages touched. It is stable across runs where
-- duration is not, and it is the metric to optimise. Elapsed time on
-- a warm cache tells you about your cache, not about your query.
-- ------------------------------------------------------------------
-- The Key Lookup, and its fix.
-- ------------------------------------------------------------------
CREATE NONCLUSTERED INDEX IX_order_date ON sales.[order] (ordered_at);
-- Plan now shows:
-- Index Seek (NonClustered) on IX_order_date
-- -> Key Lookup (Clustered) on PK_order <- 1 lookup PER ROW
-- -> Nested Loops
--
-- The seek found the rows; it then had to visit the table for
-- customer_id and status. INCLUDE puts them at the index leaf:
CREATE NONCLUSTERED INDEX IX_order_date_covering
ON sales.[order] (ordered_at)
INCLUDE (customer_id, status);
-- Key Lookup gone. INCLUDEd columns live only at the leaf, so they
-- cost nothing in the tree and nothing in a seek.
-- ------------------------------------------------------------------
-- Columnstore: a different storage format, for a different question.
-- ------------------------------------------------------------------
CREATE CLUSTERED COLUMNSTORE INDEX CCI_fact_sales ON sales.fact_sales;
-- Columns stored separately and compressed; batch-mode execution.
-- Aggregating millions of rows over a few columns: often 10-100x.
-- Looking up one row by key: much WORSE than rowstore.
--
-- The standard warehouse shape is both:
CREATE NONCLUSTERED INDEX IX_fact_order
ON sales.fact_sales (order_id); -- rowstore, for the lookups
-- ------------------------------------------------------------------
-- Statistics: the reason last month's plan is this month's incident.
-- ------------------------------------------------------------------
SELECT s.name AS stat_name, sp.last_updated, sp.rows, sp.rows_sampled,
sp.modification_counter
FROM sys.stats AS s
CROSS APPLY sys.dm_db_stats_properties(s.object_id, s.stats_id) AS sp
WHERE s.object_id = OBJECT_ID('sales.order_line2')
ORDER BY sp.last_updated;
-- modification_counter high and last_updated old = the optimiser is
-- estimating from a picture of a different table.
UPDATE STATISTICS sales.order_line2 WITH FULLSCAN;
-- ------------------------------------------------------------------
-- PARAMETER SNIFFING. The subtlest problem here.
-- ------------------------------------------------------------------
CREATE OR ALTER PROCEDURE sales.orders_for_customer @customer_id int
AS
SELECT o.order_id, o.ordered_at, l.product_id, l.quantity
FROM sales.[order] AS o
JOIN sales.order_line2 AS l ON l.order_id = o.order_id
WHERE o.customer_id = @customer_id;
GO
-- Customer 42 has 3 orders; customer 7 has 4 million.
DBCC FREEPROCCACHE; -- sandbox only, never prod
EXEC sales.orders_for_customer @customer_id = 42; -- plan: nested loops
EXEC sales.orders_for_customer @customer_id = 7; -- SAME plan. Hours.
DBCC FREEPROCCACHE;
EXEC sales.orders_for_customer @customer_id = 7; -- plan: hash match
EXEC sales.orders_for_customer @customer_id = 42; -- SAME plan. Wasteful.
--
-- Same procedure, same data, opposite behaviour depending on which
-- call compiled it. Presents as "it is fast for everyone except one
-- customer", which is why it is so often misdiagnosed.
-- The remedies, each with a cost:
-- OPTION (RECOMPILE) best plan every time; CPU per call
-- OPTION (OPTIMIZE FOR UNKNOWN) one average plan; good for nobody
-- OPTION (OPTIMIZE FOR (@customer_id = 7)) pick the plan you want
-- separate procedures for big and small customers
-- Query Store: force a known-good plan
-- ------------------------------------------------------------------
-- Query Store: on by default from 2022, and the answer to "what
-- changed".
-- ------------------------------------------------------------------
ALTER DATABASE SalesWorkshop SET QUERY_STORE = ON
(OPERATION_MODE = READ_WRITE, DATA_FLUSH_INTERVAL_SECONDS = 900,
QUERY_CAPTURE_MODE = AUTO, MAX_STORAGE_SIZE_MB = 1024);
-- Queries whose plan changed and got worse - the regression report
-- that replaces guessing:
SELECT TOP 20
q.query_id, LEFT(t.query_sql_text, 60) AS query_text,
rs.plan_id, rs.count_executions,
CAST(rs.avg_duration / 1000.0 AS decimal(10,2)) AS avg_ms,
rs.last_execution_time
FROM sys.query_store_query AS q
JOIN sys.query_store_query_text AS t ON t.query_text_id = q.query_text_id
JOIN sys.query_store_plan AS p ON p.query_id = q.query_id
JOIN sys.query_store_runtime_stats AS rs ON rs.plan_id = p.plan_id
WHERE q.query_id IN (
SELECT query_id FROM sys.query_store_plan
GROUP BY query_id HAVING COUNT(DISTINCT plan_id) > 1
)
ORDER BY rs.avg_duration DESC;
-- Force the good one:
EXEC sp_query_store_force_plan @query_id = 42, @plan_id = 17;
Discussion
No questions on this topic yet. Sign in to ask the first one.