Upsert: INSERT … ON CONFLICT
The problem
"If the row exists, update it; otherwise insert it." Doing a SELECT and then an INSERT/UPDATE is two steps, and two users can collide in between (a race condition).
ON CONFLICT (PostgreSQL's upsert)
INSERT INTO t (key, value) VALUES (…)
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value;
- Conflict target
(key)– the column(s) of a UNIQUE constraint or primary key EXCLUDED– the row you tried to insert- One atomic statement → safe under concurrency ✅
DO NOTHING
ON CONFLICT (email) DO NOTHING – skip duplicates silently (imports, "insert if missing")
Conditional update
… DO UPDATE SET … WHERE t.updated_at < EXCLUDED.updated_at – only overwrite older data
Named constraint
ON CONFLICT ON CONSTRAINT one_budget_per_category DO UPDATE …
Common uses
- Counters: page views, daily totals →
SET count = t.count + 1 - Settings / preferences per user
- Syncing data from an API or an offline app
- Imports that may contain duplicates
Requirements and gotchas
- A unique index or constraint on the conflict columns must exist
RETURNINGworks too — use(xmax = 0) AS insertedto tell an insert from an update- The same row can't be affected twice in one statement (no duplicate keys in one multi-row VALUES list)
MERGE (SQL standard, PostgreSQL 15+)
MERGE INTO target USING source ON … WHEN MATCHED THEN UPDATE … WHEN NOT MATCHED THEN INSERT … – more powerful for syncing whole tables (it can also delete).
Example
-- Daily spending totals per user: insert or add to the existing total
CREATE TABLE daily_totals (
user_id INT REFERENCES users(id),
day DATE,
total NUMERIC(12,2) NOT NULL,
entries INT NOT NULL DEFAULT 1,
PRIMARY KEY (user_id, day)
);
INSERT INTO daily_totals (user_id, day, total)
VALUES (1, '2026-11-24', 450)
ON CONFLICT (user_id, day) DO UPDATE
SET total = daily_totals.total + EXCLUDED.total,
entries = daily_totals.entries + 1
RETURNING *, (xmax = 0) AS inserted; -- total 450, entries 1, inserted = true
INSERT INTO daily_totals (user_id, day, total)
VALUES (1, '2026-11-24', 300)
ON CONFLICT (user_id, day) DO UPDATE
SET total = daily_totals.total + EXCLUDED.total,
entries = daily_totals.entries + 1
RETURNING *, (xmax = 0) AS inserted; -- total 750, entries 2, inserted = false
-- DO NOTHING: import users, skipping emails that already exist
INSERT INTO users (name, email, city) VALUES
('Asha Duplicate', 'asha@example.com', 'Kathmandu'), -- exists → skipped
('Nisha Tamang', 'nisha@example.com', 'Dharan') -- new → inserted
ON CONFLICT (email) DO NOTHING
RETURNING name; -- only Nisha Tamang
-- MERGE (PostgreSQL 15+): sync account balances from a statement
CREATE TEMP TABLE bank_statement (user_id INT, name TEXT, balance NUMERIC);
INSERT INTO bank_statement VALUES (1, 'Bank', 90000), (2, 'Savings', 15000);
MERGE INTO accounts a
USING bank_statement s
ON a.user_id = s.user_id AND a.name = s.name
WHEN MATCHED THEN UPDATE SET balance = s.balance
WHEN NOT MATCHED THEN INSERT (user_id, name, balance) VALUES (s.user_id, s.name, s.balance);
SELECT user_id, name, balance FROM accounts WHERE user_id IN (1, 2) ORDER BY user_id, name;
DROP TABLE daily_totals;