SQL Server Performance Tuning

How a Cursor Change and One Index Made a Query 8x Faster

Updated October 29, 20252 min read

Server load

~168 MBless data read on every run

Loading a team’s shade masks took 180 ms per call. A cursor option, a table variable and one index cut that to 23 ms.

Data read per run

Before178 MB
After10.4 MB

Source: 5 runs before and after.

Reading from disk is the slowest operation SQL Server does.

Therefore, tuning for less disk “reads” is often the primary goal.

The problem

The slow stored procedure significantly hampered SQL Server performance.

The fix

So here's what we did to improve the query performance:

  • Changed cursor type to FAST_FORWARD
  • Replaced temporary #table with variable @table
  • Added index IX_groupID_IsDeleted on dbo.Infractions

Final thoughts

If possible, avoid cursors!

Under the hood

Before and after, every measurement

The most interesting part…

The improvement was significant: the total number of disk reads decreased to just 1,271 from 21,737, resulting in a 5x reduction in CPU time!

The green block below shows SQL performance numbers after we made some changes in the database to improve slow SQL calls.

SQL Profiler trace comparing stored-procedure execution metrics before and after tuning.

We took 5 separate runs to analyze query performance before and after the fix:

Duration (ms)CPU (ms)Disk
(8k page reads)
BeforeAfterBeforeAfterBeforeAfter
Run 1218111711623,26534
Run 27118791517,6081,073
Run 330141101623,040100
Run 420819156-23,841773
Run 5106671094720,9354,376
AVG180231252421,7371,271
BeforeAfterImprovement
Duration (ms)*18023~8x
CPU (ms)*12524~5x
Disk (number of reads)*21,7371,271~17x
*The numbers are an avg of multiple T-SQL [LoadShadeMasksForTeam] runs.

After our tuning, the stored procedure became significantly faster, with average duration dropping from 180 ms to 23 ms.

That’s about 8x faster.

I still see a lot of people using cursors when they shouldn’t.

There are very few situations where a set-based query cannot replace cursor logic.

For these, a FAST_FORWARD cursor is an excellent place to start.

Cursor options like FORWARD_ONLY, STATIC, and KEYSET can all produce parallel plans and reduce performance impacts too.

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 ➜