Video in progress
Why do we need `INSERT ... ON CONFLICT` in PostgreSQL?
It's an "upsert": it tries to insert a row, and if there's a unique constraint conflict, instead of an error it either updates the existing row (DO UPDATE) or silently moves on (DO NOTHING). It all happens in one atomic statement.
📖 Answer
The classic wrong approach is a SELECT first, then an INSERT if nothing is found:
if (repo.findBySku(sku).isEmpty()) {
repo.save(new Product(sku, ...)); // two parallel requests both get here
}
If two threads check at the same time, both see "not there", and one of them fails with a unique violation. ON CONFLICT resolves this race inside the database:
INSERT INTO product_stock (sku, quantity)
VALUES ('A-100', 5)
ON CONFLICT (sku)
DO UPDATE SET quantity = product_stock.quantity + EXCLUDED.quantity;
EXCLUDED holds the new values you were trying to insert. For ON CONFLICT (sku) there must be a unique constraint or unique index on the sku column.
It's also handy for idempotent processing, for example when the same webhook arrives twice from the payment system:
INSERT INTO processed_events(event_id) VALUES (:id)
ON CONFLICT DO NOTHING;
If the number of affected rows is 0, the event has already been processed.
Sign up to mark studied questions and save your progress.