UPSERT — SQL Technical Interview Questions & Answers

UPSERT

UPSERT

  • Upsert = insert or update if the key exists. MySQL: INSERT … ON DUPLICATE KEY UPDATE … or REPLACE (harsher). Example: refresh Asha’s marks if roll 12 exists, else insert.
  • Needs a PRIMARY/UNIQUE key to detect ‘exists’.
  • Trap: upsert without a unique key — always inserts.
  • On the example next to this theory: UPSERT: create two demo rows, then SELECT qty >= 2 ordered. Say which labels come back.

Technical Interview Tip: INSERT … ON DUPLICATE KEY UPDATE marks = 90;

Code Examples for UPSERT

UPSERT — sample query

-- UPSERT
CREATE TABLE demo (
  id INTEGER PRIMARY KEY,
  label TEXT NOT NULL,
  qty INTEGER DEFAULT 0
);
INSERT INTO demo (id, label, qty) VALUES
  (1, 'alpha', 2),
  (2, 'beta', 5);
SELECT label, qty FROM demo WHERE qty >= 2 ORDER BY qty DESC;

UPSERT: create two demo rows, then SELECT qty >= 2 ordered. Say which labels come back.

How to Explain UPSERT to an Interviewer

MySQL upsert?

INSERT … ON DUPLICATE KEY UPDATE