Move SQL data from one table to another

后端 未结 13 2904
梦如初夏
梦如初夏 2020-11-29 20:34

I was wondering if it is possible to move all rows of data from one table to another, that match a certain query?

For example, I need to move all table rows from Tab

13条回答
  •  天涯浪人
    2020-11-29 21:35

    Here is how do it with single statement

    WITH deleted_rows AS (
    DELETE FROM source_table WHERE id = 1
    RETURNING *
    ) 
    INSERT INTO destination_table 
    SELECT * FROM deleted_rows;
    

    EXAMPLE:

        postgres=# select * from test1 ;
     id |  name
    ----+--------
      1 | yogesh
      2 | Raunak
      3 | Varun
    (3 rows)
    
    
    postgres=# select * from test2;
     id | name
    ----+------
    (0 rows)
    
    
    postgres=# WITH deleted_rows AS (
    postgres(# DELETE FROM test1 WHERE id = 1
    postgres(# RETURNING *
    postgres(# )
    postgres-# INSERT INTO test2
    postgres-# SELECT * FROM deleted_rows;
    INSERT 0 1
    
    
    postgres=# select * from test2;
     id |  name
    ----+--------
      1 | yogesh
    (1 row)
    
    postgres=# select * from test1;
     id |  name
    ----+--------
      2 | Raunak
      3 | Varun
    

提交回复
热议问题