September 4, 2025: PostgreSQL 18 RC 1 Released!
Supported Versions: Current (17) / 16 / 15 / 14 / 13
Development Versions: 18 / devel
Unsupported versions: 12 / 11 / 10 / 9.6 / 9.5 / 9.4 / 9.3 / 9.2 / 9.1 / 9.0 / 8.4 / 8.3 / 8.2 / 8.1 / 8.0 / 7.4 / 7.3 / 7.2
This documentation is for an unsupported version of PostgreSQL.
You may want to view the same page for the current version, or one of the other supported versions listed above instead.
PostgreSQL 7.3.21 Documentation
Prev Chapter 19. PL/pgSQL - SQL Procedural Language Next

19.2. Structure of PL/pgSQL

PL/pgSQL is a block structured language. The complete text of a function definition must be a block. A block is defined as:

[ <<label>> ]
[ DECLARE
 declarations ]
BEGIN
 statements
END;

Any statement in the statement section of a block can be a sub-block. Sub-blocks can be used for logical grouping or to localize variables to a small group of statements.

The variables declared in the declarations section preceding a block are initialized to their default values every time the block is entered, not only once per function call. For example:

CREATE FUNCTION somefunc() RETURNS INTEGER AS '
DECLARE
 quantity INTEGER := 30;
BEGIN
 RAISE NOTICE ''Quantity here is %'',quantity; -- Quantity here is 30
 quantity := 50;
 --
 -- Create a sub-block
 --
 DECLARE
 quantity INTEGER := 80;
 BEGIN
 RAISE NOTICE ''Quantity here is %'',quantity; -- Quantity here is 80
 END;
 RAISE NOTICE ''Quantity here is %'',quantity; -- Quantity here is 50
 RETURN quantity;
END;
' LANGUAGE 'plpgsql';

It is important not to confuse the use of BEGIN/END for grouping statements in PL/pgSQL with the database commands for transaction control. PL/pgSQL's BEGIN/END are only for grouping; they do not start or end a transaction. Functions and trigger procedures are always executed within a transaction established by an outer query --- they cannot start or commit transactions, since PostgreSQL does not have nested transactions.

19.2.1. Lexical Details

Each statement and declaration within a block is terminated by a semicolon.

All keywords and identifiers can be written in mixed upper- and lower-case. Identifiers are implicitly converted to lower-case unless double-quoted.

There are two types of comments in PL/pgSQL. A double dash -- starts a comment that extends to the end of the line. A /* starts a block comment that extends to the next occurrence of */. Block comments cannot be nested, but double dash comments can be enclosed into a block comment and a double dash can hide the block comment delimiters /* and */.


Prev Home Next
PL/pgSQL - SQL Procedural Language Up Declarations

AltStyle によって変換されたページ (->オリジナル) /