Optimistic locking with a version column

Two people edit the same row. The second save fails instead of overwriting the first.

SQL · Optimistic locking with a version columnAdvanced
ALTER TABLE articles ADD COLUMN version INT NOT NULL DEFAULT 1;

-- the form loaded version = 1; saving only works if nobody changed it meanwhile
UPDATE articles
SET title = 'New title', version = version + 1
WHERE id = 1 AND version = 1;

SELECT ROW_COUNT() AS saved;      -- 1 = saved, 0 = somebody else saved first: ask the user to reload
versionconcurrencyupdatelost update