Upsert With ON CONFLICT
Insert a row or update it when the unique key already exists, in one atomic statement that avoids a race between read and write.
Code
INSERT INTO user_stats (user_id, login_count, last_login_at)
VALUES ($1, 1, now())
ON CONFLICT (user_id) DO UPDATE
SET
login_count = user_stats.login_count + EXCLUDED.login_count,
last_login_at = EXCLUDED.last_login_at
RETURNING user_id, login_count, last_login_at;Report a problem with this exampleOpens a pre-filled issue on GitHub.