What if you could add or update data with one simple command and never worry about duplicates again?
Why INSERT ON CONFLICT (upsert) in PostgreSQL? - Purpose & Use Cases
Imagine you have a guest list for a party in a notebook. You want to add new guests, but if someone is already on the list, you want to update their details instead of writing them twice.
Manually checking if a guest is already on the list before adding or updating takes a lot of time and can cause mistakes like duplicates or missing updates.
INSERT ON CONFLICT lets you add new data or update existing data in one simple step, so you never have duplicates and always keep your list accurate.
DO $$ BEGIN IF EXISTS (SELECT 1 FROM guests WHERE id = 1) THEN UPDATE guests SET name = 'Alice' WHERE id = 1; ELSE INSERT INTO guests (id, name) VALUES (1, 'Alice'); END IF; END $$;
INSERT INTO guests (id, name) VALUES (1, 'Alice') ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name;
This makes managing data fast, safe, and simple, even when many changes happen at once.
When a website registers users, it can add new users or update existing user info without errors or duplicates using INSERT ON CONFLICT.
Manually checking for existing data is slow and error-prone.
INSERT ON CONFLICT combines insert and update in one command.
It keeps data clean and operations efficient.