PL/pgSQL For Loop
Summary: in this tutorial, you will learn about PL/pgSQL for
loop statements to iterate over a range of integers or a result set of a query.
Using PL/pgSQL for loop to iterate over a range of integers
The following illustrates the syntax of the for
loop statement that iterates over integers of a range:
In this syntax:
- First, the
for
loop creates an integer variableloop_counter
which is accessible only inside the loop. By default, thefor
loop increases theloop_counter
bystep
after each iteration. However, when you use thereverse
option, thefor
loop decreases theloop_counter
by thestep
. - Second, the
from
andto
are expressions that specify the lower and upper bound of the range. Thefor
loop evaluates these expressions before entering the loop. - Third, the
step
that follows theby
keyword specifies the iteration step. It is optional and defaults to 1. Thefor loop
evaluates thestep
expression once only.
The following flowchart illustrates the for
loop statement:
The following example uses the for
loop statement to iterate over five numbers from 1 to 5 and display each of them in each iteration:
Output:
The following example iterates over 5 numbers from 5 to 1 and shows each of them in each iteration:
Output:
The following example uses the for
loop statement to iterate over six numbers from 1 to 6. It adds 2 to the counter after each iteration:
Output:
Using PL/pgSQL for loop to iterate over a result set
The following statement shows how to use the for
loop statement to iterate over a result set of a query:
The following statement uses the for
loop to display the titles of the top 10 longest films.
Using PL/pgSQL for loop to iterate over the result set of a dynamic query
The following form of the for
loop statement allows you to execute a dynamic query and iterate over its result set:
In this syntax:
- The
query_expression
is an SQL statement. - The
using
clause is used to pass parameters to the query.
The following block shows how to use the for
loop statement to loop through a dynamic query. It has two configuration variables:
sort_type
: 1 to sort the films by title, 2 to sort the films by release year.rec_count
: is the number of rows to query from thefilm
table. We’ll use it in theusing
clause of thefor
loop.
This anonymous block composes the query based on the sort_type
variable and uses the for loop to iterate over the row of the result set.
Output:
If you change the sort_type
to 2, you’ll get the following output:
In this tutorial, you have learned various forms of the PL/pgSQL for loop statements