UPSERT หมายถึง "insert หรือ update หากมีอยู่แล้ว" PostgreSQL ทำสิ่งนี้ด้วย INSERT ... ON CONFLICT — insert แถวหนึ่ง แต่ถ้ามันจะละเมิด unique constraint ก็จะ update แถวที่มีอยู่แทน (หรือไม่ทำอะไรเลย) มันจัดการความต้องการ "insert หรือ update" ที่พบบ่อยได้อย่าง atomic
ปัญหาที่ UPSERT แก้
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)
