UPSERT betyder "infoga, eller uppdatera om det redan finns". PostgreSQL implementerar detta med INSERT ... ON CONFLICT — infoga en rad, men om det skulle bryta mot en unik constraint, uppdatera istället den befintliga raden (eller gör ingenting). Det hanterar det vanliga "infoga-eller-uppdatera"-behovet atomärt.
Problemet som UPSERT löser
You want to insert a row, but it might already exist (by a unique key):
❌ a plain INSERT fails with a unique-violation error if it exists
❌ check-then-insert (SELECT, then INSERT or UPDATE) has a RACE CONDITION
(another transaction could insert between your check and insert)
→ ON CONFLICT does it atomically in ONE statement (no race condition)
