PL/pgSQL Block Structure
Summary : in this tutorial, you will learn about the block structure of PL/pgSQL and how to write and execute your first PL/pgSQL block.
Introduction to PL/pgSQL Block Structure
PL/pgSQL is a block-structured language. Here’s the syntax of a block in PL/pgSQL:
Each block has two sections:
The declaration section is optional whereas the body section is required.
A block may have an optional
label
that is located at the beginning and end of the block. A block ends with a semicolon (
;
) after the
end
keyword.
Typically, you use the block label when you want to specify it in the
EXIT
statement of the block body or to qualify the names of
variables
declared in the block.
The declaration section is where you
declare all variables
used within the body section. Each statement in the declaration section is terminated with a semicolon (
;
).
The syntax for declaring a variable is as follows:
For example, the following declares a variable called
counter
with the type
int
and has an initial value of zero:
Sometimes, you’ll see the := operator instead of = operator. They are have the same meaning:
The initial value is optional. For example, you can declare a variable called
max
with the type
int
like this:
Please note that you’ll learn about variables in more detail in the upcoming variable tutorial .
The body section is where you place the code. Each statement in the body section is terminated with a semicolon (;).
PL/pgSQL block structure example
The following example illustrates a simple block. Because the block has no name, it is called an anonymous block.
Output: