Ask Your Question
2

Is it possible to use both a column and a where clause in the INSERT .. ON CONFLICT statement in Postgres?

asked 2022-09-24 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-07-12 06:00:00 +0000

david gravatar image

Yes, it is possible to use both a column and a where clause in the INSERT .. ON CONFLICT statement in Postgres.

Here's an example:

INSERT INTO mytable (id, name, age) 
VALUES (1, 'John', 25) 
ON CONFLICT (id) 
   WHERE name <> excluded.name 
DO UPDATE 
   SET age = excluded.age;

In this example, the ON CONFLICT clause specifies that if a record with the same id already exists in the table, the update should be performed only if the name in the existing record is different from the name in the new record being inserted. If the names match, the update is not performed.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-09-24 11:00:00 +0000

Seen: 7 times

Last updated: Jul 12 '21