Question

when deadlock occurs in sql server, which of transactions will be aborted. I mean what's the plan of sql server to decide which of transactions should be killed!

consider the two transaction below

Transaction A

begin transaction
    update Customers set LastName = 'Kharazmi'
    waitfor delay '00:00:5'; -- waits for 5 second
    update Orders set OrderId=13
commit transaction

Transaction B

begin transaction
    update Orders set OrderId=14
    waitfor delay '00:00:5'; -- waits for 5 second
    update Customers set LastName = 'EbneSina'
commit transaction

if both transaction are executed at the same time, transaction A locks and updates Customers table whereas transaction B locks and updates Orders table. After a delay of 5 second, transaction A looks for the lock on Orders table which is already held by transaction B and transaction B looks for the lock on Customers table which is already held by transaction A. So both the transactions can not proceed further, the deadlock occurs. my question is that, when deadlock occurs, which of the both transaction will be aborted. first, i executes transaction A then transaction B, sql server aborts transaction A and then first executes transaction B then A the result is the same and transaction A is alorted again. it confused me! thanks for any help.

Was it helpful?

Solution

You can learn the criteria in SET DEADLOCK_PRIORITY (Transact-SQL):

Which session is chosen as the deadlock victim depends on each session's deadlock priority:

  • If both sessions have the same deadlock priority, the instance of SQL Server chooses the session that is less expensive to roll back as the deadlock victim. For example, if both sessions have set their deadlock priority to HIGH, the instance will choose as a victim the session it estimates is less costly to roll back.

  • If the sessions have different deadlock priorities, the session with the lowest deadlock priority is chosen as the deadlock victim.

For your case, A should be considered by DBMS the less expensive transaction to roll back.

OTHER TIPS

There's no way to know just be looking at the queries. Basically, so far as I understand things, the engine considers all transactions involved in the deadlock and tries to work out which one will be the "cheepest" to roll back.

So, if, say, there are 2 rows in your Customers table, and 9000000 rows in your Orders table, it will be considerably cheeper to rollback the UPDATE applied to Customers than the one that was applied to Orders.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top