Avoid deadlocks: lock rows in the same order

Two transactions that lock the same rows in opposite order wait for each other forever. Sort the ids first.

SQL · Avoid deadlocks: lock rows in the same orderAdvanced
START TRANSACTION;

-- always lock in ascending id order, whatever the caller sent
SELECT id FROM products WHERE id IN (4, 2) ORDER BY id FOR UPDATE;

UPDATE products SET stock = stock - 1 WHERE id = 2;
UPDATE products SET stock = stock - 1 WHERE id = 4 AND stock > 0;

COMMIT;
-- if you get ERROR 1213 (deadlock), simply retry the whole transaction
deadlocktransactionlockinginnodb