Boost SQL Server Performance With Wait Statistics

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

SQLShack SQL Server training Español 

Newsletter
Boost SQL Server Performance with Wait Statistics
October 26, 2020 by Esat Erkec

Follow us!
  
In this article, we will explore, how we can increase SQL Server performance with the help of the wait statistics.
Wait statistics are one of the most important indicators to identify performance issues in SQL Server. When we
want to troubleshoot any performance issue, at first we need to diagnose the problem correctly because correctly
diagnosing problems help with half of the solution. Now, let’s learn wait statistics which helps to identify
performance issues properly.

What is the wait time in SQL Server?


SQL Server Operating System ﴾SQLOS﴿ is an application layer that provides communication between the
operating system and SQL Server. The main responsibility of the SQLOS is to perform memory, I/O, CPU
management. SQL Server uses worker threads to complete the submitted requests and are scheduled on CPU by
SQLOS and then carry out their tasks. These worker threads can exist in three different states when they are
fulfilling the assigned tasks according to resource availability. These are:

Popular
Running status indicates that the scheduled thread is currently being processed by the CPU
Different ways to SQL delete duplicate rows from a
Suspended status indicates that the assigned thread is waiting for a resource to be available. Such as, if any SQL Table
thread wants to access a data page that acquires an exclusive lock, it waits in the suspended status until the SQL Convert Date functions and formats
exclusive lock is removed and then it can access the page
SQL PARTITION BY Clause overview
Runnable status indicates that the thread is not waiting for any resources, but the CPU still unable to
How to UPDATE from a SELECT statement in SQL
process this task because it is dealing with another task Server

SQL WHILE loop with simple examples


In light of this information, wait time can be described as the elapsed time until the worker thread suspended
Learn SQL: Join multiple tables
status returns to the running status.
SQL Variables: Basics and usage

SQL Server table hints – WITH ﴾NOLOCK﴿ best


What is SQL Server wait statistics? practices

How to backup and restore MySQL databases using


the mysqldump command
The wait times are captured and recorded by the SQL Server and all this captured information called wait
CASE statement in SQL
statistics and it provides assistance to resolve problems that are related to the SQL Server performance.
SQL multiple joins for beginners with examples

The sys.dm_os_wait_stats dynamic management view can be used to obtain information about the wait type SQL Server functions for converting a String to a
Date
details. This view holds cumulative statistics about the wait types until the database engine restarted or the wait
What is the difference between Clustered and Non‐
statistics cleared. When we query the sys.dm_os_wait_stats, the following columns will return:
Clustered Indexes in SQL Server?

SQL Not Equal Operator introduction and examples


wait_type column represents the name of the wait type
The Table Variable in SQL Server
waiting_tasks_count column indicates how many times the wait type has occurred
wait_time_ms column indicates the total elapsed time the thread waited according to the wait type defined DELETE CASCADE and UPDATE CASCADE in SQL
Server foreign key
in the wait_type column
Multiple options to transposing rows into columns
max_wait_time_ms shows the maximum elapsed time the thread waited according to the wait type defined
SQL Server Transaction Log Backup, Truncate and
in the wait_type column
Shrink Operations
signal_wait_time_ms represents the total time that the thread waits on the runnable queue
How to implement error handling in SQL Server
wait_time_ms column indicates the sum of the time it spends in runnable and suspended queues. When
INSERT INTO SELECT statement overview and
we want to calculate only the resource wait time, the below formula will help us:
examples

Resource wait = (wait_time_ms) – (signal_wait_time_ms)

The following query will return the top 10 wait types and sorts them in ascending order by waiting time.

Tip: We can ignore some wait types because these wait types are related to the internal management of
SQL Server so we don’t need to consider these wait types

SELECT TOP 10 wait_type


