In this video we will discuss a scenario when a deadlock can occur in SQL Server.

When can a deadlock occurIn a database, a deadlock occurs when two or more processes have a resource locked, and each process requests a lock on the resource that another process has already locked. Neither of the transactions here can move forward, as each one is waiting for the other to release the lock. The following diagram explains this.

When deadlocks occur, SQL Server will choose one of processes as the deadlock victim and rollback that process, so the other process can move forward. The transaction that is chosen as the deadlock victim will produce the following error.Msg 1205, Level 13, State 51, Line 1Transaction (Process ID 57) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

Let us look at this in action. We will use the following 2 tables for this example.

SQL script to create the tables and populate them with test data

Createtable TableA

(

Id intidentityprimarykey,

Name nvarchar(50)

)

Go

Insertinto TableA values ('Mark')

Go

Createtable TableB

(

Id intidentityprimarykey,

Name nvarchar(50)

)

Go

Insertinto TableB values ('Mary')

Go

The following 2 transactions will result in a dead lock. Open 2 instances of SQL Server Management studio. From the first window execute Transaction 1 code and from the second window execute Transaction 2 code.

-- Transaction 1

BeginTran

Update TableA Set Name ='Mark Transaction 1'where
Id = 1

-- From
Transaction 2 window execute the first update statement

Update TableB Set Name ='Mary Transaction 1'where
Id = 1

-- From
Transaction 2 window execute the second update statement

CommitTransaction

-- Transaction 2

BeginTran

Update TableB Set Name ='Mark Transaction 2'where
Id = 1

-- From
Transaction 1 window execute the second update statement

Update TableA Set Name ='Mary Transaction 2'where
Id = 1

-- After a few
seconds notice that one of the transactions complete

-- successfully
while the other transaction is made the deadlock victim

CommitTransaction

Next Video : We will discuss the criteria SQL Server uses to choose a deadlock victim