How can I insert the return of DELETE into INSERT in postgresql?

lanrat picture lanrat · Jul 5, 2011 · Viewed 15.6k times · Source

I am trying to delete a row from one table and insert it with some additional data into another. I know this can be done in two separate commands, one to delete and another to insert into the new table. However I am trying to combine them and it is not working, this is my query so far:

insert into b (one,two,num) values delete from a where id = 1 returning one, two, 5;

When running that I get the following error:

ERROR: syntax error at or near "delete"

Can anyone point out how to accomplish this, or is there a better way? or is it not possible?

Answer

Peter Eisentraut picture Peter Eisentraut · Jul 5, 2011

You cannot do this before PostgreSQL 9.1, which is not yet released. And then the syntax would be

WITH foo AS (DELETE FROM a WHERE id = 1 RETURNING one, two, 5)
    INSERT INTO b (one, two, num) SELECT * FROM foo;