Suniel
Suniel

Reputation: 1499

Duplicate a row record in same table in postgresql

I want to duplicate a row record in same table but with modifications on some column values. I know i can duplicate a row record by using the following script.

INSERT INTO table_name( 
column_name1, column_name2, column_name3 ....
)
SELECT column_name1, column_name2, column_name3 ....
FROM table_name WHERE id=1;

But it will duplicate the whole row. For modification i further need to add update script.

So my question is, is there any simpler way to handle my scenario. Since the table in which i am working have around 40 columns, so i think this way is not feasible.

Any new ideas are most welcome.

Thanks in advance.

Upvotes: 11

Views: 14781

Answers (1)

krokodilko
krokodilko

Reputation: 36107

Change values of columns directly in SELECT, the aditional update is needless, just like in the below example

INSERT INTO table_name( 
column_name1, column_name2, column_name3 ....
)
SELECT column_name1, 
       'New string value of column 2', 
       column_name3,
       ......
       ......
       1234 as new_val_of_col_25,
       column_name26,
       ......
FROM table_name WHERE id=1;

Upvotes: 26

Related Questions