AS [Wait Type],
wait_time_ms/1000.0
AS [Total Wait Time (second)],
(wait_time_ms-signal_wait_time_ms)/1000.0
AS [Resource Wait Time (second)],
signal_wait_time_ms/1000.0
AS [Signal Wait Time (second)],
waiting_tasks_count
AS [Wait Count]
FROM sys.dm_os_wait_stats
WHERE wait_type NOT IN
(N'CLR_SEMAPHORE',
N'LAZYWRITER_SLEEP',
N'RESOURCE_QUEUE',
N'SQLTRACE_BUFFER_FLUSH',
N'SLEEP_TASK',
N'SLEEP_SYSTEMTASK',
N'WAITFOR',
N'HADR_FILESTREAM_IOMGR_IOCOMPLETION',
N'CHECKPOINT_QUEUE',
N'REQUEST_FOR_DEADLOCK_SEARCH',
N'XE_TIMER_EVENT',
N'XE_DISPATCHER_JOIN',
N'LOGMGR_QUEUE',
N'FT_IFTS_SCHEDULER_IDLE_WAIT',
N'BROKER_TASK_STOP',
N'CLR_MANUAL_EVENT',
N'CLR_AUTO_EVENT',
N'DISPATCHER_QUEUE_SEMAPHORE',
N'TRACEWRITE',
N'XE_DISPATCHER_WAIT',
N'BROKER_TO_FLUSH',
N'BROKER_EVENTHANDLER',
N'FT_IFTSHC_MUTEX',
N'SQLTRACE_INCREMENTAL_FLUSH_SLEEP', Trending
N'DIRTY_PAGE_POLL',
N'SP_SERVER_DIAGNOSTICS_SLEEP') SQL Server Transaction Log Backup, Truncate and
ORDER BY wait_time_ms-signal_wait_time_ms DESC; Shrink Operations

Six different methods to copy tables between


databases in SQL Server

How to implement error handling in SQL Server

Working with the SQL Server command line


﴾sqlcmd﴿

Methods to avoid the SQL divide by zero error

Query optimization techniques in SQL Server: tips


and tricks

How to create and configure a linked server in SQL


Server Management Studio

SQL replace: How to replace ASCII special


characters in SQL Server

How to identify slow running queries in SQL Server


Interpreting the wait types SQL varchar data type deep dive

How to implement array‐like functionality in SQL


Unfortunately, we have no chance to know which wait type indicates which SQL Server performance issue because Server

they are so many. For this reason, we can search the particular wait types on the web or use the following wait All about locking in SQL Server
type’s dictionaries that give comprehensive information: SQL Server stored procedures for beginners

Database table partitioning in SQL Server


SQLShack wait types collection
How to drop temp tables in SQL Server
Waitopedia
How to determine free space and file size for SQL
Server databases

Using PowerShell to split a string into an array

KILL SPID command in SQL Server


How to install SQL Server Express edition

SQL Union overview, usage and examples

However, some wait types might occur very commonly in the SQL Server instances, therefore, it will be beneficial Solutions
to know the common wait types.
Read a SQL Server transaction log

SQL Server database auditing techniques


SOS_SCHEDULER_YIELD How to recover SQL Server data from accidental
UPDATE and DELETE operations

As we mentioned, SQLOS accomplishes the CPU management for SQL Server. SQLOS allows the thread to be How to quickly search for SQL database data and
objects
processed by the CPU at a quantum time. If the processing of the thread is not completed and all the resources
Synchronize SQL Server databases in different
are available state for this thread, SQLOS moves the thread to the runnable queue and it begins to wait for remote sources
reprocessing. SOS_SCHEDULER_YIELD wait type is captured and recorded when the thread is waiting in the
Recover SQL data from a dropped table without
runnable queue. This wait type shows a CPU pressure but it should be evaluated with two other indicators. The backups
first one is the sys.dm_os_tasks view, this dynamic management view gives compressive information about the How to restore specific table﴾s﴿ from a SQL Server
active tasks in the SQL Server. With the help of this view, we can monitor how many threads wait in the runnable database backup
status and if this value reaches the big numbers during the day, we have to suspect a CPU pressure. Recover deleted SQL data from transaction logs

