In parts 1 and 2 of this series (see here and here), I described many of the (otherwise under-documented) features of the PL/pgSQL FOR loop.  In this last installment, I’ll show you how to loop over things you may not have realized that you could loop over (my high-school grammar teacher is very offended at that last sentence, sorry).

Continue Reading »

In the first part of this series (see here), I discussed the integer-based FOR loop and described some of the nitty-gritty details that you really should know to ensure that your code works properly in a world festering with NULL values.

I promised that part 2 (this article) would describe how to loop through the result sets produced a SELECT, INSERT, and UPDATE statements (along with a few oddities).

I lied.

Part 2 will instead provide a mini-reference (or perhaps, a supplement to the official documentation) for the query-based FOR loop, the cursor-based FOR loop, and the EXECUTE-based FOR loop.

Part 3 (which is already here) will discuss what I had originally planned to cover in part 2 – looping through SELECT, INSERT, UPDATE, DELETE, and other utility commands.

Continue Reading »

The FOR loop is one of 10 control-of-flow statements in PL/pgSQL (the others being IF, CASE, LOOP, WHILE, EXIT, CONTINUE, BREAK, RETURN, and RAISE). Most of us are familiar with two or three of the most common ways to write a FOR loop, but few of use have explored all of the subtleties of this humble statement.

Continue Reading »


Get every new post delivered to your Inbox.