Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server deadlock clarity?

After reading this interesting article I have some questions.

This table shows a deadlock situation :

enter image description here

T1 holds X lock on all rows with c1=5 on table t_lock1 while T2 holds X lock on all rows with C1=1 on table t_lock2.

Now each of these transactions wants to update the rows previously locked by the other. This results in a deadlock.

Question #1

  • Do transactions obtain locks? I know that reading from table is done by a shared lock, and write to a table is done using an exclusive lock (I'm talking about the default locking settings).

So it seems from this example that transaction also holds a lock ....is it correct?

Question #2

...T1 holds X lock on all rows with c1=5 on table t_lock1...

  • IMHO as I've said the locking is not per row (although it can be made, but the author didn't mentioned it) - so why does he say : on all rows with C1=5 ?
like image 584
Royi Namir Avatar asked Dec 29 '25 06:12

Royi Namir


1 Answers

Do transactions obtain locks?

No. The statement that you execute - a SELECT or an UPDATE will acquire the locks. Depending on your transaction isolation level setting, the duration of how long the (shared) locks (for a reading SELECT) will be held differs - that's all. Shared locks normally are held only very briefly, while update and exclusive locks are held until the transaction ends. The transaction might hold the locks - but it's not the transaction that acquires the locks...

*...T1 holds X lock on all rows with c1=5 on table t_lock1...*
IMHO as I've said the locking is not per row ( although it can be made , but the author didn't mentioned it) so why does he say : on all rows with C1=5 ?

The locking is per row - by default. But why do you think there's only a single row with C1=5? There could be multiple - possibly thousands - and the UPDATE statement will lock all those rows affected by the UPDATE statement.

like image 64
marc_s Avatar answered Jan 01 '26 23:01

marc_s



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!