Question

I iterate over an array, and do something with both the array value and its key. Since PostgreSQL 9.1 there is foreach loop, so the array value is no problem, but is there any elegant way to get the key? The only solution I found is to maintain extra variable for this:

CREATE OR REPLACE FUNCTION foobar( bar integer[] ) RETURNS integer AS $$
DECLARE
  foo integer;
  barkey integer;
BEGIN
  barkey := 1;
  FOREACH foo IN ARRAY bar LOOP
    -- do some stuff using foo and barkey
    barkey := barkey + 1;
  END LOOP;
END;
$$ LANGUAGE plpgsql;

Is this the best solution, or is there something more elegant?

Was it helpful?

Solution

FOREACH is meant for looping through the elements of an array value, not through their keys. FOR or generate_subscripts() can be used for that.

But generally, there should be no relation between the array's key and value.

OTHER TIPS

For PL/pgSQL developer looking to LOOP on an array using subscripts, you can use following kind of code. It's just a working example of pozs's answer (as I understood it).

DO $$
DECLARE
  vTab text[] := ARRAY['abc','def','ghi'];
  ind integer;
BEGIN
  FOR ind IN SELECT generate_subscripts(vTab,1)
  LOOP
    RAISE NOTICE 'element % = %', ind, vTab[ind];
  END LOOP;
END;
$$;

Result :

NOTICE:  element 1 = abc
NOTICE:  element 2 = def
NOTICE:  element 3 = ghi

For some specific purposes a raw SQL can be more elegant and sometimes faster:

postgres=# SELECT count(*) from unnest(ARRAY[1,2,3,4]);
+-------+
| count |
+-------+
|     4 |
+-------+
(1 row)

But usually FOREACH clause is optimal

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top