Optimistic Locking Version Column

Implement optimistic concurrency with a version column for conflict-free updates.

SqlData Integrity

Code

sqlsnippet
7 lines
-- Read current version
SELECT id, data, version FROM items WHERE id = 42;
-- Attempt update (fails if version changed)
UPDATE items
SET data = :new_data, version = version + 1, updated_at = NOW()
WHERE id = 42 AND version = :expected_version;
-- Check affected rows: 0 means conflict, retry

How it works

Several statements share this file — SELECT / UPDATE, with items among the objects involved.

Breaking the statements into their working parts: a WHERE clause limiting the rows one statement is allowed to reach.

Applying it

Run the statement against the items table.

Statements that matter

UPDATE items
SET data = :new_data, version = version + 1, updated_at = NOW()
WHERE id = 42 AND version = :expected_version;
SELECT id, data, version FROM items WHERE id = 42;

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
`items` — referenced directly, no join needed.