🐘 PostgreSQL Intermediate

What is the ON CONFLICT clause (upsert) in PostgreSQL?

Answer

ON CONFLICT (available since PostgreSQL 9.5) enables upsert behavior — insert a row, or take action if a conflict (UNIQUE/PRIMARY KEY violation) occurs. ON CONFLICT DO NOTHING: silently ignore duplicate inserts. ON CONFLICT (column) DO UPDATE SET col = EXCLUDED.col: update the existing row with the values that would have been inserted (accessed via the EXCLUDED pseudo-table). Example: INSERT INTO users (email, name) VALUES ('a@b.com', 'Alice') ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name, updated_at = NOW();. Specify the conflict target (column or constraint name) when multiple unique constraints exist. This is atomic — no race condition between check and insert.