Databases sql Advanced

PostgreSQL UPSERT Pattern

Insert or update a row atomically with ON CONFLICT DO UPDATE — no race conditions.

sql
INSERT INTO module_stats (module_id, views, last_seen)
VALUES ($1, 1, now())
ON CONFLICT (module_id)
DO UPDATE SET
  views    = module_stats.views + EXCLUDED.views,
  last_seen = EXCLUDED.last_seen;

Prerequisites

  • PostgreSQL >= 9.5

Pro Tips

  • → Use EXCLUDED to reference the conflicting row's values.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
sql
Level
Advanced
Read time
2 min
Published
Jan 2026
License
Commercial License

Newsletter

New modules every week, directly to your inbox.