This section is from the "Practical PostgreSQL" book, by John Worsley and Joshua Drake. Also available from Amazon: Practical PostgreSQL.
A special FOR loop is provided to iterate through records. It is defined to iterate through the results of a SELECT statement and give the ability to manipulate the data. The syntax for the FOR loop is:
FOR RECORD | row IN select_statement LOOP statements; END LOOP;
When the FOR loop is executed, the statements in the loop body is executed for each record or row in the SELECT statement result.
Another way to iterate over records or rows is through the FOR IN EXECUTE command. The syntax is:
FOR record | row IN EXECUTE text_expression LOOP statements END LOOP;
![]() | FOR IN SELECT & EXECUTE Difference |
---|---|
The difference between SELECT and EXECUTE in a FOR loop is that the FOR IN EXECUTE specifies the SELECT statement as a string expression. It is re-planned for each entry into the FOR loop. This functionality allows the programmer to have more flexibility. |
 
Continue to: