Skip to Main Content

Database Software

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

combining "delete from one table" and "insert into another table" in one command

Martin PreissDec 19 2016 — edited Dec 19 2016

a task that occurs quite frequently in data warehouse systems is to delete some rows from a table and add these rows to an archive table. It would be nice to have a syntax to do this transfer in one step (instead of using one of the options shown recently by Jonathan Lewis in https://jonathanlewis.wordpress.com/2016/11/22/deleteinsert/ ). In postgres you can use subquery factoring and the returning clause to get this task done - as shown in the following example:

postgres=# select * from t1;

id

----

  1

  2

  3

  4

  5

  6

  7

  8

  9

10

(10 Zeilen)

postgres=# create table t2 as select * from t1 where 1 = 0;

SELECT 0

postgres=# select * from t2;

id

----

(0 Zeilen)

postgres=# with moved_rows as (delete from t1 where id <= 5 returning *)

postgres-# insert into t2 select * from moved_rows;

INSERT 0 5

postgres=# select * from t1;

id

----

  6

  7

  8

  9

10

(5 Zeilen)

postgres=# select * from t2;

id

----

  1

  2

  3

  4

  5

(5 Zeilen)

Comments
Post Details
Added on Dec 19 2016
9 comments
837 views