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.

SqlData Integrity

Code

sqlsnippet
7 lines
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;

How it works

What runs is INSERT / UPDATE, with user_stats and set as the object involved.

Breaking the statements into their working parts: an upsert guard (ON CONFLICT/MERGE) that turns insert-or-update into one atomic statement; a RETURNING clause that hands the affected rows back to the caller.

Putting it to use

The user_stats table is the working surface here.

Core lines

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;

Interactive Tools for This Topic

FAQ

Which relations are involved here?
The references are `user_stats`, `set`.