Learn SQL
-- modifying.upsert_returning

UPSERT & RETURNING in SQL

Insert-or-update atomically, read back what you wrote

--concept

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.

--how it works
1

Race without upsert

Select-then-insert races under concurrency — duplicates slip through.

2

Upsert atomically

ON CONFLICT / ON DUPLICATE KEY collapses check+write into one atomic statement.

3

Constraint is the trigger

No UNIQUE constraint means no conflict detection — duplicates insert silently.

4

RETURNING closes the loop

Fetch written rows in-statement — no second SELECT race for new ids.

--visualization
ON CONFLICT (id) DO UPDATE — atomic, no race
idnamesalary
1Alice60000
Stage 1 / 1
id 1 hits Alice: updates + returns row — needs UNIQUE to conflict on.
--example
query.sql
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;
Result
idnamesalary
1Alice60000

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.

--variants

Counter upsert

Hit counter that cannot double-insert.

query.sql
1INSERT INTO counters (k, n) VALUES ('hits', 1) ON CONFLICT (k) DO UPDATE SET n = counters.n + 1 RETURNING k, n;
Result
kn
hits2
1First insert creates the row.
2Second call conflicts on UNIQUE(k) and increments.
3RETURNING hands back the new count atomically.

Employee conflict update

Existing id updates instead of erroring.

query.sql
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;
Result
idnamesalary
1Alice60000
1id 1 hits Alice — conflict detected via PK.
2DO UPDATE rewrites salary in place.
3RETURNING confirms the written values without re-read.
--key facts
Atomicityupsert kills the select-then-insert race
Needs UNIQUEno constraint = no conflict detection
RETURNINGPostgreSQL/SQLite write-plus-read in one trip
--use cases
Counters, carts, idempotent ingestion — retry-safe writes
New-id fetching without last_insert_id races
--under the hood
Upsert takes the arbiter UNIQUE index path — speculative insertion aborts cleanly on conflict; other engines emulate via MERGE.
RETURNING avoids a second index probe + closes the write-read race window.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Take the queries you just visualized and see the data structures that power real databases.