PostgreSQL
 sql >> Datenbank >  >> RDS >> PostgreSQL

PostgreSQL Upsert (On Conflict) mit denselben Werten in Insert und Update

Verwenden Sie den excluded Schlüsselwort:

INSERT INTO cars 
  (car_id, car_type, car_model) 
values
  (1, 'tesla', 'model s')
ON CONFLICT (car_id) DO UPDATE SET 
  car_type = excluded.car_type,
  car_model = excluded.car_model;

Dies funktioniert auch korrekt mit mehreren Zeilen, z. B.:

INSERT INTO cars 
  (car_id, car_type, car_model) 
values
  (1, 'tesla', 'model s'), 
  (2, 'toyota', 'prius')
ON CONFLICT (car_id) DO UPDATE SET 
  car_type = excluded.car_type,
  car_model = excluded.car_model;