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;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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- Which relations are involved here?
- The references are `user_stats`, `set`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.