Optimistic Locking Update

Update a row only when its version still matches, detecting concurrent modification through the affected row count.

SqlData Integrity

Code

snippet
-- 乐观锁更新:版本匹配才写入,且不允许透支。
UPDATE accounts
SET balance = balance - :amount,
    version = version + 1
WHERE id = :account_id
  AND version = :expected_version
  AND balance >= :amount;

-- 应用侧检查受影响行数:
--   1  -> 更新成功
--   0  -> 并发冲突,或余额不足(需再读一次以区分)

-- 取回最新版本用于重试:
SELECT id, balance, version FROM accounts WHERE id = :account_id;