Postgres features interviews ask · mid
Upsert (ON CONFLICT) and RETURNING
INSERT ... ON CONFLICT (cols) DO UPDATE / DO NOTHING performs an atomic insert-or-update based on a unique constraint, and RETURNING gives back the affected rows in the same statement, which together make idempotent writes simple and race-free.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- ON CONFLICT needs a unique index or constraint on the target columns. EXCLUDED refers to the row you tried to insert: DO UPDATE SET qty = carts.qty + EXCLUDED.qty.
- DO NOTHING ignores duplicates (e.g. recording processed webhook event ids); combine with RETURNING to know whether you inserted.
- It is atomic: no 'select then insert' race.
- RETURNING id, created_at avoids a second query after INSERT/UPDATE/DELETE. Postgres 18 adds OLD and NEW in RETURNING (see values before and after an UPDATE).
- MERGE (Postgres 15+, RETURNING since 17) handles more complex insert/update/delete logic from a source table.
- Upserts can still deadlock or contend on hot keys; keep the statement simple and indexed.
- SQLite supports the same ON CONFLICT ... DO UPDATE and RETURNING syntax; MySQL uses INSERT ... ON DUPLICATE KEY UPDATE.
The red pen
Common traps: mistake → fix
Mistake: ON CONFLICT works on any column
Fix: it needs a matching unique constraint or index.
Mistake: SELECT, then INSERT or UPDATE, is equivalent
Fix: two concurrent requests both see 'missing' and one fails or duplicates.
Easy to hard
Questions interviewers ask, easy to hard
- How do you insert-or-update a row atomically in Postgres?
- What is EXCLUDED?
- How would you record processed webhook ids so each is handled once?
- Why use RETURNING?
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.