Let’s presume that we have a t1 table where the integer weight column is marked as unique, item_id is the primary key. Can the following query fail?
UPDATE t1
SET weight = SELECT new_weight FROM (
SELECT MAX(weight) + 1 AS new_weight FROM t1
) qs
WHERE item_id = ?
where ? is an argument. Is it possible that due a race two items would attempt to set the same weight? Or is that database engine specific?
Yes you can get two identical weight values due to a race condition. Switch to
ISOLATION LEVEL SERIALIZABLEto avoid this (you will likely get a deadlock instead which you can retry. You avoid any data corruption though). Or employ proper pessimistic locking which is RDBMS specific.