67

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?

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
Dipro Sen
  • 4,350
  • 13
  • 37
  • 50

1 Answers1

125

Postgres 9.1 added FOREACH to loop over arrays:

DO
$do$
DECLARE
   _arr  int[] := '{1,2,3,4}';
   _elem int;                      -- matching element type
BEGIN
   FOREACH _elem IN ARRAY _arr
   LOOP 
      RAISE NOTICE '%', _elem;
   END LOOP;
END
$do$;

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 i IN 1 .. array_upper(_arr, 1)  -- "i" is the index
   LOOP
      RAISE NOTICE '%', _arr[i];       -- single quotes
   END LOOP;

For multi-dimensional arrays and looping over array slices see:

However, set-based solutions with generate_series() or unnest() are often faster than looping over big sets. Basic examples:

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228