4

Can I simplify the syntax when I use the same values in an Insert... On Conflict statment?

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

There are many more statements of this kind because they are part of a script that gets run on every application update.

Bascially I am looking for a way to not specify the same value twice.

1 Answer 1

11

Use the excluded keyword:

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;

This also works correctly with multiple rows, e.g:

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;
Sign up to request clarification or add additional context in comments.

2 Comments

This looks great. Do you have to specify the excluded columns, even if all values should be updated?
@tommy: yes, unfortunately.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.