Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 34/ 160
02. Aggregations, Functions & Data Manipulation

Upserts (INSERT ... ON CONFLICT DO UPDATE / DO NOTHING, MERGE)

Idempotently insert-or-update rows with ON CONFLICT or MERGE.

IntermediateON CONFLICT · MERGE · Idempotent3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Only write when something changedQuery example
1Input dataStart from the source rows or state that the statement sees.
products
3 rows
products sample rows
idnamepricecategorystock
42SQL Notebook49.5books18
84Mechanical Keyboard150hardware5
11Query Mug12.99gifts33
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1INSERT INTO2  products (sku, price)3VALUES4  ('A-17', 499)5ON CONFLICT (sku) DO UPDATE6SET7  price = EXCLUDED.price8WHERE9  products.price IS DISTINCT FROM EXCLUDED.price;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/9
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative command statuses3 sample rows
Representative command statuses
scenariostatus
new SKUINSERT 0 1
existing SKU, changed priceINSERT 0 1
existing SKU, same priceINSERT 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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Batch sync with MERGE (PostgreSQL 15+, SQL Server, Oracle)Query example
1Input dataStart from the source rows or state that the statement sees.
products
3 rows
products sample rows
idnamepricecategorystock
42SQL Notebook49.5books18
84Mechanical Keyboard150hardware5
11Query Mug12.99gifts33
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1MERGE INTO products p USING staging s ON p.sku = s.sku WHEN MATCHED THEN2UPDATE3SET4  price = s.price WHEN NOT MATCHED THEN INSERT (sku, price)5VALUES6  (s.sku, s.price);
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/6
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative MERGE summary
MERGE 3

Note: Assumes one row is updated and two rows are inserted, totaling three affected rows; exact command tags and dialect behavior vary.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Upserts beat check-then-insert; use MERGE for batch syncs, ON CONFLICT for concurrent writes.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Design

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.

SQL at this step
1CREATE UNIQUE INDEX ON products (sku)
What to watch at this step
Required
unique index
Tip: use ← → to move between steps

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

INSERT … ON CONFLICT / ON DUPLICATE KEY
Best for: Concurrent single-row or batch upserts

Strengths: Atomic, retry-safe, simple.

Watch out: Dialect-specific syntax; needs a unique index.

MERGE
Best for: Batch syncs that also delete rows missing from the source

Strengths: Standard SQL; insert, update and delete in one statement.

Watch out: Less safe under heavy concurrency; more verbose.

SELECT, then INSERT or UPDATE in app code
Best for: Nothing, if an upsert is available

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?
Interview tip: Start with the race condition that makes check-then-insert wrong, then show ON CONFLICT as the fix. Mentioning idempotent retries ties it to real API design.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Type Casting & Conversion (CAST, ::, TRY_CAST)
Next topic
Bulk Data Loading (COPY, CSV Imports & Exports)