Skip to the solution
MediumDSA14 min read

What is an UPSERT?

662 views

The problem

Question presented to candidate: "What is an UPSERT? Show me how you would write one, and tell me why it is better than checking whether the row exists first."

What a strong answer should cover:

  • Definition: insert a row, or update it if a row with the same key already exists, as one statement
  • Why not "SELECT, then INSERT or UPDATE": two sessions can both see no row and both insert; one fails with a unique violation or a write is lost
  • It needs a unique constraint or primary key to decide what "already exists" means; the conflict target must match one
  • Syntax by engine: PostgreSQL and SQLite INSERT ... ON CONFLICT (key) DO UPDATE SET col = excluded.col or DO NOTHING; MySQL INSERT ... ON DUPLICATE KEY UPDATE; SQL Server and Oracle MERGE; PostgreSQL also has MERGE since 15
  • Pitfalls: SQLite INSERT OR REPLACE deletes and re-inserts (other columns reset), duplicate keys within one statement, MERGE is not a race-free upsert

Code / implementation expected: Yes β€” a counter upsert with ON CONFLICT DO UPDATE, and DO NOTHING.

Schema used by the examples:

  • upsert

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

14 min read Β· 12 sections

Run the code

Edit the query and run it against the tables for this question.

SQLCount page views: insert new pages, add to existing ones (ON CONFLICT DO UPDATE)
SQLInsert only if absent: ON CONFLICT DO NOTHING
SQLSQLite pitfall: INSERT OR REPLACE deletes the old row, so stock resets to its default
PostgreSQL 15+: sync products from a price feed with MERGE
MERGE INTO products AS p
USING price_feed AS f ON p.sku = f.sku
WHEN MATCHED AND p.price <> f.price THEN
  UPDATE SET price = f.price, updated_on = '2026-10-17'
WHEN NOT MATCHED THEN
  INSERT (sku, name, price, stock, updated_on)
  VALUES (f.sku, f.name, f.price, 0, '2026-10-17');

SELECT sku, name, price, stock, updated_on FROM products ORDER BY sku;

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 44 of 82 in SQL

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All SQL questions
Up nextMedium

What are ACID properties?

Continue