On Conflict Cannot Affect Row Twice

Inserting two rows that hit the same conflict target fails with cannot affect row a second time; aggregate the source by key first so each target appears once.

SqlData Integrity

Code

snippet
-- INSERT ... SELECT 里同一个冲突目标出现两行时:
-- ON CONFLICT DO UPDATE 无法对同一行执行两次,整条语句以基数错误失败
CREATE TABLE counters (key text PRIMARY KEY, hits int NOT NULL);
INSERT INTO counters VALUES ('page-a', 1);

-- 暂存数据里 'page-a' 出现两次:
-- INSERT INTO counters (key, hits)
-- SELECT * FROM (VALUES ('page-a', 5), ('page-a', 7), ('page-b', 3)) AS s(key, hits)
-- ON CONFLICT (key) DO UPDATE SET hits = counters.hits + EXCLUDED.hits;
-- ERROR: ON CONFLICT DO UPDATE command cannot affect row a second time

-- 修正:先在源端按 key 归并,保证每个冲突目标只出现一次
INSERT INTO counters (key, hits)
SELECT key, SUM(hits)
FROM (VALUES ('page-a', 5), ('page-a', 7), ('page-b', 3)) AS s(key, hits)
GROUP BY key
ON CONFLICT (key) DO UPDATE SET hits = counters.hits + EXCLUDED.hits;

SELECT * FROM counters ORDER BY key;

How it works

The file stands up its own playground in two statements: CREATE TABLE counters (key text PRIMARY KEY, hits int NOT NULL) defines the conflict target, and one INSERT seeds it with a single page-a row. The commented-out block then shows the trap — feeding two page-a rows (plus page-b) straight into INSERT ... SELECT ... ON CONFLICT (key) DO UPDATE fails, because one statement may not affect the same target row twice; the file’s comment quotes the exact error text. The working statement fixes it at the source: SELECT key, SUM(hits) ... GROUP BY key collapses the duplicate page-a entries into one row before the upsert, and DO UPDATE SET hits = counters.hits + EXCLUDED.hits adds the incoming hits to whatever the row already held. A final SELECT * FROM counters ORDER BY key reads the merged state back.

What to watch for

  • The failure is about cardinality, not permissions: when one source row set touches the same conflict target twice, ON CONFLICT DO UPDATE rejects the whole statement with that error.
  • EXCLUDED carries the would-be-inserted values inside the DO UPDATE arm — counters.hits + EXCLUDED.hits is what turns the upsert into an increment rather than an overwrite.

Key statements

INSERT INTO counters (key, hits)
SELECT key, SUM(hits)
FROM (VALUES ('page-a', 5), ('page-a', 7), ('page-b', 3)) AS s(key, hits)
GROUP BY key
ON CONFLICT (key) DO UPDATE SET hits = counters.hits + EXCLUDED.hits;
CREATE TABLE counters (key text PRIMARY KEY, hits int NOT NULL);

Interactive Tools for This Topic

FAQ

Why does the commented-out INSERT fail?
Its source rows contain `page-a` twice, and `ON CONFLICT (key) DO UPDATE` cannot affect the same target row twice in one statement — the file's comment quotes the resulting error, `ON CONFLICT DO UPDATE command cannot affect row a second time`.
How does the working statement avoid it?
It collapses the source first with `SUM(hits)` and `GROUP BY key`, so each conflict target appears exactly once before the upsert runs.