UPSERT & RETURNING in SQL
Insert-or-update atomically, read back what you wrote
Upsert inserts or, on key conflict, updates instead — one atomic statement replacing racy select-then-insert. PostgreSQL/SQLite: ON CONFLICT (key) DO UPDATE; MySQL: ON DUPLICATE KEY UPDATE. Needs a real UNIQUE constraint to conflict on. RETURNING returns affected rows in the same statement — new ids, updated values — with no second SELECT race.
Race without upsert
Select-then-insert races under concurrency — duplicates slip through.
Upsert atomically
ON CONFLICT / ON DUPLICATE KEY collapses check+write into one atomic statement.
Constraint is the trigger
No UNIQUE constraint means no conflict detection — duplicates insert silently.
RETURNING closes the loop
Fetch written rows in-statement — no second SELECT race for new ids.
1INSERT INTO employees (id, name, department, salary, age) VALUES (1, 'Zara', 'Sales', 60000, 30) ON CONFLICT (id) DO UPDATE SET salary = 60000 RETURNING id, name, salary;
| id | name | salary |
|---|---|---|
| 1 | Alice | 60000 |
id 1 conflicts with Alice, so the statement updates instead of erroring, then returns the written row. No separate SELECT needed — the id fetch is race-free.
Counter upsert
Hit counter that cannot double-insert.
1INSERT INTO counters (k, n) VALUES ('hits', 1) ON CONFLICT (k) DO UPDATE SET n = counters.n + 1 RETURNING k, n;
| k | n |
|---|---|
| hits | 2 |
Employee conflict update
Existing id updates instead of erroring.
1INSERT INTO employees (id, name, department, salary, age) VALUES (1, 'Zara', 'Sales', 60000, 30) ON CONFLICT (id) DO UPDATE SET salary = 60000 RETURNING id, name, salary;
| id | name | salary |
|---|---|---|
| 1 | Alice | 60000 |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.