0

It is the query


insert into xyz_table (id_, column1, column2, 
column3, column4, column5) 
select a.id_, a.column1, a.column2, a.column3, a.column4, a.column5
from xyz_view a;

I need to copy the bulk data from xyz_view to the xyz_table. As of now the view is not having the sequence id generator. I need to provide id_, generated in a sequence for each row I copy from view to the table.

For testing purpose I need to do this only by postgres sql query.

Note: The xyz_view doesn't have the id_ column. I explicitly added these id_column in the query level to provide the id_ for each row in xyz_table sequentially.

If possible, porivde me a working query.

1
  • If the id column doesn't exist in your view and it is mapped to a serial type in your table, you could exclude it from your insert query and let the database take care of auto incrementing it. Commented Oct 22, 2021 at 23:03

1 Answer 1

2

You could use row_number to generated a sequential id

insert into xyz_table (id_, column1, column2, 
column3, column4, column5) 
select row_number() OVER () AS id, a.column1, a.column2, a.column3, a.column4, a.column5
from xyz_view a;
Sign up to request clarification or add additional context in comments.

4 Comments

...or if the id column is a serial, you could exclude it from your insert queries and let the database do its job..?
yes, but it seems that the user wants one per insert
Thank you guys, it worked. could you explain me what it is doing?
it makes exactly what you ask for, for every row in the view it add its row number, which marks its position on the result set. it is art if th window function and has a number of more posibilities

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.