How to recover SQL Server data from accidental


SELECT scheduler_id, session_id, task_state updates without backups
FROM sys.dm_os_tasks
WHERE task_state IN ('RUNNABLE') Automatically compare and synchronize SQL Server
and session_id > 50 data

Another indicator that we can use with SOS_SCHEDULER_YIELD is the signal_wait_time_ms column of the Open LDF file and view LDF file content

sys.dm_os_wait_stats view. As we stated, this value indicates the time which spends in the runnable queue for a Quickly convert SQL code to language‐specific client
code
thread. As a result, if we monitor the following metrics, we need to suspect about CPU pressure:
How to recover a single table from a SQL Server
database backup
If the SOS_SCHEDULER_YIELD wait type is listed in the top list of the resource wait statistics query
Recover data lost due to a TRUNCATE operation
If a lot of tasks are monitored in the runnable status without backups
If the signal wait time is higher than 35% of the total resource waits
How to recover SQL Server data from accidental
If the System\% Processor Queue Length counter of the Perfmon represents greater than 3 per CPU DELETE, TRUNCATE and DROP operations
If the Processor﴾_Total﴿\%Processor Time counter of the Perfmon indicates greater 80 percentage or Reverting your SQL Server database back to a
greater values specific point in time

How to create SSIS package documentation


To handle this wait the following recommendation can be potential solutions: Migrate a SQL Server database to a newer version
of SQL Server
Identify and optimize the queries which consume high CPU How to restore a SQL Server database backup to an
Adding more CPU older version of SQL Server

Schedule the index maintains plans on the non‐peak times


Ensure to have enough CPU resource when using the Page compression algorithms

ASYNC_NETWORK_IO
The ASYNC_NETWORK_IO indicates two main bottlenecks that are related to the network and the network
problems affect SQL Server performance negatively. The first one is that the application requests a huge result set
but the application cannot handle the result set as fast as SQL Server due to some reasons. The second one can
be related to network infrastructure. The following suggestions may be the solution to this issue:

Review the applications and try to reduce the requested amount of data
Check the network capacities that are between client machines and SQL Server ﴾Routers, switches, NIC,
cables, etc.﴿
Validate the server NIC configurations and ensure the last driver is installed
Consider increasing the packet size property in the connection string if you are planning to send or receive
a large amount of XML or blob data.

Categories and tips


► Auditing and compliance ﴾50﴿
Azure ﴾178﴿

Azure Data Studio ﴾37﴿

Backup and restore ﴾105﴿

► Business Intelligence ﴾444﴿

Data science ﴾21﴿

► Database design ﴾209﴿


► Database development ﴾372﴿

DBAtools ﴾30﴿

DevOps ﴾22﴿

DevSecOps ﴾2﴿

Documentation ﴾19﴿

ETL ﴾56﴿

► Features ﴾201﴿

Importing, exporting ﴾45﴿

Installation, setup and configuration ﴾103﴿


PAGEIOLATCH Jobs ﴾41﴿
► Languages and coding ﴾637﴿
SQL Server uses a reserved memory area that is called a buffer pool and it is used to cache data and index pages.
Lists ﴾12﴿
The main idea behind this working principle to as possible as to reduce the disk activity and improving the SQL
Server performance. SQL Server must read indexes and data pages from the disk before transferring to the buffer Machine learning ﴾32﴿

pool. PAGEIOLATCH wait type captures when the data pages fetch from the disk into the buffer pool. Most often Maintenance ﴾92﴿
time PAGEIOLATCH wait type indicates I/O problems related to the storage subsystems or memory pressure. Migration ﴾46﴿

Miscellaneous ﴾1﴿

▼ Performance tuning ﴾768﴿


Alerting ﴾8﴿

