Merge Upsert Atomic Insert Or Update
Use MERGE or INSERT ON CONFLICT for atomic upsert without race conditions.
Code
-- PostgreSQL
INSERT INTO users (id, email, name, updated_at)
VALUES (1, 'user@example.com', 'Alice', NOW())
ON CONFLICT (id) DO UPDATE
SET email = EXCLUDED.email, name = EXCLUDED.name, updated_at = NOW();
-- SQL Server
MERGE users AS target
USING (VALUES (1, 'user@example.com', 'Alice')) AS source (id, email, name)
ON target.id = source.id
WHEN MATCHED THEN UPDATE SET email = source.email, name = source.name
WHEN NOT MATCHED THEN INSERT (id, email, name) VALUES (source.id, source.email, source.name);How the snippet works
What runs here is INSERT / UPDATE — users and set are the objects involved.
The pieces that do the work: an upsert guard (ON CONFLICT/MERGE) that turns insert-or-update into one atomic statement.
Applying it
The users table is the working surface here.
Statements that matter
MERGE users AS target
USING (VALUES (1, 'user@example.com', 'Alice')) AS source (id, email, name)
ON target.id = source.id
WHEN MATCHED THEN UPDATE SET email = source.email, name = source.name
WHEN NOT MATCHED THEN INSERT (id, email, name) VALUES (source.id, source.email, source.name);
INSERT INTO users (id, email, name, updated_at)
VALUES (1, 'user@example.com', 'Alice', NOW())
ON CONFLICT (id) DO UPDATE
SET email = EXCLUDED.email, name = EXCLUDED.name, updated_at = NOW();
Interactive Tools for This Topic
FAQ
- Which tables appear in this script?
- The references are `users`, `set`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.