The WHILE statement keeps executing a block of statements while a particular condition is met. Its syntax is as follows:
[ <<label>> ]
WHILE boolean-expression LOOP
statements
END LOOP [ label ];
The following example uses the while loop to print the days of the current month:
DO $$
DECLARE
first_day_in_month date := date_trunc('month', current_date)::date;
last_day_in_month date := (date_trunc('month', current_date)+ INTERVAL '1 MONTH - 1 day')::date;
counter date = first_day_in_month;
BEGIN
WHILE (counter <= last_day_in_month) LOOP
RAISE notice '%', counter;
counter := counter + interval '1 day';
END LOOP;
END;
$$ LANGUAGE plpgsql;