Consider the following schema in mysql:
create table foo(
id int not null primary key auto_increment,
name varchar(32) not null,
unique key(name)
);
And there is a record with name "abc" in the table.
I have a transaction (RC):
start transaction;
delete from foo where name = "abc";
insert into foo(name) values("abc");
commit;
If there are two concurrent transactions, the dead lock will happen.
| TX A | TX B
---------------------------------------------------------------------
Step 1 | start transaction; |
| delete name="abc"; |
---------------------------------------------------------------------
Step 2 | | start transaction;
| | delete name="abc";
| | <wait for lock>
---------------------------------------------------------------------
Step 3 | insert name="abc"; | <deadlock detected, exit>
---------------------------------------------------------------------
Step 4 | commit; |
---------------------------------------------------------------------
I'm wondering why this sequence causes the deadlock.
In the mysql doc says (https://dev.mysql.com/doc/refman/8.0/en/innodb-locks-set.html)
If a duplicate-key error occurs, a shared lock on the duplicate index record is set. This use of a shared lock can result in deadlock should there be multiple sessions trying to insert the same row if another session already has an exclusive lock. This can occur if another session deletes the row.
I suppose when transaction A runs the "delete" statement, it has acquired the X lock of the record "abc". When the "insert" statement executes, it tries to acquire the S lock due to the "duplicate key error". Shouldn't it get the S lock since it has got the X lock of the same record? Why deadlock happens here?
delete ....i assume you always meandelete from foo where name = "abc";and withinsert ...i assume you always meaninsert into foo(name) values("abc");- Raymond NijlandDELETE FROM ... WHERE ...sets an exclusive next-key lock on every record the search encounters. However, only an index record lock is required for statements that lock rows using a unique index to search for a unique row. - Raymond NijlandTX Aholds because ofDELETE FROM ... WHERE ...a unique index lock on the value"abc"..TX Balso tryes to delete with "abc" but transactionTX A"invalidates"TX Bdelete transaction state whenTX Adoes that insert with "abc" whats whyTX Bdeadlocks asTX Aholds the rights of "abc" (more or less as it is simplified a bit) - Raymond Nijland