Let’s say I have the following:
SELECT – Shared Lock — long running
UPDATE – Exclusive Lock
SELECT – Shared Lock — long running
These three statements come in order, the first select takes a long time to execute, in this time an update comes and has to wait (conflicting lock), followed by another select (compatible lock). Will the select be allowed to get the row? Or, does the update start a line. If the 2nd (or more) select is allowed to “cut in”, and is also long running, will the update end up deadlocked? Is there a way to prevent this, without having to upgrade the select lock to something more?
Assuming that each statement comes on its own transaction (ie. separate, conflicting lock namespaces):
No, the third SELECT would not ‘cut in’ in front of the UPDATE. A lock has to be compatible with all the locks in the wait list to be granted. Otherwise the X lock would ‘starve’.
There is some smallprint:
See also SQL Server, Lock Manager, and “relaxed” FIFO