Blocking and maintenance
~6.8 hless CPU time per run
Before the fix, this query caused a blocking chain and high CPU, and kept other sessions and the index maintenance job from completing. After the rewrite it averaged 5.8 seconds of CPU per run instead of about 24,663 seconds (6.85 hours).
CPU time per run
Source: averages of multiple runs on a DEV server with a database restored from PROD. 24,662,578 − 5,781 ms of CPU = 6.8 h.
Most SQL Servers bottleneck on Disk.
So, the goal is usually to get SQL Server to read less from the disk.
The problem
This query ran for a long time, causing a blocking chain and high CPU usage.
It was also preventing other sessions and the index maintenance job from completing.
Here's a glance at the pre-tuning metrics:
- Duration (ms): 24,735,261
- CPU (ms): 24,662,578
- Disk (number of read operations): 1,001,538,390
The fix
- Finding: The problem was a
NOT INoperation calling aVIEWwithout aWHEREclause, which caused a massive number of reads. - Action Taken: Replaced
NOT INwithNOT EXISTS, optimizing the query for performance.
Here is how we modified the original query to fix the problem:

Final thoughts
Such dramatic enhancements serve as a potent reminder of the power of SQL tuning. Even minor adjustments can unleash significant performance gains, ensuring our systems run smoother, faster, and more efficiently.
By replacing the
NOT INoperation withNOT EXISTS, we can significantly cut down on disk reads and enhance the query performance.
Remember, in the realm of SQL performance tuning, the devil often lies in the details.
Under the hood
Before and after, every measurement
The transformation was nothing short of miraculous: the execution time plummeted from about 24,735 seconds (6.9 hours) to just 1.4 seconds (1,402 ms)!
Below is a comparison of the number of table reads before and after tuning:

The optimized query returned the same result set and ran much faster:
| Before | After | Improvement | |
|---|---|---|---|
| Duration (ms)* | 24,735,261 | 1,402 | ~17,643x |
| CPU (ms)* | 24,662,578 | 5,781 | ~4,266x |
| Disk (number of reads)* | 1,001,538,390 | 478,903 | ~2,091x |
Overall, we observed a staggering improvement, making the query execution over 17,000 times faster.
Note: The performance difference between NOT IN and NOT EXISTS could be massive. This is one of those examples.
Test environment
- All the tests were executed on the DEV server against a database restored from the PROD server.
- The query was executed a few times, and possible solutions were tested to improve performance and fix the query issue.


