SQL Server Query Tuning: Read the Plan, Fix the Cause, Prove It
Most queries need only a few rows: one case, a customer's open items, the bookings of one day. They become slow when the database reads far more than it has to. Query tuning means finding out where that happens, changing it in a targeted way and proving that the change works.
This path expands the section "One query is always slow" of our SQL Server performance guide. It is written for two groups of readers: developers who may change the code, and administrators who look after a vendor's application and may not change its code. Each group gets its own path at the end.
Query tuning in one sentence
Query tuning is about one query, not the whole server. So first rule out that the query is merely waiting, for example for a lock held by another session. Tuning does not help there; the path Blocking and timeouts does. If the query stays slow without waiting, the cause is the work it does itself. That work is what this page is about.
The example that runs through this path
An application manages cases for 50 tenants. One of them is much larger than all the others: it owns 600,000 of the 1,000,000 cases. Many line-of-business applications have that one large customer, site or tenant. The application regularly asks for a tenant's open cases since a given date:
CREATE OR ALTER PROCEDURE dbo.OffeneVorgaenge @MandantId int, @Ab datetime2(0)
AS
SELECT VorgangId, Kennung, Betrag, Angelegt
FROM dbo.Vorgang
WHERE MandantId = @MandantId AND Status = 0 AND Angelegt >= @Ab;The object names are German, as in our lab: Vorgang is the case, MandantId the tenant, Angelegt the creation date, Betrag the amount. For small tenants the procedure is fast. For the large one it is sometimes fast and sometimes not. The following steps show how to find, measure and fix that. All figures come from our lab, not from a customer system.
Lab setup: synthetic database with 1,000,000 cases (32,313 data pages), tenant 1 owning 60%. SQL Server 2017, 2019, 2022 and 2025, each with the compatibility levels of its version (140 to 170). We measured logical reads: the number of 8 KB pages a query reads in memory. They do not depend on the hardware and repeat exactly with the same data. Unless stated otherwise, the values were the same on all versions.
Step 1: Find the right query
The slowest single execution is rarely the best place to start. A query that takes one second and runs a thousand times a day costs more than one that takes ten seconds once. So look for the total effort in the time window: reads across all executions.
If Query Store has collected data in the database, this query lists the candidates. Whether it is enabled and how to set it up is covered in Setting up Query Store.
/* ============================================================================
PSG · Query tuning, step "Find": most expensive queries in a time window
----------------------------------------------------------------------------
CAUTION: Read-only, reads the Query Store of the current database.
Still run it on a test or staging system first and coordinate with
operations and the software vendor.
Permissions: VIEW DATABASE STATE (from SQL Server 2022,
VIEW DATABASE PERFORMANCE STATE is enough). Runs on SQL Server 2016 and later.
Tested in the PSG lab on 2017, 2019, 2022 and 2025.
OPTION (MAXDOP 1): the analysis should take as little CPU as possible
away from production.
Sorted by total effort (logical reads across all executions),
not by the slowest single execution.
============================================================================ */
DECLARE @Hours int = 24; -- time window, backwards from now
DECLARE @Top int = 20; -- number of rows
SELECT TOP (@Top)
q.query_id AS [Query ID],
ISNULL(OBJECT_NAME(q.object_id), N'(ad hoc)') AS [Object],
SUM(rs.count_executions) AS [Executions],
CAST(SUM(rs.avg_logical_io_reads * rs.count_executions) AS bigint)
AS [Total reads],
CAST(SUM(rs.avg_logical_io_reads * rs.count_executions)
/ NULLIF(SUM(rs.count_executions), 0) AS bigint) AS [Reads per execution],
CAST(SUM(rs.avg_cpu_time * rs.count_executions) / 1000.0 AS decimal(18,1))
AS [Total CPU (ms)],
CAST(SUM(rs.avg_duration * rs.count_executions) / 1000.0 AS decimal(18,1))
AS [Total duration (ms)],
COUNT(DISTINCT p.plan_id) AS [Plans],
LEFT(REPLACE(REPLACE(qt.query_sql_text, CHAR(13), N' '), CHAR(10), N' '), 120)
AS [Statement (start)]
FROM sys.query_store_query AS q
JOIN sys.query_store_query_text AS qt ON qt.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
JOIN sys.query_store_runtime_stats_interval AS i ON i.runtime_stats_interval_id = rs.runtime_stats_interval_id
WHERE i.end_time >= DATEADD(HOUR, -@Hours, SYSUTCDATETIME())
GROUP BY q.query_id, q.object_id, qt.query_sql_text
ORDER BY [Total reads] DESC
OPTION (MAXDOP 1);Sample output from our lab (SQL Server 2025, trimmed to the key columns and rows):
Query ID Object Executions Total reads Reads per execution Plans Statement (start)
60 OffeneVorgaenge 20 1506396 75319 3 (@MandantId int,@Ab datetime2(0))SELECT VorgangId, ...
51 (ad hoc) 2 406478 203239 1 SELECT TOP (100000) v.VorgangId, dbo.fnMandantName(...
65 (ad hoc) 2 97599 48799 1 CREATE INDEX IX_Vorgang_Mandant_Status_Angelegt ...
25 SucheVorgang 2 65040 32520 1 (@MandantId int,@Kennung varchar(20),@Status ...How to read the result:
- The example's procedure is at the top, with the most reads and three plans. Several plans for the same query suggest that its cost depends on the plan. The next steps follow exactly that lead.
- Maintenance shows up too, here an index build. That is not an error: maintenance costs as well. When tuning an application query, skip such rows.
- CPU and duration are included in the query. For comparing before and after a change, reads are usually more telling because they do not depend on what else is running on the server.
For many databases or longer periods, we analyze Query Store with our tool PSG QX.
Step 2: Measure the work
Measure the query you found on a test system with comparable data. Two settings in SQL Server Management Studio are enough:
SET STATISTICS IO, TIME ON; -- reads per table and CPU time on the "Messages" tab
-- Ctrl+M: "Include Actual Execution Plan"
EXEC dbo.OffeneVorgaenge @MandantId = 1, @Ab = '2025-11-28';Caution: this runs the query again, with all its work and, for modifying statements, with its changes. Test with real parameters and the same connection settings as the application; why SSMS can otherwise show a different plan is explained in the path Sometimes fast, sometimes slow.
From SQL Server 2019, the last actual plan can also be retrieved without running the query again: Last actual plan. Which switches do what, and at what cost, is covered in the profiling family.
Step 3: Read the plan with five questions
An execution plan shows how SQL Server processes the query. You do not need to understand all of it. Five questions usually lead to the cause:
- Where are most rows produced? Follow the thick arrows. That is where the work happens.
- Do estimate and actual differ a lot? If an operator says "estimated 4,655 rows" and "actual 200,016", the optimizer planned with wrong assumptions.
- Does it seek or read everything? An Index Seek reads a slice, a Scan reads everything. A scan is not always wrong, but it is suspicious when only a few rows are needed.
- How often does it look up? A Key Lookup fetches missing columns from the table, once per row. With many rows, that gets expensive.
- Are there warnings? A yellow triangle on an operator points to an implicit conversion, missing statistics or a spill to TempDB, for example (Spills and spools). Not every warning is the cause, but each is worth a question.
In the example, the plan for the large tenant answers questions 2 and 4 at once: the index seek was estimated at 4,655 rows and returned 200,016, each followed by a lookup in the table (SQL Server 2022, similar on the other versions). Pattern 4 shows why.
Step 4: Eight typical patterns
We see the following patterns again and again in investigations. Each one shows the query before and after, with the reads from the lab.
Pattern 1: A function on the column
If a column is wrapped in a function, SQL Server cannot use the index to seek for that condition. It has to compute and check every entry. A usable condition is called sargable.
All cases of the large tenant in November 2026
SELECT VorgangId, Angelegt
FROM dbo.Vorgang
WHERE MandantId = 1
AND YEAR(Angelegt) = 2026 AND MONTH(Angelegt) = 11; --! function on the column1,495 reads: all 600,000 entries of the tenant checked
SELECT VorgangId, Angelegt
FROM dbo.Vorgang
WHERE MandantId = 1
AND Angelegt >= '20261101' AND Angelegt < '20261201'; --! range on the column43 reads: November only
Code as in the lab. Index on (MandantId, Angelegt).
The same applies to LEFT(Kennung, 3) = 'V00' (better Kennung LIKE 'V00%') or calculations such as Betrag * 1.19 > 100 (better Betrag > 100 / 1.19).
Pattern 2: A parameter with the wrong data type
If the column is varchar but the parameter is nvarchar, SQL Server has to convert one of them. If the column has a SQL collation (its name starts with SQL_), the column gets converted: the seek turns into a scan. This often happens with database access generated by a tool that passes strings as nvarchar by default.
Find a case by its identifier
EXEC sys.sp_executesql
N'SELECT VorgangId, Betrag FROM dbo.Vorgang WHERE Kennung = @k',
N'@k nvarchar(4000)', --! data type does not match the column
@k = N'V0000500000';3,114 reads: Index Scan, plan warning about the conversion
EXEC sys.sp_executesql
N'SELECT VorgangId, Betrag FROM dbo.Vorgang WHERE Kennung = @k',
N'@k varchar(20)', --! same data type as the column
@k = 'V0000500000';6 reads: Index Seek
Code as in the lab; column Kennung varchar(20) with index, collation SQL_Latin1_General_CP1_CI_AS.
The plan then shows a warning on the first operator with CONVERT_IMPLICIT and the note that the conversion affects the seek. For a column with a Windows collation, the effect did not show in the lab: it stayed a seek with 6 reads. Whether you are affected therefore depends on the collation of the column in question.
Pattern 3: One search for every case
Search screens with optional fields often end up in a single query in which every condition can be switched off. There is only one plan for this "catch-all" query, and it has to work for every combination. Usually it becomes a scan.
Search by identifier through a search procedure
SELECT VorgangId, MandantId, Kennung, Betrag
FROM dbo.Vorgang
WHERE (@MandantId IS NULL OR MandantId = @MandantId) --! every condition can be switched off
AND (@Kennung IS NULL OR Kennung = @Kennung)
AND (@Status IS NULL OR Status = @Status);32,521 reads: scan of the whole table
DECLARE @sql nvarchar(max) = N'SELECT VorgangId, MandantId, Kennung, Betrag FROM dbo.Vorgang WHERE 1 = 1';
IF @MandantId IS NOT NULL SET @sql += N' AND MandantId = @MandantId';
IF @Kennung IS NOT NULL SET @sql += N' AND Kennung = @Kennung'; --! only what is searched for
IF @Status IS NOT NULL SET @sql += N' AND Status = @Status';
EXEC sys.sp_executesql @sql, N'@MandantId int, @Kennung varchar(20), @Status tinyint',
@MandantId, @Kennung, @Status;6 reads: Index Seek
Code as in the lab. First call with tenant, measured call with identifier.
The dynamic version stays parameterized and is therefore safe against SQL injection. One approach for searches with many optional conditions is T-Lift. SQL Server 2025 defuses the pattern by itself from compatibility level 170: in the lab the call dropped to 42 reads there. On all older versions and levels the scan remained.
Pattern 4: The large tenant gets the small tenant's plan
This is the example from the beginning. SQL Server compiles a procedure's plan on the first call and reuses it afterwards. If the first call came from a small tenant, the plan is built for few rows: seek, then look up every row. For the large tenant, the same plan means 200,016 lookups.
| Call | Reads |
|---|---|
| large tenant with its own plan | 32,547–32,565 |
| large tenant with the small tenant's plan | 638,083 |
| small tenant with its own plan | 8,738–8,750 |
| small tenant with the large tenant's plan | 32,521 |
Who shaped the plan depends on which call came first after a restart or a recompilation. That is why the query is "sometimes fast, sometimes slow". The background is explained in Understanding parameter sniffing.
Since SQL Server 2022 there is an optimization that can keep several plans ready for such parameters. In the lab it did not kick in for this example on any version or compatibility level. So do not rely on it. What helped here is shown in path B below.
Pattern 5: When looking up gets too expensive
If an index does not contain all the columns a query needs, SQL Server looks them up in the table row by row. With few rows that is cheap. Above a certain amount it prefers to read the whole table right away. The same query for the large tenant over periods of different length shows this tipping point:
| Period | Index without Betrag | with INCLUDE (Betrag) |
|---|---|---|
| 7 days | 12,268 (seek + lookups) | 20 |
| 30 days | 32,519 (scan) | 66 |
| 90 days | 32,519 (scan) | 184 |
| 365 days | 32,519 (scan) | 725 |
With the additional column in the index, the lookups disappear. Every index costs space and time with each change to the table, though, and it affects all queries on the table, not just this one. How to weigh that up is shown in Index tuning.
Pattern 6: A table variable with many rows
Up to compatibility level 140, SQL Server estimates a table variable at a single row, no matter how many it holds. With 50,000 rows, it chose 50,000 single seeks in the lab instead of a join over the table.
Store 50,000 open cases and join them
DECLARE @t TABLE (VorgangId int PRIMARY KEY); --! estimated at 1 row up to level 140
INSERT @t (VorgangId) SELECT VorgangId FROM dbo.Vorgang WHERE Status = 0;
SELECT SUM(v.Betrag)
FROM @t AS t JOIN dbo.Vorgang AS v ON v.VorgangId = t.VorgangId
WHERE v.Angelegt >= '20260101';Level 140: 150,091 reads (estimate 1 row) · from level 150: 32,430–32,717
CREATE TABLE #t (VorgangId int PRIMARY KEY); --! has statistics
INSERT #t (VorgangId) SELECT VorgangId FROM dbo.Vorgang WHERE Status = 0;
SELECT SUM(v.Betrag)
FROM #t AS t JOIN dbo.Vorgang AS v ON v.VorgangId = t.VorgangId
WHERE v.Angelegt >= '20260101';32,541–32,841 reads on all levels
Code as in the lab. Same query; only the kind of intermediate table differs.
From compatibility level 150 (SQL Server 2019), SQL Server waits with the plan until the table variable is filled and then estimates correctly. Important: it is the level that matters, not the version. A database that stays at level 140 after an upgrade keeps the problem.
Pattern 7: A scalar function in the select list
A scalar function that reads data itself runs once per row. In the lab, it was called 100,000 times for 100,000 rows.
Return the tenant name for 100,000 cases
CREATE OR ALTER FUNCTION dbo.fnMandantName (@MandantId int) RETURNS varchar(50)
AS
BEGIN
RETURN (SELECT Name FROM dbo.Mandant WHERE MandantId = @MandantId);
END
GO
SELECT TOP (100000) v.VorgangId, dbo.fnMandantName(v.MandantId) AS Mandant --! one call per row
FROM dbo.Vorgang AS v ORDER BY v.VorgangId;Level 140: 100,000 function calls · from level 150: 0 (inlined)
SELECT TOP (100000) v.VorgangId, m.Name AS Mandant
FROM dbo.Vorgang AS v
JOIN dbo.Mandant AS m ON m.MandantId = v.MandantId --! set instead of single calls
ORDER BY v.VorgangId;one query, no function call
Code as in the lab.
For this pattern, reads are not the right measure: the function reads the same row per call as the join. The cost lies in the single calls. From compatibility level 150, SQL Server inlines simple functions like this one into the query by itself. Whether that works for your function and where the limits are is shown in Functions and performance.
Pattern 8: Row by row instead of all at once
A loop that sends its own query for every record turns one task into thousands. In the lab we reproduced this inside the server: 2,000 cases queried one by one compared with one query for all 2,000.
| Approach | Queries | Reads |
|---|---|---|
| loop with single queries | 2,000 | 14,062–14,072 |
| one query for all | 1 | 6,452–7,105 |
If the loop comes from the application, for example because related data is loaded for every record, each query adds a network round trip. We did not measure those here; they often weigh more than the reads. What this looks like with Entity Framework is shown in our hub on Entity Framework and SQL Server.
Step 5: Fix it
Path A: You may change the code
Then the query itself is the best place to start:
- Write conditions sargably (pattern 1), align the data types of parameters and columns (pattern 2).
- Break catch-all searches into targeted queries (pattern 3).
- Sets instead of loops and single calls (patterns 7 and 8), a temporary table instead of a table variable for many rows (pattern 6).
- An index only after checking its effect on all queries on the table (pattern 5).
After every change, measure with the same data and parameters as before.
Path B: The application belongs to a vendor
Many slow queries come from software whose code you may not change. Even then, there are two things you can do:
An index, agreed with the vendor. In the example, one index solved the problem of pattern 4 completely without changing a single line of code:
CREATE INDEX IX_Vorgang_Mandant_Status_Angelegt
ON dbo.Vorgang (MandantId, Status, Angelegt)
INCLUDE (Kennung, Betrag);| Call | without index | with index |
|---|---|---|
| large tenant with the small tenant's plan | 638,083 | 63 |
| small tenant with the large tenant's plan | 32,521 | 6–7 |
With this index it no longer matters which tenant shaped the plan: both cases are fast, on all versions tested. Agree such indexes with the vendor. Many vendors define in their contracts what may be changed in the database, and an update can remove or overwrite indexes.
A finding the vendor can work with. If the cause lies in the query text, such as a function on the column or a wrong parameter type, only the vendor can fix it. What the vendor needs:
- the query and the plan in which the problem is visible;
- the conditions under which it occurs, for example the large tenant or a long period;
- the place in the query text and a sargable version;
- the reads before and after, measured on a replica with comparable data.
The actual fix then lies in the application code. A good finding makes sure it does not stall at the vendor over the question of whether the problem can be reproduced at all.
Step 6: Prove the effect
A change is only an improvement once it is proven:
- Measure before and after in the same way: the same data, the same parameters, the same connection settings. Compare reads and plan shape.
- Check in production: Query Store shows the same query before and after the change. You can run the query from step 1 for two time windows.
- Compare two systems: if the same query behaves differently on test and production, sp_BlitzPlanCompare helps.
- Define the fallback path before you change anything: how is a new index removed again, how is the old version restored?
Record the result in the findings sheet of the guide. That way it can be passed on to IT management or the vendor.
When we step in
You can take many of these steps yourself. It gets harder when the application belongs to a vendor and the finding has to convince, when many queries are affected at once, when there is no test system with comparable data, or when time is short. Then we investigate together with your team, prove the cause and measure the effect: SQL Server performance tuning.
Frequently asked questions
Isn't an index enough? Sometimes, as with patterns 4 and 5. With patterns 1 to 3, an index does not help as long as the query cannot use it for a seek. And every index costs on every change to the table.
Should I apply the missing index suggestions? As a hint, yes; unchecked, no. The suggestions only look at one query at a time, do not always order the columns well and in total often add up to near-duplicate indexes. Check each suggestion as described in Index tuning.
Does OPTION (RECOMPILE) help? With patterns 3 and 4, often: the query gets a matching plan on every call. In return it is compiled every time, which can become noticeable for very frequent queries. And it is a code change.
Is NOLOCK a solution? No. It avoids waiting for locks but does not reduce the work of the query. In return, it can read rows twice or not at all.
Why not simply raise the compatibility level? For patterns 6 and 7 and, with SQL Server 2025, for pattern 3, that helped in the lab. A higher level can change other plans too, for better or worse. Back up the change with Query Store and, for vendor software, agree on it beforehand.