Search code examples
postgresqlsql-insertsql-delete

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


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?


Solution

  • Before PostgreSQL 9.1 you can create a volatile function like this (untested):

    create function move_from_a_to_b(_id integer, _num integer)
    returns void language plpgsql volatile as
    $$
      declare
        _one integer;
        _two integer;
      begin
        delete from a where id = _id returning one, two into strict _one, _two;
        insert into b (one,two,num) values (_one, _two, _num);
      end;
    $$
    

    And then just use select move_from_a_to_b(1, 5). A function has the advantage over two statements that it will always run in single transaction — there's no need to explicitly start and commit transaction in client code.