SQL Server Performance Tuning Dos and Don’ts
SQL Server performance tuning identifies what slows a database down and fixes it, so queries return results faster and use less CPU, memory, and storage. The cause is usually a query that reads more rows than it needs, a missing or disorganized index, sessions that block each other, or a server that has run short on resources. DBAs fix the problem by rewriting the query, adjusting indexes, or changing the database design. Then they run the query again to confirm the change helped.
Summary
- SQL Server performance tuning follows one repeatable cycle. A DBA records how a slow query performs today, finds the cause in its execution plan and wait statistics, applies a fix, and runs the query again to confirm it improved.
- Start tuning with query design and indexing. Pulling only the columns a query needs, processing rows in sets instead of one at a time, and keeping indexes lean and current address common causes of slow queries.
- Checking SQL Server instances one at a time leaves problems running. A blocking chain on a server nobody has checked yet can stall applications until users start complaining. Monitoring that gathers wait statistics and blocking data from every instance in one place lets a DBA see which server to open first.
- SQL Diagnostic Manager 14.3 will report on whole groups of servers at once. The upcoming SQL Diagnostic Manager 14.3 release adds enterprise reports for Top Queries, Query Wait Statistics, Blocking, and Server Resources, plus real-time instance monitoring in the Web Console.
Why Is SQL Server Performance Tuning Important?
SQL Server performance tuning matters because every application, report, and dashboard built on a database waits on its queries. When one query reads more data than it needs, or waits for a lock (SQL Server’s way of stopping two sessions from changing the same data at once), everything that depends on it waits too. The delay gets worse as more people use the system at the same time.
Tuning reduces the CPU, memory, and disk work each query demands, so the same server can handle more requests at once. Faster queries also release locks sooner, so they hold up other sessions less often. For DBAs new to tuning, we walk through the process and six SQL Server tools that support it in our Beginning Performance Tuning whitepaper.
What Slows Down SQL Server Queries?
Slow SQL Server queries usually trace back to five factors, which are table size, joins, aggregations, concurrency, and indexes. The table below shows what each one does to a query and where to look for it.
| Factor |
Effect on the query |
Where to look |
| Table size |
Without a useful index, queries on large tables read every row |
Scan operators in the execution plan |
| Joins |
Extra or poorly written joins increase the rows SQL Server has to match |
Join operators and row estimates in the execution plan |
| Aggregations |
SUM, AVG, and COUNT over many rows use CPU and memory |
CPU and memory use during execution |
| Concurrency |
More simultaneous requests compete for locks, CPU, and memory |
Wait statistics and blocking sessions |
| Indexes |
Missing or fragmented indexes force SQL Server to read more data pages than the query needs |
Index recommendations and fragmentation levels |
Wait statistics show which factor to chase first. Every time a request waits, SQL Server records what it waited for, whether that is a lock, a disk read, or CPU time. If most of the waiting comes from locks, look at concurrency. If it comes from disk reads, start with table size and indexes.
5 Ways to Find Slow SQL Queries in SQL Server
Before tuning anything, find the queries that take the longest or consume the most resources. SQL Server includes five built-in ways to find them.
- Review the execution plan. An execution plan lays out the steps SQL Server takes to run a query, such as which tables it reads and how it joins them, and shows which steps cost the most.
- Monitor resource usage. Watch how much CPU, memory, and disk activity a query uses while it runs.
- Run the Database Engine Tuning Advisor. This tool studies a sample of real queries and recommends new indexes or ways to split large tables into smaller sections, a technique called partitioning.
- Set up Extended Events. This built-in tracing feature logs events as they happen, such as each query that finishes and how long it took.
- Use Query Store. Query Store keeps a history of each query’s execution plans and runtime statistics inside the database, so a DBA can see when a plan changed and how performance moved with it. Its Regressed Queries report lists the queries that got slower, and a DBA can force an earlier, faster plan without changing application code. Query Store is on by default for new databases starting with SQL Server 2022, and DBAs on SQL Server 2016 through 2019 turn it on per database with ALTER DATABASE.
From Single-Instance Checks to Environment-Wide Monitoring
A DBA uses each method on one instance at a time. An instance is a single running copy of SQL Server. The methods work well once the DBA knows which server and which query need attention.
But a DBA responsible for dozens of instances rarely knows that up front. Checking each server in turn takes time, and a problem on the last server in the rotation keeps running while the DBA works through the others. A monitoring tool that covers every instance gathers wait statistics, blocking, and resource data in one place, so the DBA can spot the worst problem across all servers and open that one first.
That delay hurts most when blocking is the problem. Blocking happens when one session holds a lock that other sessions need. Those sessions queue up behind it in what DBAs call a blocking chain, and every application that relies on the server stalls until someone finds the session at the front. In our guide to analyzing SQL Server blocking, we show how to find that session and clear it.
Deadlocks cause a quieter problem. A deadlock happens when two sessions each hold a lock the other needs, so neither can finish. SQL Server breaks the standoff by ending one of them, so deadlocks often clear before anyone notices. The application gets an error, and the DBA only finds out if a monitoring tool caught the deadlock and sent an alert.
How to Optimize SQL Queries in SQL Server
Optimizing a SQL query follows a four-step cycle, and the dos and don’ts below belong in the fix step. Working in the cycle means the DBA tests every change against the query’s starting numbers.
- Measure. Record how the query performs now, including how long it takes, how much CPU it uses, how many data pages it reads (known as logical reads), and what it waits on.
- Diagnose. Read the execution plan and wait statistics to find the cause.
- Fix. Apply the relevant do or don’t, or adjust an index.
- Verify. Run the query again and compare the results with the first measurement. Keep the change only if the numbers improve.
In our Making SQL Server Queries Run Faster webcast, we walk through the same cycle of measuring, reviewing the plan, fixing, and running the query again. For more advanced techniques, including query hints (instructions that override SQL Server’s own choices), partitioning, and deeper wait analysis, read Query Tuning Secrets for 2025.
T-SQL for the Measure and Diagnose Steps
Two dynamic management views cover most of the measure and diagnose work. The first query reads sys.dm_exec_query_stats and lists the 10 cached statements that have used the most CPU, with the average CPU time, duration, and logical reads for each run.
SELECT TOP (10)
qs.execution_count,
qs.total_worker_time / qs.execution_count / 1000 AS avg_cpu_ms,
qs.total_elapsed_time / qs.execution_count / 1000 AS avg_duration_ms,
qs.total_logical_reads / qs.execution_count AS avg_logical_reads,
SUBSTRING(st.text, (qs.statement_start_offset / 2) + 1,
((CASE qs.statement_end_offset
WHEN -1 THEN DATALENGTH(st.text)
ELSE qs.statement_end_offset
END - qs.statement_start_offset) / 2) + 1) AS statement_text
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
ORDER BY qs.total_worker_time DESC;
The view reports times in microseconds, so the query divides by 1,000 to show milliseconds. It covers only plans still in the plan cache, and a statement’s row disappears when its plan leaves the cache. Record the target query’s numbers before changing anything, then run the same query again in the verify step.
The second query reads sys.dm_os_wait_stats and ranks the instance’s wait types by total wait time. The NOT IN list leaves out background waits that accumulate even on an idle server.
SELECT TOP (10)
wait_type,
wait_time_ms / 1000.0 AS wait_time_s,
signal_wait_time_ms / 1000.0 AS signal_wait_s,
waiting_tasks_count,
100.0 * wait_time_ms / SUM(wait_time_ms) OVER () AS pct_of_total
FROM sys.dm_os_wait_stats
WHERE waiting_tasks_count > 0
AND wait_type NOT IN (
N'SLEEP_TASK', N'LAZYWRITER_SLEEP', N'BROKER_TO_FLUSH', N'BROKER_TASK_STOP',
N'CHECKPOINT_QUEUE', N'REQUEST_FOR_DEADLOCK_SEARCH', N'XE_TIMER_EVENT',
N'XE_DISPATCHER_WAIT', N'LOGMGR_QUEUE', N'SQLTRACE_INCREMENTAL_FLUSH_SLEEP',
N'DIRTY_PAGE_POLL', N'HADR_FILESTREAM_IOMGR_IOCOMPLETION',
N'SP_SERVER_DIAGNOSTICS_SLEEP', N'WAITFOR',
N'QDS_PERSIST_TASK_MAIN_LOOP_SLEEP',
N'QDS_CLEANUP_STALE_QUERIES_TASK_MAIN_LOOP_SLEEP')
ORDER BY wait_time_ms DESC;
The counts are cumulative since the database engine last started or since someone reset them with DBCC SQLPERF, so take two snapshots a few minutes apart and compare them to see what the server waits on now. Lock waits (LCK_M_ types) point to blocking, and PAGEIOLATCH_ waits point to slow reads from disk. Both views require VIEW SERVER STATE permission, or VIEW SERVER PERFORMANCE STATE on SQL Server 2022 and later.
Query Tuning Dos
- Do join only the tables the result needs.
- Do filter rows with WHERE and save HAVING for conditions on totals and other aggregates. Filtering early leaves fewer rows to group.
- Do use NOT EXISTS instead of NOT IN when the subquery can return NULL. If any value the subquery returns is NULL, NOT IN evaluates to UNKNOWN instead of TRUE, so the query returns no rows, while NOT EXISTS returns the rows that have no match. For positive checks, EXISTS and IN usually produce the same plan in current versions of SQL Server.
- Do pick data types that fit the data. A column sized far larger than its values wastes storage and memory.
- Do use wildcards carefully. A search that starts with a wildcard, such as ‘%term’, forces SQL Server to check every row instead of using an index.
- Do use TOP, or OFFSET and FETCH, to return only the rows a sample or a page of results needs.
- Do prefer UNION ALL over UNION when duplicates don’t matter. UNION adds a step to remove duplicates, and UNION ALL skips it.
- Do use stored procedures. SQL Server saves their execution plans and reuses them on later runs.
- Do watch for parameter sniffing in those procedures. When SQL Server compiles a stored procedure, it builds the plan around the parameter values passed on that call and reuses the plan for later calls, a behavior Microsoft calls parameter sensitivity. A plan that suits a value matching a few rows can run badly for a value matching millions, which is a common reason a procedure that was fast yesterday is slow today. Fixes include OPTION (RECOMPILE) on the affected statement, the OPTIMIZE FOR query hint, and, on SQL Server 2022 at database compatibility level 160, Parameter Sensitive Plan optimization, which caches more than one plan for the same statement.
- Do agree on requirements before writing the query. Knowing exactly which columns and rows a report needs keeps the query from pulling data nobody uses.
- Do monitor query performance continuously. A query that runs well today can slow down as its tables grow.
Query Tuning Don’ts
- Don’t use SELECT *, which returns every column in the table. Ask only for the columns the query needs.
- Don’t use SELECT DISTINCT to hide duplicates. Fix the join or filter that creates them.
- Don’t join tables in the WHERE clause. Explicit JOIN clauses are easier to read and make it harder to drop a join condition by accident.
- Don’t process rows one at a time with cursors or loops. Set-based statements handle all the rows at once and let SQL Server plan the work as a whole.
- Don’t run heavy queries during peak hours. Schedule them for quieter times.
Each of these patterns has a few legitimate uses, but treat them as exceptions.
How to Tune Indexes in SQL Server
Indexes affect almost every query a DBA tunes, so they deserve their own pass. A database index works like the index at the back of a book. It keeps a sorted copy of one or more columns with a pointer to each row, so SQL Server can jump straight to the rows it needs instead of reading the whole table.
Why Index Tuning Matters
Index tuning matters because a missing index forces SQL Server to scan the entire table, while too many indexes slow down every insert, update, and delete. In index tuning, DBAs decide which indexes to add, keep, or drop, and how to build each one.
Index Tuning Tools
Index tuning tools analyze workloads, recommend new indexes, flag unused ones, and suggest changes to existing ones, so DBAs don’t have to check each index manually. SQL Server includes one such tool, the Database Engine Tuning Advisor mentioned earlier. In SQL Diagnostic Manager, a DBA selects a slow query in Query Monitor and receives AI-generated index or query recommendations to review before applying any of them. For fragmented indexes, SQL Defrag Manager finds fragmentation based on policies the DBA sets and defragments indexes on demand or on a schedule.
SQL Server Index Best Practices
- Keep index keys narrow. Fewer, smaller key columns take less space and let SQL Server read fewer pages on each lookup.
- Avoid redundant indexes. Every extra index takes disk space, and SQL Server must update it whenever someone inserts, updates, or deletes a row.
- Check index usage regularly. Drop indexes that no query uses.
- Create covering indexes. A covering index includes every column a query needs, so SQL Server can answer the query from the index alone without going back to the table.
- Watch for missing indexes. Execution plans and tuning tools both suggest indexes that would help.
- Update statistics regularly. Statistics summarize how values are spread across a column. The query optimizer, the part of SQL Server that chooses an execution plan, relies on them to estimate how many rows each step will return, so outdated statistics lead to poor plans.
How to Tune SQL Server Configuration Settings
Some slow queries have nothing to do with how they’re written. Four instance-level settings control how SQL Server shares CPU, memory, and disk between queries, and a poor value in any of them can slow the whole workload. Change one setting at a time and run the measure, diagnose, fix, and verify cycle after each change.
- Max degree of parallelism (MAXDOP). This setting caps how many processors a single query can use when SQL Server splits it into parallel tasks. Microsoft’s MAXDOP guidance recommends a value of 8 on a server with one NUMA node (a group of processors that share local memory) and more than eight logical processors, and no more than the processor count on smaller servers. Servers with several NUMA nodes follow a separate rule based on processors per node.
- Cost threshold for parallelism. SQL Server considers a parallel plan only when a query’s estimated cost exceeds this value. Microsoft’s cost threshold guidance treats the default of 5 as a starting point, not a target, and suggests raising it in small steps so smaller transactional queries run on a single processor. Watch a full business cycle before changing it again.
- Max server memory. The default value is effectively unlimited, so SQL Server can keep claiming memory until the operating system and other applications run short. Microsoft’s memory guidance recommends capping it at 75% of the memory that other processes, including other SQL Server instances, don’t use.
- tempdb data files. tempdb is the system database that every session on the instance shares for temporary tables, sorts, and other intermediate work. Microsoft’s tempdb guidance recommends one data file per logical processor up to eight, all with the same size and growth settings. If sessions still compete to allocate space in tempdb, add files four at a time.
SQL Server 2019 and later versions suggest starting values for MAXDOP and max server memory during setup. On older or upgraded instances, check whether these settings still use their original defaults.
Monitor SQL Server Performance Across Every Instance With SQL Diagnostic Manager
SQL Diagnostic Manager monitors every SQL Server instance a team manages from a single console. It covers on-premises servers, VMware and Hyper-V virtual machines, Azure SQL Database, Azure SQL Managed Instance, Amazon RDS for SQL Server, and Google Cloud, so every instance reports to the same place. DBAs have used it for more than 20 years.
It continuously collects the wait statistics, blocking data, and resource usage that the measure and diagnose steps rely on. The table below matches each tuning task in this guide with the feature that supports it.
| Tuning task |
SQL Diagnostic Manager capability |
| Spot problems as they happen |
Real-time monitoring of all SQL Server instances from a centralized console |
| Find the cause of contention |
Performance analysis that identifies bottlenecks, blocking, deadlocks, and wait statistics |
| Find the queries worth tuning |
Query analysis to find and optimize problematic queries |
| Keep alerts relevant |
Alerting with customizable thresholds |
| Fix what the analysis finds |
Automated optimization recommendations |
| Report on trends |
Historical data for trend analysis and capacity planning |
When an alert fires, the DBA uses wait statistics and query analysis to trace it to the responsible query or session. Historical data then shows whether the problem is new or has happened before.
Start Every Tuning Cycle on the Right Server With SQL Diagnostic Manager 14.3
Every fix in this guide works, but only on the server a DBA is looking at. When servers are checked one at a time, a blocking chain on the last instance in the rotation keeps stalling applications while the DBA works through the others. A deadlock that cleared on its own leaves nothing behind but an error in someone’s application. By the time users complain, the DBA has to start from scratch with no record of what happened.
SQL Diagnostic Manager automatically captures deadlocks, along with the queries and resources on both sides, so the evidence is there when the DBA looks. The upcoming version 14.3 adds five enterprise reports that cover a whole group of servers at once, and four of them line up with the tuning work in this guide.
- Top Queries shows the highest-impact queries across the group, so the measure, diagnose, fix, and verify cycle starts with the query that matters most.
- Query Wait Statistics shows where queries spend their time waiting on every server.
- Blocking shows blocking duration, blocked sessions, and the top blocking queries across the group.
- Server Resources shows CPU, disk, and memory use, with peak-activity periods marked.
Once a report points to a server, the real-time view that 14.3 adds to the Web Console will show that server’s activity live from any browser. The DBA can then move from the group-wide view to the session causing the problem without opening each instance in turn. The full list of changes is on our SQL Diagnostic Manager 14.3 page.
The trial is free for 14 days, includes every feature, and needs no credit card. SQL Diagnostic Manager runs without agents, so most teams see live instances within about five minutes of installing.
Find out which server needs attention first.
Start a free trial of SQL Diagnostic Manager and connect it to the instances behind the slowest applications.
Frequently asked questions about SQL Server performance tuning
How do DBAs handle performance tuning in SQL Server?
Work in a cycle. Measure the slow query, then read its execution plan and wait statistics to find the cause. Apply a fix, such as rewriting the query or adjusting an index, and run it again to confirm it improved. Then move on to the next slow query.
What is the best way to improve SQL performance?
Start with how queries are written and indexed. Ask only for the columns a query needs, filter early with WHERE, and swap cursors and loops for set-based statements. Keep indexes lean, current, and duplicate-free, and update statistics regularly so SQL Server plans each query based on accurate information.
What is the purpose of performance tuning?
Performance tuning cuts the time and server resources each query uses. Users wait less for results, and the same server can handle more requests. That lets DBAs size hardware and cloud instances to fit the workload.
How can I monitor my SQL Server performance?
On a single instance, execution plans, Extended Events, and CPU, memory, and disk counters show what a given workload is doing. Across many instances, a monitoring tool such as SQL Diagnostic Manager gathers wait statistics, blocking, deadlocks, and resource usage from every server into one console. It sends an alert when a metric crosses a threshold the DBA has set.