Skip to content
Advertisement

How to insert and delete from and to the same table in the same query?

Is there any way to select something from table A then delete & insert those records from/to table B (kind of updating B with values from A)?

Let’s say I have two following tables:

I came up with this:

This is working expect when it fails for “duplicate key value” error. However I thought maybe the delete is ran prior to insert but apparently they are executed is the same transaction.

At the end, Table B should become:

Anyone has any simple way to do that (without using temp tables and by doing only once the SELECT part of course)?

Advertisement

Answer

Provided that you have a unique constraint for (id, name) in B, I think that you need INSERT...ON CONFLICT:

See the demo.
Results:

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement