Replace — SQL Technical Interview Questions & Answers

Replace

Replace

  • REPLACE INTO students (roll, name, marks) VALUES (12, 'Asha', 90); if roll 12 exists, MySQL deletes that row and inserts the new one (PK/UNIQUE clash). It is not an in-place UPDATE — triggers and FKs behave like delete + insert.
  • Prefer INSERT … ON DUPLICATE KEY UPDATE when you want to keep the same row id and only change columns. REPLACE can break child rows.
  • Trap: using REPLACE as a casual synonym for UPDATE.
  • On the example next to this theory: Replace: create two demo rows, then SELECT qty >= 2 ordered. Say which labels come back.

Technical Interview Tip: REPLACE is delete+insert on key clash. Upsert with ON DUPLICATE KEY UPDATE.

Code Examples for Replace

Replace — sample query

-- Replace
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;

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

How to Explain Replace to an Interviewer

REPLACE vs UPDATE?

REPLACE may delete+insert UPDATE changes the same row