I need to declare an array of records that will be inserted into some table then. But i cannot find a way to initialize this array. Like, for table like this:
create table mytable
(
id serial,
value varchar
);
I need something like:
do
$$
declare
rowsForTable mytable%rowtype[] := array [
( id=1, value='val 1' ),
( id=2, value='val 2' ),
( id=3 )
];
How could I achieve it?
Thank you!
2
Answers
Using the
array
andROW
constructors in PostgreSQL, you can initialise an array of composite types (records) for insertion into a table. While you cannot initialise fields directly, as in your example, you can initialise each field separately using theROW
constructor. This is how:This method utilises a loop to put values into the table after initialising each field using the
ROW
constructor. Due to the loop, it’s crucial to keep in mind that this approach works best for smaller datasets. For larger inserts, a more effective strategy like a singleINSERT INTO
line with aVALUES
clause could be preferable.Use just
mytable[]
forrowsForTable
datatype, notmytable%rowtype[]
. Use positional row literals w/o names to initialize the array.Please note the
null
in the third array element.