0

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?

3
  • Maybe if you array_agg that 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. Commented Nov 22, 2017 at 14:43
  • Aggregate functions are not allowed in returning. Commented Nov 23, 2017 at 8:58
  • You are correct, but you can make your insert inside CTE and do SELECT array_agg(returned_id) INTO my_ids FROM ins_cte. From what little test I did it seems to preserve order. Commented Nov 23, 2017 at 10:03

1 Answer 1

1

You could use three CTEs:

with i1 as (
      insert into table_1 (...) values (...)returning id
     ),
     i2 as (
      insert into table_1 (...) values (...) returning id
     ),
     i3 as (
      insert into table_1 (...) values (...) returning id
     )
insert . . .;

This doesn't put the values into three variables. It does put them in three separate CTEs so each can be referred to individually.

Sign up to request clarification or add additional context in comments.

2 Comments

And I have to reference the id as select id from i1 limit 1?
@Shoe . . . That would be one approach.

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.