I am trying to loop through an integer array (integer[]) in a plpgsql function. Something like this:
declare
a integer[] = array[1,2,3];
i bigint;
begin
for i in a loop
raise notice "% ",i;
end loop;
return true;
end
In my actual use case the integer array a is passed as parameter to the function. I get this error:
ERROR: syntax error at or near "$1"
LINE 1: $1
How to loop through the array properly?
Postgres 9.1 added
FOREACHto loop over arrays:db<>fiddle here
Works for multi-dimensional arrays, too: Postgres flattens the array and iterates over all elements. To loop over slices, see link below.
For older versions:
For multi-dimensional arrays and looping over array slices see:
However, set-based solutions with
generate_series()orunnest()are often faster than looping over big sets. Basic examples: