Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform a MERGE (insert/update/delete) using PostgreSQL?

Tags:

sql

postgresql

I'm using INSERT ... ON CONFLICT ... to be able to upsert some data in a PostgreSQL table.

But now I'd also like to be able to delete some existing rows, if they are not provided by the current INSERT query. So, in addition to INSERT and UPDATE, I would like to be able to do a DELETE.

Using SQL Server, I would do this using a MERGE query and :

WHEN NOT MATCHED BY SOURCE THEN DELETE

What is the recommended way to achieve something similar using PostgreSQL?

I would prefere not to run two separated queries.

like image 735
electrotype Avatar asked Jul 30 '18 14:07

electrotype


People also ask

Which command you use to combine insert update and DELETE operations?

The MERGE statement actually combines the INSERT, UPDATE, and the DELETE operations altogether.

Can we use DELETE in MERGE statement?

Instead of writing a subquery in the WHERE clause, you can use the MERGE statement to join rows from a source tables and a target table, and then delete from the target the rows that match the join condition.

Is it possible to insert update and DELETE within one select statement?

With a MERGE you can can 'sync' two tables by executing an insert, delete and update in ONE statement. A MERGE is much more than that though; it offers you a wide range of options in comparing and syncing tables. You can even keep track of the output of the merge.


1 Answers

You could use a CTE for that

WITH updated AS (
INSERT ... 
INTO tbl 
ON CONFLICT ...
RETURNING your_primary_key
)
DELETE FROM tbl t 
WHERE your_primary_key NOT IN ( 
  SELECT updated.your_primary_key FROM updated
);
like image 111
Thomas Berger Avatar answered Oct 26 '22 22:10

Thomas Berger