Saturday, May 8, 2021

Get lock waits for the current database

Hey there, fellow database enthusiasts! Ever wondered about those pesky database locks that can slow things down? Today, we're sharing a super useful SQL query to help you identify and analyze lock waits in your SQL Server databases. This script is a fantastic tool for pinpointing tables and indexes experiencing contention, allowing you to optimize your database performance.

Here’s the SQL query:

SELECT o.name AS [table_name]
 ,i.name AS [index_name]
 ,ios.index_id
 ,ios.partition_number
 ,SUM(ios.row_lock_wait_count) AS [total_row_lock_waits]
 ,SUM(ios.row_lock_wait_in_ms) AS [total_row_lock_wait_in_ms]
 ,SUM(ios.page_lock_wait_count) AS [total_page_lock_waits]
 ,SUM(ios.page_lock_wait_in_ms) AS [total_page_lock_wait_in_ms]
 ,SUM(ios.page_lock_wait_in_ms) + SUM(row_lock_wait_in_ms) AS [total_lock_wait_in_ms]
FROM sys.dm_db_index_operational_stats(DB_ID(), NULL, NULL, NULL) AS ios
INNER JOIN sys.objects AS o WITH (NOLOCK) ON ios.[object_id] = o.[object_id]
INNER JOIN sys.indexes AS i WITH (NOLOCK) ON ios.[object_id] = i.[object_id]
 AND ios.index_id = i.index_id
WHERE o.[object_id] > 100
GROUP BY o.name
 ,i.name
 ,ios.index_id
 ,ios.partition_number
HAVING SUM(ios.page_lock_wait_in_ms) + SUM(row_lock_wait_in_ms) > 0
ORDER BY total_lock_wait_in_ms DESC
OPTION (RECOMPILE);

This query leverages sys.dm_db_index_operational_stats, a dynamic management function that provides detailed information about index activity, including lock waits. By joining it with sys.objects and sys.indexes, we can get a clear picture of which tables and their associated indexes are experiencing the most lock contention.

The results will show you the total wait counts and wait times for both row and page locks, helping you quickly identify bottlenecks. Remember, analyzing these lock waits is a crucial step in maintaining a healthy and performant SQL Server environment!

Popular Posts