Atomic Self Referencing UPDATE Increment
Increment counters inside a single self-referencing UPDATE so concurrent transactions serialize on the row lock; the read-then-write pattern loses increments.
Code
-- 先 SELECT 回内存再 UPDATE 会丢更新;把算术放进 UPDATE 本身,
-- 同一行的并发自增由行锁串行化,每个事务都基于最新值
CREATE TABLE counters (
name text PRIMARY KEY,
value integer NOT NULL DEFAULT 0
);
INSERT INTO counters (name, value) VALUES ('api_requests', 0)
ON CONFLICT (name) DO NOTHING;
UPDATE counters
SET value = value + 1
WHERE name = 'api_requests'
RETURNING value;
-- 上限保护也写进同一条语句:到顶后不再增加
UPDATE counters
SET value = LEAST(value + 1, 1000)
WHERE name = 'api_requests'
AND value < 1000
RETURNING value;Inside the snippet
Several statements share this file — INSERT / UPDATE / CREATE, with counters among the objects involved.
Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; an upsert guard (ON CONFLICT/MERGE) that turns insert-or-update into one atomic statement; a RETURNING clause that hands the affected rows back to the caller; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns.
Using it
Run the statement against the counters table.
Key statements
UPDATE counters
SET value = LEAST(value + 1, 1000)
WHERE name = 'api_requests'
AND value < 1000
RETURNING value;
UPDATE counters
SET value = value + 1
WHERE name = 'api_requests'
RETURNING value;
INSERT INTO counters (name, value) VALUES ('api_requests', 0)
ON CONFLICT (name) DO NOTHING;
Interactive Tools for This Topic
FAQ
- What objects does the SQL involve?
- `counters` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.