SQL Server Performance Tuning

How Three Small Changes Made a Slow Query 6x Faster

Updated October 29, 20252 min read

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

Before80.7 MB
After25.9 MB

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 WHERE clause (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 WHERE clause, 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)
BeforeAfterBeforeAfterBeforeAfter
Run 18054765004535,5634,471
Run 2807346-33713
Run 31,1714125-1,03414
Run 43,0095631,76651610,9584,612
Run 53,6134322,68839031,3546,678
AVG1,8812951,0254539,8493,157

Below is the detailed breakdown by metric:

Before After Improvement
Duration (ms)*1,881295~6x
CPU (ms)*1,025453~2x
Disk (number of reads)*9,8493,157~3x
*The numbers are an average of multiple T-SQL runs

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.

Check Red9's SQL Server Services

SQL Server Consulting

Perfect for one-time projects like SQL migrations or upgrades, and short-term fixes such as performance issues or SQL remediation.

Discover More ➜

SQL Server Managed Services

Continuous SQL support, proactive monitoring, and expert DBA help with one predictable monthly fee.

Discover More ➜

Emergency SQL Support

Take the stress out of emergencies with immediate access to a SQL Server Sr. DBA 24x7x365

Discover More ➜

Explore All Services ➜