I have an insert statement that may insert single or multiple records into a table with an INSERT statement. I need to know what the primary id value is for each new row.
Tried adding the following to the insert statement:
RETURNING array_agg(new_seq_id) INTO new_ids
Get the following error:
[42803] ERROR: aggregate functions are not allowed in RETURNING
Is there a way to get an array into the returning statements of all the new sequence values?
3
Answers
You need to wrap it into a common table expression:
Yes, you can use a data modifying CTE.
After returning newly generated (and actually inserted!) IDs in a data-modifying CTE (like others provided), to insert into a table, you need an
INSERT
statement:TABLE cte
is the short form ofSELECT * FROM cte
.An ARRAY constructor is typically a bit faster than the (more versatile)
array_agg()
aggregate function. See:Only makes sense if you, indeed, need to return a single array. You might just return a set of rows with the
RETURNING
clause.