I have two concurrent transactions inserting identical but differently ordered data into a table with unique keys, thus causing frequent deadlocks. How can I avoid these deadlocks in this setup? I'm using MySQL
Example:
CREATE TABLE cache (
id int auto_increment primary key,
k int unique not null,
v int not null
);
with the first transaction inserting entry 1 before 2
START TRANSACTION;
INSERT INTO cache (k, v) VALUES (1, 1);
INSERT INTO cache (k, v) VALUES (2, 2);
COMMIT;
and the second concurrent transaction inserting data the other way around
START TRANSACTION;
INSERT INTO cache (k, v) VALUES (2, 2);
INSERT INTO cache (k, v) VALUES (1, 1);
COMMIT;
Some more context: The table in question acts as a cache table. The values are computed in our application and will be used for subsequent sorting and filtering. The application knows which cache entries are relevant to its current task. In our current implementation, we first do a database query to check which of these cache entries are still missing, compute and insert them, and then do a query on the (now complete) cache table.
k
isUNIQUE
andNOT NULL
, removeID
and makek
thePRIMARY KEY
.INSERT
with both rows? Then, can you sort the data as you build that single statement?