Plpgsql if statements, arrays and loops

An if statement begins with IF condition THEN and ends with END IF;.

IF name = 'chris' THEN
  raise notice 'you are called chris';
ELSE
  raise notice 'you are not called chris';
END IF;

An array is declared with [] and can be initialized using a string with curly braces {"a", "b"}'. If you have another item, or another array, || lets you concatenate them.

my_array[] := '{"one", "two", "three"}'

You can loop over this array with FOREACH. You name your item, write IN ARRAY, then name your array. Then you surround your code with LOOP and END LOOP;. You must declare a variable for your foreach variable beforehand.

FOREACH item IN ARRAY my_array
LOOP
  raise notice '%', item; 
END LOOP;
postgresql

Edit on github
comments powered by Disqus
Click me