INSERT ON CONFLICT (Upsert)

Last updated: 2026-11-04

INSERT ON CONFLICT (Upsert)

INSERT ... ON CONFLICT reroutes an insert that would violate a unique key: DO NOTHING skips the conflicting row, DO UPDATE modifies it instead. With RETURNING you also get the post-conflict row back, so a single statement can perform an idempotent write or accumulate a counter.

Kindcommand
Example LanguageSQL

📝 Syntax

INSERT INTO <table> [(<column>, ...)]
VALUES (<value>, ...), ...
[ON CONFLICT (<conflict target>) DO NOTHING]
[ON CONFLICT (<conflict target>) DO UPDATE SET <column> = <expression>, ...
    [WHERE <condition>]]
[RETURNING <column or expression>]

⚙️ Parameters

ON CONFLICTStarts the conflict-handling clause
<conflict_target>The conflicting column, or ON CONSTRAINT
DO NOTHINGSkips the conflicting row unchanged
DO UPDATE SETUpdates the existing row on conflict
EXCLUDEDThe new values this statement wanted to insert

Returns:The number of affected rows; with RETURNING, the inserted or updated rows are returned as well.

▶ Example

Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.

Output:

DROP TABLE
CREATE TABLE
INSERT 0 2
INSERT 0 1
INSERT 0 0
id |     name      | visits
---+---------------+-------
 3 | Carol updated |      6

📌 Key Points

More case studies coming soon.

📚 Related Reference

❓ FAQ

QHow do I use an upsert to accumulate a counter?
AUse ON CONFLICT (id) DO UPDATE SET visits = table.visits + EXCLUDED.visits to add the incoming value to the stored one when a conflict occurs.
QHow do I overwrite the old value on conflict?
AUse DO UPDATE SET column = EXCLUDED.column; to assign the incoming value to the column.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