'Get index of the current array element being processed by a foreach loop with postgres's plpgsql [duplicate]

Using postgres's plpgsql, I'm trying to use a foreach loop to iterate over the elements of an array. I am trying to see if there's a way to get (from within the loop) the index of the current element of the array being processed by the foreach loop, but so far I haven't been able to find a way to do it in the documentation, is there any way to do this?



Solution 1:[1]

There is no ready-made tool for this, but you can use an auxiliary variable, e.g.:

do $$
declare 
    a text;
    i int = 0;
begin
    foreach a in array array['a','b','c'] loop
        i:= i+ 1;
        raise notice '% %', i, a;
    end loop;
end $$

Solution 2:[2]

Why not just use a for loop over an integer:

do 
$$
declare 
  input text[] := array['a','b','c'];
begin
  for i in 1..cardinality(input) loop
    raise notice 'Index: %, value: %', i, input[i];
  end loop;
end $$
;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 klin
Solution 2 a_horse_with_no_name