Introduction
FOREACH helps you look at each item in a list one by one inside a database function. It makes working with lists easy without writing complex loops.
Jump into concepts and practice - no test required
FOREACH element_variable IN ARRAY array_variable LOOP -- statements using element_variable END LOOP;
DECLARE
current_number integer;
numbers integer[] := ARRAY[1, 2, 3];
BEGIN
FOREACH current_number IN ARRAY numbers LOOP
RAISE NOTICE 'Number: %', current_number;
END LOOP;
END;DECLARE
current_text text;
texts text[] := ARRAY['apple', 'banana', 'cherry'];
BEGIN
FOREACH current_text IN ARRAY texts LOOP
RAISE NOTICE 'Fruit: %', current_text;
END LOOP;
END;DECLARE
current_item integer;
empty_array integer[] := ARRAY[]::integer[];
BEGIN
FOREACH current_item IN ARRAY empty_array LOOP
RAISE NOTICE 'This will not print';
END LOOP;
END;DO $$
DECLARE
current_value integer;
sample_array integer[] := ARRAY[10, 20, 30, 40];
BEGIN
RAISE NOTICE 'Array before loop: %', sample_array;
FOREACH current_value IN ARRAY sample_array LOOP
RAISE NOTICE 'Current value: %', current_value;
END LOOP;
END $$;FOREACH statement in PostgreSQL when working with arrays?arr using FOREACH in PL/pgSQL?DECLARE
arr integer[] := ARRAY[2, 4, 6];
sum integer := 0;
BEGIN
FOREACH val IN ARRAY arr LOOP
sum := sum + val;
END LOOP;
RAISE NOTICE '%', sum;
END;DECLARE
arr text[] := ARRAY['a', 'b', 'c'];
ch text;
BEGIN
FOREACH ch IN arr LOOP
RAISE NOTICE '%', ch;
END LOOP;
END;FOREACH. Which of the following code snippets correctly implements this?