Server load
~55 MBless data read on every run
Every run kept its caller waiting 1.9 seconds. Three small code changes cut that to 295 ms.
Data read per run
Source: 5 runs before and after.
SQL Server tuning reduces CPU time and disk reads, which speeds up operations.
The problem
The slow stored procedure significantly hampered SQL Server performance.
The fix
Here is what we've done to make this query run faster:
- Removed SQL function from
WHEREclause (subquery) - Removed unused columns from temporary tables
- Replaced two temporary tables with Common Table Expressions (CTE)
SQL Server functions in the WHERE clause
For better performance, avoid wrapping columns in functions in the WHERE clause. Here is why:
When a function wraps a column in the
WHEREclause, SQL Server usually cannot use an index seek on that column, so it scans the whole table or index.
Under the hood
Before and after, every measurement
The improvement was huge: the total number of disk reads was 3,157 instead of 9,849!
| Duration (ms) | CPU (ms) | Disk (8k page reads) | ||||
|---|---|---|---|---|---|---|
| Before | After | Before | After | Before | After | |
| Run 1 | 805 | 476 | 500 | 453 | 5,563 | 4,471 |
| Run 2 | 807 | 3 | 46 | - | 337 | 13 |
| Run 3 | 1,171 | 4 | 125 | - | 1,034 | 14 |
| Run 4 | 3,009 | 563 | 1,766 | 516 | 10,958 | 4,612 |
| Run 5 | 3,613 | 432 | 2,688 | 390 | 31,354 | 6,678 |
| AVG | 1,881 | 295 | 1,025 | 453 | 9,849 | 3,157 |
Below is the detailed breakdown by metric:
| Before | After | Improvement | |
|---|---|---|---|
| Duration (ms)* | 1,881 | 295 | ~6x |
| CPU (ms)* | 1,025 | 453 | ~2x |
| Disk (number of reads)* | 9,849 | 3,157 | ~3x |
After our tuning, the stored procedure became significantly faster, with average duration dropping from 1,881 ms (1.9 seconds) to 295 ms.
That’s over 6x faster.


