2

I have a table with two columns: id, age where id is the primary key

I know how to insert ONE new row for new primary key else update the age with the new value if the age value is not null using the following sql:

insert into obj (id, age) 
values (2, 42) 
on conflict (id) do 
update set age = coalesce(42, obj.age)

but how do I do it with multiple rows? For example:

insert into obj (id, age) 
values (2, 42), (3, 43), (5, 60) 
on conflict (id) do 
update set age = coalesce(???, obj.age)

the question is what should I put in the '???' in COALESCE?

I thought some one suggested using COALESCE(values(age), obj.age, I tried but it didn't work (syntax error).

1 Answer 1

1
insert into obj (id, age) 
values (2, 42), (3, 43), (5, 60) 
on conflict (id) do 
update set age = coalesce(excluded.age, obj.age)

Note the use of the special record excluded. Per the documentation:

The SET and WHERE clauses in ON CONFLICT DO UPDATE have access to the existing row using the table's name (or an alias), and to rows proposed for insertion using the special excluded table.

Sign up to request clarification or add additional context in comments.

Comments

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.