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.colorDO NOTHING; MySQLINSERT ... ON DUPLICATE KEY UPDATE; SQL Server and OracleMERGE; PostgreSQL also hasMERGEsince 15 - Pitfalls: SQLite
INSERT OR REPLACEdeletes 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: