The next type of loop widely used in Postgres is the FOR
loop.
A FOR
loop iterates a specified number of times. The lower and upper bound of the range are evaluated once when entering the loop.
Below are some examples of integer FOR
loops:
FOR i IN 1..10 LOOP
/* i will take on the values:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
within the loop */
END LOOP;
If the REVERSE
keyword is specified, then the step value is subtracted, rather than added, after each iteration.
FOR i IN REVERSE 10..1 LOOP
/* i will take on the values:
10, 9, 8, 7, 6, 5, 4, 3, 2, 1
within the loop */
END LOOP;
The iteration step is 1 by default or the value (if any) specified in the BY
clause.
FOR i IN REVERSE 10..1 BY 2 LOOP
/* i will take on the values:
10, 8, 6, 4, 2
within the loop */
END LOOP;