ON CONFLICT (UPSERT)
# ON CONFLICT (UPSERT)
You can use
ON CONFLICT (column_name) to perform a different action
when trying to insert a record. For example, you can update the existing
record instead of just having a constraint exception raised.
NOTE: the columns used in
ON CONFLICT must be backed by a database
INSERT INTO vehicle_make_model_tiers (make, model, tier) VALUES ('A', 'B', 1), ('A', 'C', 2) ON CONFLICT (make, model) DO UPDATE SET tier = EXCLUDED.tier
- In this example we have a unique, compound index for
- So, when a conflict arises, instead of just throwing the exception…
DOfollowed by the action.
- You could
DO UPDATE ...
EXCLUDED.column_nameto access the values of the conflicting insert attempt