Covers a hands-on T-SQL tuning walkthrough: baseline with SET STATISTICS IO, TIME and the actual plan, reading the plan for scans, residual predicates, key lookups and sorts, fixing SARGability and indexing, rewriting the query, and proving the improvement with logical reads and Query Store.
I start with a baseline: SET STATISTICS IO, TIME ON and the actual plan, using realistic parameter values. Logical reads per table are my main number, because elapsed time varies with cache and blocking.
Then I read the plan right to left: a clustered index scan on Orders, a seek with a residual predicate, key lookups executed thousands of times, a sort for ORDER BY. I fix non-SARGable predicates first, then add or adjust an index shaped to the query (equality columns, then the sort or range column, small INCLUDE), and trim the query (no SELECT *, no DISTINCT hiding duplicates).
I prove it by re-measuring with the same and extreme values, checking the write cost, and comparing Query Store before and after.
"First I make the problem measurable. I take the query with realistic parameter values (a typical customer and our biggest one), turn on
SET STATISTICS IO, TIME ONand the actual plan, and run it twice so the second run is from memory. Logical reads per table are my main number because they don't change with caching or blocking the way elapsed time does.Then I read the plan from the right. In this case I'd expect something like a clustered index scan on Orders, because the filter is written as
YEAR(OrderDate) = 2026andStatus <> 'Closed', which can't seek; a nested loops join to OrderLines; a key lookup to Products for the name; and a sort forORDER BY OrderDate DESC. So step one is SARGability: rewriteYEAR(OrderDate) = 2026as a half-open range, and turn the negative status test into the positive set of open statuses. Step two is an index shaped to the access pattern:CustomerIdfor equality,OrderDate DESCso the range and the sort come from the index, and only the columns the query returns inINCLUDE. Step three is the query itself:SELECT *replaced with the columns needed, and aDISTINCTthat was hiding a duplicate-producing join replaced with the right join.Then I prove it: same parameters, same measurements. Logical reads on Orders going from about 48,000 to 30 is the evidence, not 'it feels faster'. I also run the biggest customer to make sure the plan holds for skewed values, check the cost the new index adds to inserts, and after release compare Query Store duration and CPU for that query. The mistake I see is people jumping to an index before fixing the predicate: the index can't be used if the column is wrapped in a function. Measure, fix the predicate, shape the index, measure again."
| Step | What I do | Evidence |
|---|---|---|
| 1. Baseline | STATISTICS IO/TIME, actual plan, typical + extreme values | Reads per table, CPU ms |
| 2. Read the plan | Find first estimated vs actual divergence, scans, lookups, sorts | Operator properties |
| 3. Predicates | Make them SARGable, fix data types | Seek predicate appears |
| 4. Index | Equality, then range/sort, minimal INCLUDE | Lookup and sort disappear |
| 5. Query shape | Columns, joins, early filtering | Fewer rows flowing |
| 6. Re-measure | Same values, plus write path | Reads before/after |
| 7. Production | Query Store comparison | Duration and CPU trend |
| Metric | Before | After |
|---|---|---|
| Orders logical reads | 48,210 | 30 |
| OrderLines logical reads | 12,400 | 96 |
| CPU time | 1,610 ms | 2 ms |
| Elapsed | 2,050 ms | 4 ms |
This is the shape of a real fix on an [order portal] 'recent open orders' widget: the rewrite plus one index removed a scan that ran [40,000] times a day, and Azure SQL average CPU dropped by [12%] after release.
Checks whether the candidate can tune methodically and prove the result, not just name techniques.
Green flags
Red flags
A logical read is one 8 KB page read from the buffer pool. Physical reads depend on what's cached; elapsed time depends on blocking, parallelism and network. Logical reads are the most stable measure of work done, so they're the right before/after comparison. CPU time is the second.
SELECT
└─ Sort (OrderDate DESC) est 30 act 1,240
└─ Hash Match (Inner Join)
├─ Clustered Index Scan Orders rows read 2.1M act 410
│ Predicate: YEAR(OrderDate)=2026 AND CustomerId=@c AND Status<>'Closed'
└─ Nested Loops
├─ Index Seek OrderLines.IX_OrderId
└─ Key Lookup Products.PK executions 1,240
YEAR(OrderDate) hides the column from any index.Status <> 'Closed' is a negative predicate; even with an index it's a range scan of most values.| Non-SARGable | SARGable rewrite |
|---|---|
YEAR(OrderDate) = 2026 |
OrderDate >= '2026-01-01' AND OrderDate < '2027-01-01' |
Status <> 'Closed' |
Status IN ('New', 'Paid', 'Picking') |
CAST(CustomerId AS varchar) = @s |
CustomerId = @c with an int parameter |
Name LIKE '%phone%' |
Full-text, or a leading-anchored LIKE 'phone%' if acceptable |
For WHERE CustomerId = @c AND OrderDate >= @from ORDER BY OrderDate DESC:
IX_Orders_Customer_Date (CustomerId, OrderDate DESC) INCLUDE (Status, Total)
equality ^ range + sort ^ returned/filtered ^
Status could be a key column if it's very selective; with three open statuses as a residual on a handful of rows per customer it's fine as an INCLUDE. A filtered index (WHERE Status IN (...)) is an option if open orders are a small fraction.
SELECT
└─ Nested Loops
├─ Index Seek Orders.IX_Orders_Customer_Date act 410 (ordered, no sort)
└─ Nested Loops
├─ Index Seek OrderLines.IX_OrderId_Cover (INCLUDE ProductId, Qty)
└─ Clustered Index Seek Products.PK (Name from clustered row)
The Products lookup becomes a clustered index seek on a small table, which is cheap; covering Products isn't worth it.
INCLUDE (Status, Total) for no INCLUDE and count key lookups.Schema, the slow query, and the tuned version with measurements.
CREATE TABLE dbo.Products (ProductId int PRIMARY KEY, Name nvarchar(200) NOT NULL);
CREATE TABLE dbo.Orders (
OrderId bigint IDENTITY PRIMARY KEY,
CustomerId int NOT NULL,
OrderDate datetime2(0) NOT NULL,
Status varchar(20) NOT NULL,
Total decimal(12,2) NOT NULL
);
CREATE TABLE dbo.OrderLines (
OrderId bigint NOT NULL REFERENCES dbo.Orders(OrderId),
LineNo int NOT NULL,
ProductId int NOT NULL REFERENCES dbo.Products(ProductId),
Qty int NOT NULL,
CONSTRAINT PK_OrderLines PRIMARY KEY (OrderId, LineNo)
);
SET STATISTICS IO, TIME ON;
DECLARE @CustomerId int = 1042;
-- BEFORE: non-SARGable date, negative status test, SELECT *, DISTINCT hiding duplicates
SELECT DISTINCT o.*, p.Name
FROM dbo.Orders o
JOIN dbo.OrderLines l ON l.OrderId = o.OrderId
JOIN dbo.Products p ON p.ProductId = l.ProductId
WHERE o.CustomerId = @CustomerId
AND YEAR(o.OrderDate) = 2026
AND o.Status <> 'Closed'
ORDER BY o.OrderDate DESC;
-- Table 'Orders'. logical reads 48210 | CPU 1610 ms, elapsed 2050 ms
-- FIX 1: index shaped to equality + range/sort, minimal INCLUDE
CREATE INDEX IX_Orders_Customer_Date
ON dbo.Orders (CustomerId, OrderDate DESC) INCLUDE (Status, Total)
WITH (ONLINE = ON);
-- AFTER: SARGable range, positive status set, only needed columns, one row per line
SELECT o.OrderId, o.OrderDate, o.Status, o.Total, l.LineNo, l.Qty, p.Name
FROM dbo.Orders o
JOIN dbo.OrderLines l ON l.OrderId = o.OrderId
JOIN dbo.Products p ON p.ProductId = l.ProductId
WHERE o.CustomerId = @CustomerId
AND o.OrderDate >= '2026-01-01' AND o.OrderDate < '2027-01-01'
AND o.Status IN ('New', 'Paid', 'Picking')
ORDER BY o.OrderDate DESC;
-- Table 'Orders'. logical reads 30 | CPU 2 ms, elapsed 4 ms
The same query from .NET with Dapper and correctly typed parameters (DECLARE above is only for the SSMS demo; the app sends parameters):
namespace Shop.Data;
using Dapper;
using Microsoft.Data.SqlClient;
public sealed record OpenOrderLine(long OrderId, DateTime OrderDate, string Status,
decimal Total, int LineNo, int Qty, string Name);
public sealed class OpenOrdersQuery(string connectionString)
{
private const string Sql = """
SELECT o.OrderId, o.OrderDate, o.Status, o.Total, l.LineNo, l.Qty, p.Name
FROM dbo.Orders o
JOIN dbo.OrderLines l ON l.OrderId = o.OrderId
JOIN dbo.Products p ON p.ProductId = l.ProductId
WHERE o.CustomerId = @CustomerId
AND o.OrderDate >= @From AND o.OrderDate < @To
AND o.Status IN ('New', 'Paid', 'Picking')
ORDER BY o.OrderDate DESC;
""";
public async Task<IReadOnlyList<OpenOrderLine>> RunAsync(int customerId, int year, CancellationToken ct)
{
await using var conn = new SqlConnection(connectionString);
var args = new { CustomerId = customerId, From = new DateTime(year, 1, 1), To = new DateTime(year + 1, 1, 1) };
var rows = await conn.QueryAsync<OpenOrderLine>(new CommandDefinition(Sql, args, cancellationToken: ct));
return rows.AsList();
}
}
YEAR(col) or an implicit conversion still prevents a seek. Instead: Make the predicate SARGable first.sp_executesql and check estimated vs actual rows for both.DISTINCT to remove duplicates created by a join. Why it is wrong: It adds a sort or hash over every joined row and hides a logic error. Instead: Ask why there are duplicates. If you only need to know that a related row exists (customers who ordered product X), use WHERE EXISTS (SELECT 1 FROM dbo.OrderLines l WHERE l.OrderId = o.OrderId AND l.ProductId = @p), which stops at the first match and returns each order once. Keep DISTINCT for genuinely wanting unique values of a column (the list of states customers live in).SELECT *. Why it is wrong: Prevents covering indexes and moves more data. Instead: Select only needed columns.Tuning is a measurement exercise, not a bag of tricks. The order matters: predicate first (an index can't help a hidden column), index second (shaped to equality, range and sort), query shape third, and always prove it with the same numbers. A senior also asks whether the query should exist in this form: a widget polled every five seconds might be better served from a cache or a summary table.
Fix scope proportionately: a rewrite costs nothing at runtime; an index costs on every write; a hint costs future flexibility.
| Fix | When it fits | Cost | When not to |
|---|---|---|---|
| SARGable rewrite | Functions, conversions, negative predicates | None at runtime | — |
| New / adjusted index | Repeated access pattern on a hot path | Write and storage cost | Write-heavy tables at index budget |
| Covering INCLUDE | Lookups with high execution counts | Wider index | Few rows or small lookup table |
| Filtered index | Small subset (open orders) | Parameter matching gotcha | Filter doesn't match the query |
| Caching / summary table | Very frequent reads, tolerant of staleness | Invalidation complexity | Strongly consistent data |
A predicate is SARGable (Search ARGument-able) when the optimiser can turn it into a seek range on an index. The rule: leave the column bare and put any calculation on the other side.
YEAR(OrderDate) = 2026 scans; OrderDate >= '2026-01-01' AND OrderDate < '2027-01-01' seeks.Price * 1.1 > 100 scans; Price > 100 / 1.1 seeks.varchar column vs nvarchar parameter) often scans; match types.LIKE 'abc%' seeks; LIKE '%abc' cannot.ISNULL(col, 0) = 0 scans; col = 0 OR col IS NULL seeks.When the expression is unavoidable, index a persisted computed column. Trade-off: the rewrite is free; the computed column costs storage and writes.
A key lookup happens when a non-clustered index finds the rows but lacks some columns the query needs, so SQL Server goes back to the clustered index for each row (a RID lookup on a heap). Each one is 3–4 random logical reads.
A covering index holds every column the query references, so no lookup is needed.
WHERE, JOIN and ORDER BY.Lookups hurt when they run for thousands of rows; past the tipping point the optimiser scans instead. Trade-off: covering speeds a query but widens the index and every write.
An estimated plan is what the optimiser would do; an actual plan is the same plan plus runtime numbers: actual rows, number of executions, memory grant used and runtime warnings. Data flows right to left; thick arrows mean many rows.
The first thing I check is estimated vs actual rows on each operator: a big gap means a bad estimate, and almost every bad plan follows from one. Then I look for scans where I expected seeks, key lookups executed thousands of times, the join type (nested loops with a huge outer input is a red flag), and warnings such as CONVERT_IMPLICIT, spills and residual predicates.
Cost percentages are estimates too, so I confirm with logical reads from SET STATISTICS IO.
How to tell it (STAR)
**S:** Our [order portal]'s home page widget took [2 seconds] and was the top CPU consumer in Query Store. **T:** I picked it up to bring it under [100 ms]. **A:** I baselined with STATISTICS IO, which showed [48,000] reads on Orders, and the plan showed a scan because the query wrapped OrderDate in YEAR() and used a negative status test. I rewrote the predicate as a range and a positive status list, dropped the DISTINCT that was hiding a join problem, and added one index matching the filter and sort. Then I re-measured with our biggest customer and checked insert cost. **R:** Reads dropped to [30] per call, page p95 fell to [120 ms], and database CPU fell by about [12%].
Last updated 23 Nov 2026.