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.
The MERGE statement actually combines the INSERT, UPDATE, and the DELETE operations altogether.
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.
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.
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
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With