SQL Server Performance Tuning

How Replacing NOT IN Made a 53-Minute Query 34,785x Faster

Updated November 18, 20262 min read

Server capacity

~7.7 TBless data read per run

This query ran for 53 minutes, made almost 1 billion disk reads and pushed CPU to 70% across 12 threads. Rewriting one NOT IN as NOT EXISTS brought it down to 92 ms.

Data read per run

Before7,719 GB (7.7 TB)
After0.25 GB (248 MB)

Source: the post’s before and after measurements. Data = 942,222,862 → 30,312 page reads × 8 KB.

Most SQL Servers bottleneck on Disk, which is number of disk operations required to pull all data necessary to process the query.

When tuning, the goal is often to get SQL Server to read less data from the disk.

The problem

We identified a long-running query that was pushing CPU usage to 70% and concurrently executing across 12 threads.

Here’s a glance at the pre-tuning metrics:

  • Duration (query duration in milliseconds): 3,200,290
  • Disk (number of read operations required to get all data needed): 942,222,862

The query execution time was 53 minutes (3,200,290 ms) while making almost 1 billion disk read operations.

The fix

  • After reviewing the query plan, we identified the culprit: a NOT IN operation invoking a VIEW.
  • The fix was straightforward: switching the NOT IN operation to a NOT EXISTS operation. See below.

Here is how we modified the original query to fix the problem:

Note: The performance difference between NOT IN and NOT EXISTS is often massive. This is one of those examples.

Final thoughts

Swapping the NOT IN operation for a NOT EXISTS operation resulted in a 34,785x improvement.

In SQL performance tuning, it helps to understand how the SQL engine retrieves data.

Under the hood

Before and after, every measurement

Small changes, huge difference? Totally!

We slashed a query's run time from 3,200,290 ms (53 minutes) down to 92 ms. No joke!

Below is a comparison of the number of disk reads before vs after tuning:

Reads per table before and after tuning

Before and after the NOT EXISTS rewrite

BeforeAfter

Duration34,785x faster

Before: 3,200,290 ms (53 min)After: 92 ms

Disk reads31,084x less

Before: 942,222,862 readsAfter: 30,312 reads

Values from the measurement table below. Each pair of bars is on its own scale.

BeforeAfterImprovement
Duration (ms) 3,200,2909234,785x
Disk (number of reads)942,222,86230,31231,084x

A query rewrite reduced the duration of the query by 34,785 times.

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 ➜