8

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.

3
  • We can't do that yet :^( Wait for PostgreSQL v12 which will probably have a MERGE statement... Commented Jul 30, 2018 at 16:02
  • So how do you workaround it using PostgreSQL? I mean, it's not such an edge case... Two requests are mandatory? Commented Jul 30, 2018 at 16:32
  • 1
    I think you will have to use two statements, yes. Commented Jul 30, 2018 at 16:35

1 Answer 1

8

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
);
Sign up to request clarification or add additional context in comments.

1 Comment

could you please create an example of the above? I'm not able to update values which already have an id (serial primary key) and insert values which do not exist in table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.