Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL multiple on conflicts in one upsert statement

I have two unique constraints on the same table, and I want to do an upsert statement on that table.

Is it possible to specify the two conflicts in the upsert? I saw this: How to upsert in Postgres on conflict on one of 2 columns?

but my issue is slightly more involved because one of the unique constraints is a subset of the other unique constraint. I.e.

unique_constraint_1 = (col_1) unqiue_constraint_2 = (col_1, col_2)

INSERT INTO table (col_1, col_2, col_3) 
VALUES (val_1, val_2, val_3) 
ON CONFLICT (what do I put here to account for both constraints?) 
DO NOTHING; 

thanks!

like image 865
chris Avatar asked Jun 29 '16 21:06

chris


People also ask

Does PostgreSQL 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 in PostgreSQL?

In PostgreSQL, the UPSERT operation means either UPDATE or INSERT operation. The UPSERT operation allows us to either insert a row or skip the insert operation if a row already exists and update that row instead. Suppose you want to insert bulk data from one table to another table that already has some data.

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.

What does on conflict do nothing mean?

ON CONFLICT DO NOTHING simply avoids inserting a row as its alternative action. ON CONFLICT DO UPDATE updates the existing row that conflicts with the row proposed for insertion as its alternative action.


1 Answers

According to documentation, ON CONFLICT covers all unique constraints by default.

when omitted, conflicts with all usable constraints (and unique indexes) are handled

In your case there is no need for two constraints, as Grzegorz Grabek pointed out already. That is because the stricter single-column constraint already covers the looser two-column constraint.

like image 113
Jonathan Jacobson Avatar answered Sep 17 '22 15:09

Jonathan Jacobson