Problem
Say I have the following insert statement:
insert into table_1 (...) values (...), (...), (...);
Assuming I know those 3 rows will be correctly inserted (no clause is violated), how can I fetch the id field of each inserted row into a separate variabile in order for me to use it in the rest of the .sql script?
What I tried
I've read about returning which would presumably translate into:
insert into table_1 (...) values (...), (...), (...) returning id;
I've also read about with (Common Table Expressions) which could "save" the result of returning into a table for later use in the following insert statements;
but it appears that I would then have to get the ids as select id from temp_table associating some kind of selector to distinguish between each 3 rows.
Question
Is there a way to get the ids of each inserted row to later use them, separately, in a different insert statement?
array_aggthat returning ID and assign it to array variable, then sorting order will be the same as inserts and you will be able to just do my_arr[1], my_arr[2] to get ID of specific rows.SELECT array_agg(returned_id) INTO my_ids FROM ins_cte. From what little test I did it seems to preserve order.