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

📚 Interview question

Here is a slow query: it lists a customer's recent open orders with product names and takes 2 seconds. Tune it step by step in front of me. How do you measure it, what do you look for in the plan (scans, seeks, key lookups, sorts), what do you change, and how do you prove the change worked?

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.

Mid-Level Sql Intermediate execution-plans indexes query-tuning sargability sql-server t-sql

🎯 Key points

  • Baseline first: SET STATISTICS IO, TIME ON and the actual plan, with typical and extreme parameter values sent as parameters (not local variables)
  • Logical reads per table are the primary metric; elapsed time is noisy (cache, blocking)
  • Read the plan right to left: scans on large tables, seeks with residual predicates, key lookup executions, sorts and tempdb spill warnings
  • Fix non-SARGable predicates first (functions on columns, implicit conversions, leading wildcards)
  • Design an index for the access pattern: equality columns, then range or ORDER BY column, INCLUDE only what is needed
  • Reduce rows early: apply the most selective filter to the largest table so fewer rows reach the joins; replace DISTINCT-over-joins with EXISTS
  • Keep it one reusable, parameterised plan that is good for skewed values; check the write cost of any new index
  • Confirm in production with Query Store before/after (duration, CPU, reads)

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 ON and 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) = 2026 and Status <> 'Closed', which can't seek; a nested loops join to OrderLines; a key lookup to Products for the name; and a sort for ORDER BY OrderDate DESC. So step one is SARGability: rewrite YEAR(OrderDate) = 2026 as 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: CustomerId for equality, OrderDate DESC so the range and the sort come from the index, and only the columns the query returns in INCLUDE. Step three is the query itself: SELECT * replaced with the columns needed, and a DISTINCT that 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."


My tuning loop

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

Before and after (this example)

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can tune methodically and prove the result, not just name techniques.

Green flags

  • Baselines with STATISTICS IO/TIME and the actual plan.
  • Fixes SARGability before indexing.
  • Designs the index around equality, range and ORDER BY with a small INCLUDE.
  • Tests skewed values and the write path; confirms in Query Store.
  • Knows what newer engine features do and don't fix (adaptive joins, memory grant feedback smooth bad estimates but don't make a scan into a seek).

Red flags

  • 'Add an index' with no measurement.
  • Uses elapsed time from one run as proof.
  • Hides join duplicates with DISTINCT.

📚 Learn in depth

1. Why logical reads are the metric

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.

2. The plan before

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
  • The Orders scan reads 2.1 million rows to return 410: the predicate is a residual, not a seek.
  • 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.
  • The sort is needed because nothing provides OrderDate order.

3. Making predicates SARGable

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

4. Shaping the index

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.

5. Plan after

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.

6. Checking side effects

  • New indexes add write cost: measure insert/update duration on Orders before and after.
  • Plans for other queries may change; Query Store's Regressed Queries report after release catches it.
  • Skewed customers: test the largest, and check estimated vs actual rows there.

Try it yourself

  1. Build the schema below with 2 million orders and run the 'before' query with STATISTICS IO.
  2. Rewrite only the YEAR predicate (no new index) and note that reads don't change much; then add the index.
  3. Swap INCLUDE (Status, Total) for no INCLUDE and count key lookups.
  4. Compare the plan for a customer with 10 orders and one with 200,000.
  5. Measure 10,000 inserts into Orders with and without the new index.

💻 Code

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

⚠ Common mistakes

  • Mistake: Judging improvement by elapsed time from one run. Why it is wrong: Caching, blocking and parallelism make it noisy. Instead: Compare logical reads and CPU over several runs.
  • Mistake: Adding an index before fixing the predicate. Why it is wrong: YEAR(col) or an implicit conversion still prevents a seek. Instead: Make the predicate SARGable first.
  • Mistake: Testing with one 'nice' parameter value. Why it is wrong: The cached plan is reused for every value, and skewed values may need a different shape. Instead: Test typical and extreme values through sp_executesql and check estimated vs actual rows for both.
  • Mistake: Using 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).
  • Mistake: Keeping SELECT *. Why it is wrong: Prevents covering indexes and moves more data. Instead: Select only needed columns.
  • Mistake: Covering every lookup. Why it is wrong: A lookup on a small table or for a few rows is cheap; wide indexes cost writes. Instead: Cover only lookups with high execution counts on hot paths.
  • Mistake: Ignoring the write-path cost of the new index. Why it is wrong: Inserts and updates slow down. Instead: Measure the write path and check index usage later.
  • Mistake: Ignoring spill warnings on Sort or Hash operators. Why it is wrong: A spill means the memory grant was too small and the operator is writing to tempdb, often from a bad row estimate. Instead: Fix the estimate or remove the sort with an index that supplies the order.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate rewrites a function on a column Why: Checks the full range of non-SARGable patterns
    How to answer

    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.
    • An implicit conversion of the column (e.g. 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.

  2. When: Candidate removes a key lookup with INCLUDE Why: Checks when covering is worth it
    How to answer

    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.

    • Key columns are sorted and searchable: use them for WHERE, JOIN and ORDER BY.
    • INCLUDE columns sit only in the leaf level: not sorted, not counted in the key size limit, cheaper to maintain. Use them for columns that are only selected.

    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.

  3. When: Candidate reads the plan right to left Why: Checks plan-reading depth: estimates vs actuals, residual predicates
    How to answer

    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.

🛠 Real-world problems: how you handle them

'Recent open orders' widget scanning Orders 40,000 times a day
Situation
A [B2B order portal] showed each customer their recent open orders on the home page. The Orders table had [2.1 million] rows on [Azure SQL General Purpose, 4 vCores]; the widget ran [about 40,000] times a day.
Signals
Query Store's Top Resource Consuming report ranked the widget query first by total CPU ([~18%] of the database). Application Insights showed p95 [2 s] for the home page dependency; users reported slow logins.
Investigation
STATISTICS IO showed [48,000] logical reads on Orders per execution. The actual plan had a clustered index scan with a residual predicate `YEAR(OrderDate) = @y AND Status <> 'Closed'`, a sort, and key lookups to Products. The query used `SELECT DISTINCT o.*` to hide duplicates from the OrderLines join.
Resolution
Rewrote the predicate as a half-open date range and a positive status list, selected only needed columns, removed DISTINCT, and added `IX_Orders_Customer_Date (CustomerId, OrderDate DESC) INCLUDE (Status, Total)` with ONLINE = ON. Reads fell to [30] per execution.
Prevention
Added the query to a performance test with typical and largest customers; a PR checklist item for non-SARGable predicates; a weekly Query Store top-10 review.

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%].

↩ Usually asked after

More in Query Performance

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me