Always On Availability Groups ﴾81﴿

Buffer Pool Extension ﴾BPE﴿ ﴾8﴿

Columnstore index ﴾9﴿

Deadlocks ﴾15﴿

Execution plans ﴾106﴿

In‐Memory OLTP ﴾22﴿

Indexes ﴾76﴿

Latches ﴾5﴿

Locking ﴾9﴿

Monitoring ﴾84﴿

Performance ﴾161﴿

Performance counters ﴾26﴿

Performance Testing ﴾9﴿

CXPACKET Query analysis ﴾100﴿

Reports ﴾20﴿
When the SQL Server query optimizer decides to execute a query in parallel, it tries to divide the query operation SSAS monitoring ﴾3﴿
into equal‐sized threads as possible. CXPACKET wait type indicates the time that spends to execute a parallel SSIS monitoring ﴾10﴿
query. This wait type does not indicate any problem and can be ignored and it improves SQL Server performance.
SSRS monitoring ﴾4﴿
On the other hand, all threads cannot carry out their task exactly the same time, and the query execution time
Wait types ﴾11﴿
can be as fast as the slowest thread. When this thread’s synchronization problem reaches the unacceptable
► Professional development ﴾57﴿
amount ﴾greater than 50% of total waits﴿, we have to take into account this wait type as a problem. Possible
reasons may be as follows: Recovery ﴾32﴿

Security ﴾81﴿

Outdated statistics Server management ﴾13﴿


Missing or fragmented indexes SQL Azure ﴾219﴿
Insufficient memory SQL Server Management Studio ﴾SSMS﴿ ﴾85﴿
CPU pressure
SQL Server on Linux ﴾9﴿
Cardinality Estimator version
► SQL Server versions ﴾161﴿
Improper configured Maximum degree of parallelism ﴾MAXDOP﴿ option
► Technologies ﴾267﴿
Improper configured Cost threshold for parallelism option
Uncategorized ﴾3﴿

Utilities ﴾18﴿

 Helpers and best practices


BI performance counters

SQL code smells rules

SQL Server wait types

WRITELOG
SQL Server writes all modifications to the Log Buffer and its size is limited to 60KB. When Log Buffer fills up, the
log records are written into the disk and this mechanism is called Log Buffer Flush. WRITELOG wait type
indicates the elapsed time when the log records writing into the disk. The possible causes can be as below:

Locate the data files ﴾mdf,ndf﴿ and log files ﴾ldf﴿ into the separated disks
Increase the I/O capacity of the disk where the log file is placed
Consider using the Delayed Transaction Durability option of the SQL Server
Avoid the cursor which makes iterative modifications
Reducing the size of the log file

Conclusion
In this article, we learned how to boost SQL Server performance through the wait statistics. Wait statistics are the
main metrics that help to monitor and diagnose the performance problems of the SQL Server.

See more
Check out SpotLight, a free, cloud based SQL Server monitoring tool to easily detect, monitor, and solve SQL
Server performance problems on any device

Introducing Spotlight Cloud

Watch on

Esat Erkec
Esat Erkec is a SQL Server professional who began his career 8+ years ago as a Software
Developer. He is a SQL Server Microsoft Certified Solutions Expert.

Most of his career has been focused on SQL Server Database Administration and Development.
His current interests are in database administration and Business Intelligence. You can find him
on LinkedIn.

View all posts by Esat Erkec

Related Posts:
1. All about SQL Server spinlocks
2. How to handle excessive SOS_SCHEDULER_YIELD wait type values in SQL Server
3. SQL Server Statistics and how to perform Update Statistics in SQL
4. The SQL Server 2014 Resource Governor
5. Top SQL Server Books

Monitoring, Performance, Performance counters, Wait types

21,265 Views

© 2021 Quest Software Inc. ALL RIGHTS RESERVED. | GDPR | Terms of Use | Privacy

You might also like