SQL

UPSERT — PostgreSQL ON CONFLICT

admin by @admin ADMIN
6m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`INSERT ... ON CONFLICT DO UPDATE` inserts a row, or updates the existing one if a unique-constraint collision happens. The atomic alternative to "SELECT, then INSERT or UPDATE".
SQL
Raw
-- Insert or bump the view count for a URL
INSERT INTO page_views (url, views, last_seen)
VALUES ('/about', 1, NOW())
ON CONFLICT (url) DO UPDATE
   SET views     = page_views.views + 1,
       last_seen = EXCLUDED.last_seen;
-- EXCLUDED.* refers to the row we tried to insert.

-- Ignore the insert entirely on conflict (no-op upsert)
INSERT INTO events (event_id, payload)
VALUES ('evt_123', '{}'::jsonb)
ON CONFLICT (event_id) DO NOTHING;

-- Conditional update — only overwrite if newer
INSERT INTO user_settings (user_id, theme, updated_at)
VALUES (42, 'dark', NOW())
ON CONFLICT (user_id) DO UPDATE
   SET theme = EXCLUDED.theme, updated_at = EXCLUDED.updated_at
   WHERE user_settings.updated_at < EXCLUDED.updated_at;

-- Composite unique constraint
INSERT INTO favorites (user_id, post_id, created_at)
VALUES (42, 9001, NOW())
ON CONFLICT (user_id, post_id) DO NOTHING;
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.