Question

What is deadlock in sql server and when it arises? What are the issues with deadlock and how to resolve it?

Was it helpful?

Solution

In general, deadlock means that two or more entities are blocking some sources, and none of them is able to finish, because their are blocking sources in a cyclic way.

One example: Let's say I have table A and table B, I need to do some update in A and then B and I decide to lock both them at the moment of usage (this is really stupid behaviour, but it serves it's purpose now). At the same moment, someone else does the same thing in opposite order - locks B firstly, then locks A.

Chronologically, this happens:

proc1: Lock A

proc2: Lock B

proc1: Lock B - starts waiting until proc2 releases B

proc2: Lock A - starts waiting until proc1 releases A

Neither of them will ever finish. That's a deadlock. In practice this usually results in timeout errors since it is not desired to have any query hanging forever, and the underlying system (e.g. database) will kill queries that don't finish in time.

One real world example of a deadlock is when you lock your house keys in your car, and your car keys in your house.

OTHER TIPS

Deadlock is what happens when two people need multiple resources to execute, and where some of the resources are locked by each of the people. This leads to the fact that A can't execute without something B has and vice versa.

Lets say I have Person A and Person B. They both need to get two rows to run (Row1 and Row2).

  • Person A locks Row1 and tries to get Row2.
  • Person B locks Row2 and tries to get Row1.

Person A can't run because it needs Row2, Person B can't run because it needs Row1. Neither person will ever be able to execute because they're locking what the other needs and vice versa.


One reasonably simple way to reduce deadlock is in all your complex transactions, you should do operations in the same order. In other words, access Table1 then Table2 in the same order. This will help reduce the number of deadlocks that occur.

An impasse that may result when two (or more) transactions are each waiting for locks to be released that are held by the other.

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