Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upsert if on conflict occurs on multiple columns in Postgres db

I have a table in Postgres db with no primary keys. I want to update if the combination of 2 columns have the same value.

...
ON CONFLICT (col1, col2)
DO UPDATE

ELSE 
INSERT
...

I couldn't find anything without primary keys. Also, the combination of col1 and col2 is unique. There could be multiple rows for col1 with the same value or with col2 but together cannot.

So my table is something like this:

col1  col2
1     A    
1     B
2     A
2     B

I cannot have a unique constraint on either of these columns but adding the index together in a combination works as follows:

CREATE TABLE example (
col1 integer,
col2 integer,
col3 integer,
UNIQUE (col1, col3));

But now, how to handle the inserts. What should be the ON CONFLICT condition as we cannot have on 2 columns so back to the same issue.

like image 836
Atihska Avatar asked Feb 21 '18 21:02

Atihska


People also ask

Does Postgres support upsert?

PostgreSQL lets you either add or modify a record within a table depending on whether the record already exists. This is commonly known as an "upsert" operation (a portmanteau of "insert" and "update").

How does upsert work Postgres?

In relational databases, the term upsert is referred to as merge. The idea is that when you insert a new row into the table, PostgreSQL will update the row if it already exists, otherwise, it will insert the new row. That is why we call the action is upsert (the combination of update or insert).

What does on conflict do Postgres?

ON CONFLICT DO UPDATE updates the existing row that conflicts with the row proposed for insertion as its alternative action.

What is insert on conflict?

The INSERT ON CONFLICT statement allows you to update an existing row that contains a primary key when you execute the INSERT statement to insert a new row that contains the same primary key. This feature is also known as UPSERT or INSERT OVERWRITE. It is similar to the REPLACE INTO statement of MySQL.


1 Answers

Actually, found it here but not in the post marked as answer but the most rated post. Use multiple conflict_target in ON CONFLICT clause

So our query will be as follows:

INSERT into table (col1, col2, col3)
VALUES ('1', 'A', 'colval1A')
ON CONFLICT (col1, col2) DO UPDATE 
SET col3 = 'good_value'
like image 136
Atihska Avatar answered Oct 17 '22 02:10

Atihska