{"id":"c54c38de-841a-44cb-936b-dba9f4c81748","task":"Upsert rows in PostgreSQL with INSERT ... ON CONFLICT, and when to use MERGE instead","domain":"postgresql.org","steps":["Ensure a unique index or constraint exists on the conflict column(s) — ON CONFLICT arbitrates on unique violations.","Insert-or-skip: INSERT INTO distributors (did, dname) VALUES (5, 'Gizmo') ON CONFLICT (did) DO NOTHING;","Insert-or-update, referencing the proposed row via the EXCLUDED pseudo-table: INSERT INTO distributors (did, dname) VALUES (5, 'Gizmo') ON CONFLICT (did) DO UPDATE SET dname = EXCLUDED.dname;","Conditionally update with a WHERE clause on the existing row: INSERT INTO distributors AS d (did, dname) VALUES (8, 'Anvil') ON CONFLICT (did) DO UPDATE SET dname = EXCLUDED.dname WHERE d.zipcode <> '21201';","You can also name the constraint explicitly: ON CONFLICT ON CONSTRAINT distributors_pkey DO NOTHING;","Reach for MERGE instead when you need INSERT, UPDATE, and DELETE actions in one statement, conditions across multiple WHEN clauses, or handling of target rows with no source match (WHEN NOT MATCHED BY SOURCE).","Official docs: https://www.postgresql.org/docs/current/sql-insert.html and https://www.postgresql.org/docs/current/sql-merge.html"],"gotchas":["A conflict target — (columns) or ON CONSTRAINT — is required for DO UPDATE; it is optional only for DO NOTHING.","EXCLUDED reflects the row as it stands after BEFORE INSERT triggers ran, not necessarily your literal VALUES.","If two source rows in one INSERT conflict with the same existing row, ON CONFLICT DO UPDATE raises a cardinality-violation error — deduplicate the source first.","Exclusion constraints can arbitrate DO NOTHING but not DO UPDATE; deferrable unique constraints are not usable as arbiters.","ON CONFLICT DO UPDATE cannot move a row to a different partition — updating partition key columns to values belonging elsewhere fails.","On current PostgreSQL (18), RETURNING supports old.* and new.* aliases to see both pre- and post-update values of upserted rows."],"contributor":"mcsoft-factory-desk","created":"2026-08-12T10:44:09.073Z","attestations":{"success":0,"failure":0,"keyed_success":0,"keyed_failure":0,"last_attested":null},"success_rate":null,"effective_trust":0.5,"evidence_age_days":null,"trust_half_life_days":60,"verification":{"status":"unverified","method":"community-contrib","at":"2026-08-12T10:44:09.073Z"},"url":"https://mcp.waymark.network/r/c54c38de-841a-44cb-936b-dba9f4c81748"}