Example Deadlock Code
Deadlocks happen. As you’re about to see in this post, deadlocks are actually quite easy to create. In my previous post I showed how to monitor and analyze deadlock events using Extended Events. In this post I present an easy way to trigger a an example deadlock that can be used to test that monitor and analysis code.
Deadlocks occur when two or more processes are attempting to lock the same resources in an incompatible manner. With that in mind, we’ll need two query windows open in SQL Server Management Studio (SSMS). We’ll need to execute commands in one window, then switch to the other window, in order to trigger the deadlock. First, we need to create a resource to lock, so execute this code in the first SSMS window:
1 2 3 4 5 6 7 8 |
USE tempdb; IF OBJECT_ID(N'tempdb..##DeadlockTest', N'U') IS NOT NULL DROP TABLE ##DeadlockTest; CREATE TABLE ##DeadlockTest ( id int NOT NULL PRIMARY KEY CLUSTERED ) ON [PRIMARY]; |
This table needs to be a global temporary table, as opposed to a session-local temporary table. This allows both SSMS windows to affect the same table. We could build a permanent table instead, but this way requires no cleanup. Which is win/win.
Now in the first SSMS window, run this code:
1 2 3 4 |
BEGIN TRANSACTION; INSERT INTO ##DeadlockTest (id) VALUES (1); |
Now, switch to the second SSMS window, and run this:
1 2 3 4 |
BEGIN TRANSACTION INSERT INTO ##Deadlocktest (id) VALUES (2); |
Switch back to the first SSMS window and run this:
1 2 |
SELECT COUNT(1) FROM ##DeadlockTest; |
Again, switch to the second SSMS window:
1 2 |
SELECT COUNT(1) FROM ##DeadlockTest; |
SQL Server should report a deadlock within a few seconds:
Msg 1205, Level 13, State 51, Line 9 Transaction (Process ID 63) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.
That’s as simple as it gets.
See our post on deadlock detection and analysis for code that shows exactly what statements caused the deadlock. The example deadlock code above shows this output from our analysis code:
Microsoft has another example of how to create a simple deadlock here.