Documentation says, serializable
transactions execute one after one.
But in practic it seems not to be truth. Here's two almost equal transactions, the difference is delay for 15 seconds only.
#1:
set transaction isolation level serializable
go
begin transaction
if not exists (select * from articles where title like 'qwe')
begin
waitfor delay '00:00:15'
insert into articles (title) values ('qwe')
end
commit transaction go
#2:
set transaction isolation level serializable
go
begin transaction
if not exists (select * from articles where title like 'qwe')
begin
insert into articles (title) values ('asd')
end
commit transaction go
The second transaction has been run after couple of seconds since the start of first one.
The result is deadlock. The first transaction dies with
Transaction (Process ID 58) was deadlocked on
lock resources with another process and has been chosen as the deadlock victim.
Rerun the transaction.
reason.
The conclusion, serializable transactions are not serial?
serializable
means one transaction at a time? As far as I am aware serializable transaction isolation level will obtain exclusive/Range locks on the resources even if it is only reading data (in less strict isolation levels it obtains a shared lock when only reading data), and prevent other users to even read data.serializable
transactions is to run them in parallel if at all possible. The end result of the transactions will be identical to running them one after the another so the promise you get is that there cannot be any effects caused by parallel execution. If you want to run stuff one after another even when both could run at the same time without collision, use explicit locking instead. Theserializable
isolation level you take the risk of wasting CPU and RAM for trying to execute queries in parallel to reduce typical latency.