Optimistic Locking Update
Update a row only when its version still matches, detecting concurrent modification through the affected row count.
Code
-- 乐观锁更新:版本匹配才写入,且不允许透支。
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;What the code does
Several statements share this file — SELECT / UPDATE, with accounts among the objects involved.
Clause by clause, expect: a WHERE clause that narrows down the rows one statement touches.
Applying it
Run it in the accounts database context.
Statements that matter
UPDATE accounts
SET balance = balance - :amount,
version = version + 1
WHERE id = :account_id
AND version = :expected_version
AND balance >= :amount;
SELECT id, balance, version FROM accounts WHERE id = :account_id;
Interactive Tools for This Topic
SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.
FAQ
- What objects does the SQL involve?
- `accounts` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.