Iterating over integer[] in PL/pgSQL
DO$do$DECLARE a integer[] := array[1,2,3]; i integer; -- int, not bigintBEGIN FOR i IN 1 .. array_upper(a, 1) LOOP RAISE NOTICE '%', a[i]; -- single quotes END LOOP;END$do$;
Or simpler with FOREACH
in PostgreSQL 9.1 or later:
FOREACH i IN ARRAY a LOOP RAISE NOTICE '%', i; END LOOP;
For multi-dimensional arrays see:
However, set-based solutions with generate_series()
or unnest()
are often faster than looping over big sets. Basic examples:
Search the tags generate-series or unnest for more.