Blocking in SQL Server


Blocking in SQL Server occurs when one transaction holds a lock on a resource (such as a table or a row) and another transaction attempts to access the same resource. The second transaction is blocked until the first transaction releases the lock.

There are several methods to identify and resolve blocking in SQL Server:

  • Use SQL Server Management Studio (SSMS) Activity Monitor: Activity Monitor provides a graphical view of the current activity on the SQL Server instance, including blocking. To access Activity Monitor, right-click on the SQL Server instance in SSMS and select "Activity Monitor". The "Processes" tab shows the current running processes, and the "Resource Waits" tab shows the resources that are being waited on.

  • Use the system stored procedures: SQL Server provides several system stored procedures that can be used to identify blocking. For example, sp_who2 shows the current running processes and their status, including whether they are blocked by another process. sp_lock shows the current locks on resources, including the process that holds the lock and the process that is waiting for the lock.

  • Use dynamic management views (DMVs): DMVs provide a more detailed view of the current activity on the SQL Server instance. For example, sys.dm_exec_requests shows the current running requests, including the session ID and the status. sys.dm_tran_locks shows the current locks on resources, including the lock type and the process that holds the lock.

To resolve blocking in SQL Server, there are several methods:

  • Kill the blocking process: If the blocking process is not critical, it can be killed using the KILL command. This will release the locks and allow the blocked process to continue.

  • Optimize queries: Long-running queries can cause blocking. Optimizing queries by adding indexes or rewriting them can reduce the time they take to execute and reduce the likelihood of blocking.

  • Use snapshot isolation: Snapshot isolation allows transactions to read data without acquiring locks, reducing the likelihood of blocking. This can be enabled at the database level using the ALTER DATABASE command.

  • Increase lock timeout: If blocking is caused by long-running transactions, increasing the lock timeout can allow the transactions to complete without causing blocking. This can be done using the SET LOCK_TIMEOUT command.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.