Upsert Batch Order Avoids Deadlock
Sort batch upsert input by conflict key so concurrent transactions acquire row locks in the same order instead of failing with deadlock detected.
Code
-- 并发批量 upsert:两个事务各带一批键,触达顺序不同 → 行锁交叉等待
-- → 一方以 deadlock detected 中止。让所有批次先按冲突键排序,
-- 行锁按一致顺序获取,交叉等待消失。
CREATE TABLE daily_counters (
metric text PRIMARY KEY,
delta_sum bigint NOT NULL DEFAULT 0
);
INSERT INTO daily_counters (metric, delta_sum) VALUES
('requests', 0), ('api_latency', 0), ('api_errors', 0);
-- VALUES 批次按冲突键排序后再写入:api_errors → api_latency → requests
INSERT INTO daily_counters AS dc (metric, delta_sum)
SELECT metric, delta
FROM (
VALUES
('api_errors', 3),
('api_latency', -1),
('requests', 12)
) AS batch(metric, delta)
ORDER BY metric
ON CONFLICT (metric) DO UPDATE
SET delta_sum = dc.delta_sum + EXCLUDED.delta;Inside the snippet
The write path is a single statement: the INSERT ... SELECT takes its rows from the VALUES batch and ORDER BY metric applies them in api_errors → api_latency → requests order, so any two transactions that sort their batches this way acquire the daily_counters row locks in one consistent order instead of interleaving.
ON CONFLICT (metric) DO UPDATE SET delta_sum = dc.delta_sum + EXCLUDED.delta makes each row insert-or-update atomic — the dc alias reads the stored row while EXCLUDED carries the incoming delta.
Using it
Run the CREATE TABLE block first: metric text PRIMARY KEY fixes row identity and delta_sum bigint NOT NULL DEFAULT 0 starts new counters at zero, so the seed INSERT creates the three rows and every sorted batch after that takes the DO UPDATE path.
Key statements
INSERT INTO daily_counters AS dc (metric, delta_sum)
SELECT metric, delta
FROM (
VALUES
('api_errors', 3),
('api_latency', -1),
('requests', 12)
) AS batch(metric, delta)
ORDER BY metric
ON CONFLICT (metric) DO UPDATE
SET delta_sum = dc.delta_sum + EXCLUDED.delta;
INSERT INTO daily_counters (metric, delta_sum) VALUES
('requests', 0), ('api_latency', 0), ('api_errors', 0);
CREATE TABLE daily_counters (
metric text PRIMARY KEY,
delta_sum bigint NOT NULL DEFAULT 0
);
Interactive Tools for This Topic
FAQ
- Which tables does the SQL touch?
- `daily_counters`, `set`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.