PL/pgSQL Exit Statement
Summary: in this tutorial, you will learn about the PL/pgSQL exit
statement and how to use it to terminate a loop or exit a block.
Introduction to the PL/pgSQL exit statement
The exit
statement allows you to prematurely terminate a loop including an unconditional loop, a while loop, and a for loop.
The following shows the syntax of the exit
statement:
In this syntax:
- The
label
is the loop label of the current loop where theexit
is in or the loop label of the outer loop. Depending on the label, theexit
statement will terminate the corresponding loop. If you don’t use the label, theexit
statement will terminate the enclosing loop. - Use the
when boolean_expression
clause to specify a condition that terminates a loop. Theexit
statement will terminate the loop if theboolean_expression
evaluates totrue
.
The following statements are equivalent:
The exit when
is cleaner and shorter.
Besides terminating a loop, you can use the exit
statement to exit a block specified by the begin...end
keywords.
In this case, the control is passed to the statement after the end
keyword of the current block:
PL/pgSQL Exit statement examples
Let’s take some examples of using the PL/pgSQL exit
statement.
1) Using PL/pgSQL Exit statement to terminate an unconditional loop
The following example illustrates how to use the exit
statement in unconditional loops:
Output:
How it works.
This example contains two loops: outer and inner loops.
Since both exit
statements don’t use any loop labels, they will terminate the current loop.
The first exit
statement terminates the outer loop when i
is greater than 3
. That’s why you see the value of i
in the output is 1
, 2
, and 3
.
The second exit
statement terminates the inner loop when j
is greater than 3
. It is the reason you see that j
is 1
, 2
, and 3
for each iteration of the outer loop.
The following example places the label of the outer loop in the second exit
statement:
Output:
In this example, the second exit
statement terminates the outer loop when j
is greater than 3.
2) Using the PL/pgSQL Exit statement to exit a block
The following example illustrates how to use the exit
statement to terminate a block:
Output
In this example, the exit statement terminates the simple_block
immediately:
This statement will never be reached:
Summary
- Use the
exit
statement to terminate a loop including an unconditionalloop
,while
, andfor
loop. - Use the
exit
statement to exit a block.