Skip to the page

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.

The 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

  1. How do you insert-or-update a row atomically in Postgres?
  2. What is EXCLUDED?
  3. How would you record processed webhook ids so each is handled once?
  4. Why use RETURNING?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview