Upsert & Conflict Handling
Insert a row, or update it if it already exists, in one atomic statement.
What is it?
Sometimes you don't know whether a row exists yet, like when syncing a record from another system or incrementing a page-view counter that may not have started. A SELECT to check, then an INSERT or UPDATE, isn't safe. Two requests at once can both see "doesn't exist" and both insert, causing a duplicate-key error or one update silently overwriting the other.
An upsert (INSERT ... ON CONFLICT in Postgres, MERGE in standard SQL and SQL Server) does the check and the write as one atomic operation, removing that race.
Explain like I'm 10
It's a hotel desk that creates or updates a guest's reservation in one motion, instead of an agent looking the guest up, stepping away, and someone double-booking the room before the agent acts on what they saw.
Examples
Insert, or update the existing row on conflict
INSERT INTO page_views (page_id, views)
VALUES ('home', 1)
ON CONFLICT (page_id)
DO UPDATE SET views = page_views.views + 1;If no 'home' row exists, it's inserted with 1 view. If one exists, its views are incremented instead, atomically, with no gap for a race.
Ignore instead of update
INSERT INTO users (email, name)
VALUES ('a@example.com', 'Alice')
ON CONFLICT (email) DO NOTHING;If a user with this email exists, the statement does nothing instead of erroring or overwriting. Useful for safe, repeatable deduplication.
How it works
The database tries the insert. If it would break a unique constraint or primary key named in ON CONFLICT, it runs the fallback (DO UPDATE or DO NOTHING) on the existing row instead of raising an error, all as one atomic operation.
Because it's atomic, no other transaction can slip a conflicting write in between "check" and "write." A separate SELECT-then-INSERT in app code can't guarantee that.
Why does it exist?
It removes the race in "check, then act" logic in app code, and saves the extra round trip of a SELECT before deciding to INSERT or UPDATE.
When to use it
Use an upsert when syncing external data that may already exist, maintaining counters, building "create or update settings" endpoints, or deduplicating on a unique column like email.
When not to use it
When insert and update should trigger different app behavior (like a "welcome" email only on real creation), an upsert hides which branch ran unless you inspect what it returned. Separate insert and update logic can be clearer.
Common mistakes
Naming a column in ON CONFLICT that has no real unique constraint or primary key. Postgres needs an actual constraint to detect the conflict.
Forgetting that DO UPDATE must use the table name (like page_views.views) to mean the existing row's value, not the attempted new one.
Keeping SELECT-then-INSERT/UPDATE app logic where there's real concurrency, and hitting rare but real races an upsert would avoid.
Practice exercises
- Easy:
Write an upsert that inserts a product by sku, or increments its stock count if the sku exists.
- Medium:
Write an upsert with ON CONFLICT DO NOTHING that safely deduplicates email signups.
- Hard:
Step by step, show how two simultaneous requests using SELECT-then-INSERT (no upsert) could both succeed and create two rows despite an intended uniqueness rule.
Interview questions
What problem does an upsert solve that a SELECT followed by INSERT or UPDATE doesn't?
It removes the race between checking whether a row exists and writing it, by making check-and-write one atomic operation.
What must the column(s) named in ON CONFLICT correspond to?
A real unique constraint or unique index on the table, not just columns that happen to be unique in practice.
What's the difference between ON CONFLICT DO NOTHING and DO UPDATE?
DO NOTHING silently skips the write on a conflict. DO UPDATE changes fields on the existing conflicting row.
Walk through how two concurrent SELECT-then-INSERT sequences can both 'see' no existing row and both attempt to insert.
Both run their SELECT at nearly the same moment, before either inserts, so both correctly see no row and both INSERT. The check was right when it ran but stale by the time of the write.
Why doesn't wrapping the SELECT-then-INSERT in a transaction at the default READ COMMITTED isolation level fix that race on its own?
READ COMMITTED only makes each statement see data committed as of when it runs. A second transaction's SELECT can still run (and see nothing) before the first one's INSERT commits, so both can insert.
Why does making the check-and-write a single atomic upsert statement close the race regardless of isolation level?
There's no gap between check and write for another transaction to slip into. The database detects the conflict and applies the fallback as one operation, so a second concurrent attempt finds the row and takes the DO UPDATE/DO NOTHING path instead of inserting.
What is the `EXCLUDED` pseudo-table in Postgres's INSERT ... ON CONFLICT DO UPDATE, and what does it refer to?
The row proposed for insertion: the new values from VALUES that hit the conflict. DO UPDATE can use it to refer to the attempted new data, separate from the existing row.
In `DO UPDATE SET views = page_views.views + 1`, why reference the table name (`page_views.views`) rather than `EXCLUDED.views`?
page_views.views is the value already in the existing row. EXCLUDED.views is the attempted new value (here, the literal 1), so EXCLUDED.views + 1 would ignore the row's current count.
What does the standard SQL / SQL Server MERGE statement do, and how does it compare to Postgres's INSERT ... ON CONFLICT?
MERGE matches a set of source rows against a target table, with different actions for matched and unmatched rows in one statement (typically update if matched, insert if not). ON CONFLICT is a narrower, insert-first version for rows hitting a specific unique constraint.
What's one thing MERGE can express that a single ON CONFLICT clause typically can't?
MERGE can act on target rows missing from the source (e.g. delete them) and process many source rows against the target in one statement. ON CONFLICT only reacts to conflicts from the rows you're inserting.
How would you make an ON CONFLICT DO UPDATE conditional, and how does that differ from DO NOTHING?
Add a WHERE after the SET list: DO UPDATE SET ... WHERE <condition>. The update applies only when the condition holds. DO NOTHING never touches the row; a false WHERE still recognizes the conflict but changes nothing.
Why can ON CONFLICT target a specific named constraint instead of listing columns directly, and when would you need that?
Use ON CONFLICT ON CONSTRAINT constraint_name when the uniqueness isn't a simple column list (e.g. a rule defined with an expression), or to say exactly which of several unique constraints you mean.
Can ON CONFLICT target a partial unique index (one defined with its own WHERE clause)? What has to match?
Yes, but the target must match both the indexed columns/expression and the index's WHERE condition. A row outside the partial index's condition can't conflict with it.
How would you find out, after running an upsert, whether it actually inserted a new row or updated an existing one?
Add a RETURNING clause with something that differs between paths (like xmax = 0 in Postgres, true only for a fresh insert), or use the value change itself if it's distinguishable.
Why is an upsert alone not enough when insert and update are supposed to trigger genuinely different application behavior, like sending a welcome email only on true creation?
The statement doesn't tell your code which path it took. Inspect what it returned (e.g. with RETURNING) to branch correctly, instead of assuming it always means 'created'.
What's a gotcha with auto-incrementing primary keys and an upsert that hits a conflict and ends up doing nothing?
The sequence value generated for the attempted insert is still used up even though no row was created, leaving a permanent gap. Harmless, but surprising the first time.
Why does that sequence-gap behavior happen — why doesn't the database 'give the number back' when the conflicting insert doesn't go through?
Sequences hand out values without blocking or coordinating with other transactions. Taking a value back depending on a later step would need exactly the locking sequences avoid. Gaps are the price of that speed.
What does 'idempotent write' mean, and how does DO NOTHING support writing idempotent sync code?
An idempotent write can be applied many times with the same result as once. DO NOTHING makes re-inserting the same row (say, retrying a sync job after a partial failure) a no-op instead of an error.
How would you write a single statement that upserts many rows at once from a bulk import, rather than one row at a time?
Use a multi-row VALUES list (or INSERT ... SELECT ... from a staging table) with one ON CONFLICT clause. Conflicts are handled per row, but it's one statement instead of one round trip per row.
Why is INSERT ... ON CONFLICT generally faster than the equivalent SELECT-then-INSERT/UPDATE application logic, even ignoring the race condition it fixes?
It's one round trip instead of two or more. A separate SELECT and a conditional INSERT or UPDATE each pay their own network and query-planning overhead.
Scenario: importing 10,000 rows with ON CONFLICT (email) DO NOTHING, the table's row count only grows by 9,000. What happened to the other 1,000, and is it a bug?
Not a bug. Those 1,000 emails already existed, and DO NOTHING skipped them, exactly as designed for safe, repeatable deduplication.
Debugging: an upsert meant to catch duplicate emails inserted a new row for what looks like the same email, just different casing, instead of updating the existing one. What's the likely explanation?
The unique constraint is on the raw email column, and values differing in case aren't equal to it. You'd need a case-insensitive unique index (e.g. UNIQUE (LOWER(email))) with a matching ON CONFLICT target.
Why must the column(s)/expression named in ON CONFLICT match an existing unique constraint or index precisely?
Postgres needs to know exactly which constraint violation to catch and redirect to the fallback. It can't infer that from columns that happen to be unique without a declared constraint or index.
What error does Postgres raise if you write ON CONFLICT (col) but no unique constraint or index exists on that exact column?
An error at query time (something like 'there is no unique or exclusion constraint matching the ON CONFLICT specification'). It doesn't silently fall back to a plain insert.
How does MySQL's INSERT IGNORE differ in behavior from Postgres's ON CONFLICT DO NOTHING?
INSERT IGNORE suppresses a broader set of errors, not only duplicate keys but also things like some data-truncation or not-null violations, turning them into warnings. ON CONFLICT DO NOTHING only handles a conflict with the declared or inferred constraint.
Can ON CONFLICT DO NOTHING be written without naming a specific column or constraint at all — what does it apply to then?
Yes. Without a target, it skips a row that conflicts with any unique or exclusion constraint. Other violations, such as NOT NULL or CHECK, still raise an error. DO UPDATE requires an explicit target, because it must know which existing row to update.
What isolation-related guarantee is a SELECT ... FOR UPDATE followed by INSERT/UPDATE inside a transaction also trying to achieve, and why is an upsert usually simpler?
It locks the possibly conflicting row so no other transaction can act on it between check and write. An upsert gives the same race-free result without reasoning about explicit locks, lock ordering, or holding a transaction open across the whole sequence.
Why would separate, explicit INSERT and UPDATE logic still be preferable over an upsert in some cases, despite the upsert being safer against races?
When insert and update need different behavior (different validation, or side effects like a welcome email), two explicit paths keep the branching obvious, instead of hiding it in one statement whose outcome must be inferred from its return value.