Upserts (INSERT ... ON CONFLICT DO UPDATE / DO NOTHING, MERGE)
Idempotently insert-or-update rows with ON CONFLICT or MERGE.
In plain words
"Put this row in. If it's already there, update it instead." The database does both checks and the change in one go.
Think of it like…
A guest register at a hotel desk: if the guest is already listed, update their room number; if not, add a new line. Doing it in one motion means two clerks can't both add the same guest.
Where you’ve seen it
Syncing product prices from a supplier feed every hour: INSERT INTO products (sku, price) VALUES ($1, $2) ON CONFLICT (sku) DO UPDATE SET price = EXCLUDED.price, updated_at = now();. Running the same feed twice leaves the table in the same state.
Words you’ll hear
- Conflict target
- The unique column(s) that define "already exists"; must have a unique index or constraint.
- EXCLUDED
- In PostgreSQL, the row you tried to insert, used in DO UPDATE.
- Idempotent
- Running the operation twice gives the same result as running it once.
- MERGE
- Standard statement that matches a source against a target and inserts, updates or deletes.
Visual diagram
Theory & example queries
ON CONFLICT and ON DUPLICATE KEY
In PostgreSQL, ON CONFLICT (sku) DO UPDATE SET price = EXCLUDED.price updates the existing row using values from the row you tried to insert (EXCLUDED). DO NOTHING silently skips duplicates, which is handy for "insert if missing". A WHERE on DO UPDATE can skip rows that haven't changed, avoiding pointless writes.
MySQL's equivalent is INSERT … ON DUPLICATE KEY UPDATE price = new.price, using a row alias (the older VALUES(price) form is deprecated since 8.0.20). It fires on any unique key in the table, not one you name, which surprises people when a table has several unique indexes.
| id | name | price | category | stock |
|---|---|---|---|---|
| 42 | SQL Notebook | 49.5 | books | 18 |
| 84 | Mechanical Keyboard | 150 | hardware | 5 |
| 11 | Query Mug | 12.99 | gifts | 33 |
INSERT INTO products (sku, price)VALUES ('A-17', 499)ON CONFLICT (sku) DO UPDATESET price = EXCLUDED.priceWHERE products.price IS DISTINCT FROM EXCLUDED.price;PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Representative command statuses3 sample rows
| scenario | status |
|---|---|
| new SKU | INSERT 0 1 |
| existing SKU, changed price | INSERT 0 1 |
| existing SKU, same price | INSERT 0 0 |
Note: PostgreSQL command tags are illustrative: the conditional DO UPDATE affects one row when the price differs and zero rows when it does not.
Key takeaway: Name the conflict target, use EXCLUDED for the new values, and skip no-op updates.
Why not SELECT-then-INSERT, and where MERGE fits
Checking first and then inserting leaves a gap where another session can insert the same key, giving either a duplicate (without a unique constraint) or a unique-violation error. An upsert relies on the unique index to make the check and the write one atomic operation.
MERGE is more general: it compares a source table with a target and can insert, update and delete in one statement, which suits batch syncs. Under heavy concurrency it's not a drop-in replacement for ON CONFLICT: PostgreSQL's MERGE can still raise unique violations when sessions race, and SQL Server needs a HOLDLOCK hint for safety. A batch that contains the same key twice makes PostgreSQL fail with "ON CONFLICT DO UPDATE command cannot affect row a second time", so deduplicate the input first.
| id | name | price | category | stock |
|---|---|---|---|---|
| 42 | SQL Notebook | 49.5 | books | 18 |
| 84 | Mechanical Keyboard | 150 | hardware | 5 |
| 11 | Query Mug | 12.99 | gifts | 33 |
MERGE INTO products p USING staging s ON p.sku = s.sku WHEN MATCHED THENUPDATESET price = s.price WHEN NOT MATCHED THEN INSERT (sku, price)VALUES (s.sku, s.price);PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Representative MERGE summary
Note: Assumes one row is updated and two rows are inserted, totaling three affected rows; exact command tags and dialect behavior vary.
Key takeaway: Upserts beat check-then-insert; use MERGE for batch syncs, ON CONFLICT for concurrent writes.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Define "same row"
Decide which column(s) identify an existing record, such as sku or (user_id, date), and make sure there's a unique index on them.
CREATE UNIQUE INDEX ON products (sku)When to use it & trade-offs
What it is
An upsert inserts a row, or updates it if a row with the same unique key already exists, as one atomic statement. PostgreSQL and SQLite use INSERT … ON CONFLICT (key) DO UPDATE (or DO NOTHING), MySQL uses INSERT … ON DUPLICATE KEY UPDATE, and SQL Server, Oracle and PostgreSQL 15+ also offer the standard MERGE.
Why it matters: Imports, syncs, counters and retried API calls all need "create it if it's new, update it if not". Doing that as SELECT-then-INSERT in application code is racy: two requests can both see "not there" and both insert. A proper upsert lets the database handle it atomically and makes the operation safe to retry.
When to reach for it
- Syncing data from external feeds or other systems
- Idempotent API handlers that may be retried
- Counters and "last seen" tables keyed by user or date
When to avoid or be careful
- Check-then-insert logic in application code
- Upserting batches that contain duplicate keys
- DO UPDATE on every column when most rows are unchanged, which creates needless writes
Ways to insert-or-update
Strengths: Atomic, retry-safe, simple.
Watch out: Dialect-specific syntax; needs a unique index.
Strengths: Standard SQL; insert, update and delete in one statement.
Watch out: Less safe under heavy concurrency; more verbose.
Strengths: Works in any database.
Watch out: Race conditions, extra round trips, duplicate or failed inserts.
Interview signals & numbers to know
When this topic comes up
- “Insert if it doesn't exist, otherwise update”
- “Make this endpoint safe to retry”
- Duplicate key errors in a sync job
- “ON CONFLICT vs MERGE”
- Race condition between two inserts
Benchmarks & rules of thumb
- 1
- statement instead of SELECT + INSERT/UPDATE
- PostgreSQL 9.5
- ON CONFLICT introduced
- PostgreSQL 15
- MERGE introduced
Common mistakes & follow-ups
Common interview mistakes
- Writing ON CONFLICT without a unique index on the target columns and getting an error.
- Doing SELECT-then-INSERT and getting duplicates when two requests arrive together.
- Sending a batch with the same key twice and failing the whole statement.
Likely interviewer follow-ups
- Why is SELECT-then-INSERT unsafe under concurrency?
- What does EXCLUDED refer to in PostgreSQL's ON CONFLICT?
- When would you prefer MERGE over INSERT … ON CONFLICT?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Upserts (INSERT ... ON CONFLICT DO UPDATE / DO NOTHING, MERGE) with hands-on SQL practice and interview Q&A.