Structure
A function or procedure that uses PL/pgSQL must specify thePLpgSQL language within the or statement:
- An optional
DECLAREsection that contains variable declarations for all variables that are used within the block and are not defined as or parameters. - A or body, consisting of statements enclosed by
BEGINandEND. - An optional
EXCEPTIONsection for catching and handlingSQLSTATEerrors.
$$). Dollar quotes are not required, but are easier to use than single quotes, which require that you escape other single quotes that are within the function or procedure body.
Syntax
Declare a variable
DECLARE specifies all variable definitions that are used in the function or procedure body.
variable_nameis an arbitrary variable name.data_typecan be a supported , , or the PL/pgSQLREFCURSORtype, when declaring cursor variables.CONSTANTspecifies that the variable cannot be reassigned, ensuring that its value remains constant within the block.expressionis an expression that provides an optional default value for the variable.
Declare cursor variables
A cursor encapsulates a selection query and is used to fetch the query results for a subset of rows. You can declare forward-only cursors as variables to be used within PL/pgSQL blocks. These must have the PL/pgSQLREFCURSOR data type. For example:
CURSOR FOR syntax and specify the query:
REFCURSOR data type.
For information about opening and using cursors, see Open and use cursors.
Assign a result to a variable
Use the PL/pgSQLINTO clause to assign a result of a or mutation (, , ) statement to a specified variable:
expressionis an expression that defines the result to be assigned to the variable.targetis an arbitrary variable name. This can be a list of comma-separated variables, or a single .
t with INT column col:
The following inserts a specified value x into the table, and the INTO clause assigns the to i.
NOTICE message that contains the inserted value:
max() to find the maximum col value in table t, and assigns the result to i.
Write conditional statements
UseIF syntax to execute statements conditionally. PL/pgSQL understands several forms of IF statements.
IF... THEN executes statements only if a boolean condition is true.
IF... THEN... ELSE executes statements if a boolean condition is true. If the condition is false, the ELSE statements are executed.
IF... THEN... ELSIF executes statements if a boolean condition is true. If the condition is false, each ELSIF condition is evaluated until one is true. The corresponding ELSIF statements are executed. If no ELSIF conditions are true, no statements are executed unless an ELSE clause is included, in which case the ELSE statements are executed.
Write loops
Use looping syntax to repeatedly execute statements. On its own,LOOP executes statements infinitely.
WHILE executes statements infinitely if a boolean condition is true. The statements repeat until the condition is false.
EXIT statement to end a LOOP or WHILE statement block. This should be combined with a conditional statement.
CONTINUE statement to end a LOOP or WHILE statement block, skipping any statements below CONTINUE, and begin the next iteration of the loop. This should be combined with a conditional statement. In the following example, if the IF condition is met, then CONTINUE causes the loop to skip the second block of statements and begin again.
Open and use cursors
PL/pgSQL cursors can be used in the following scenarios:- When declared as variables, cursors can be used within PL/pgSQL blocks.
- When specified as a parameter in a statement, cursors can be accessed externally from the stored procedure.
FOR clause.
FETCH statement to assign the result to one or more variables.
In PL/pgSQL,
FETCH returns a single row. For example, FETCH 10 returns the 10th row.FETCH statement to retrieve query results for a specified number of rows:
FETCH statements have to be issued within the same transaction, or the cursor will not be found:
Report messages and handle exceptions
Use theRAISE statement to print messages for status or error reporting.
RAISE messages the client directly, and does not currently produce log output.-
levelis the message severity. Possible values areDEBUG,LOG,NOTICE,INFO,WARNING, andEXCEPTION. SpecifyEXCEPTIONto raise an error that aborts the current transaction. -
messageis a message string to display. -
expressionsis an optional, comma-separated list of expressions that provide values to replace any%placed within the message string. The number of expressions must match the number of%placeholders. -
optionis a type of additional information to include. Possible values areMESSAGE,DETAIL,HINT, orERRCODE. To specifyMESSAGE, use the following alternate syntax: -
expressionis an expression to display that corresponds to the specifiedoption. IfERRCODEis the specified option, this must be a validSQLSTATEerror code or name.
Write exception logic
Use anEXCEPTION statement to catch and handle specified errors.
Any valid SQLSTATE error code or name can be specified, except for Class 40 (transaction rollback) errors. Arbitrary user-defined SQLSTATE codes can also be specified.
If a specified error is caught, the exception handling statements are executed. Any unspecified errors are caught by WHEN OTHERS, except for query_canceled and assert_failure.
EXCEPTION logic is included after the main body of a PL/pgSQL block. For example:
Examples
Create a user-defined function using PL/pgSQL
The following returns thenth integer in the Fibonacci sequence.
It uses the PL/pgSQL syntax to iterate through a simple calculation, and to return an error message if the specified n is negative.
Create a stored procedure using PL/pgSQL
Setup
To follow along, run to start a temporary, in-memory cluster with the sample dataset preloaded:vehicle_location_histories.
It uses the PL/pgSQL syntax to iterate through the rows, RAISE to return notice and error messages, and REFCURSOR to define a cursor that fetches the next rows to be affected by the procedure.
rides_left cursor name:
vehicle_location_histories:
Known limitations
- PL/pgSQL blocks cannot be nested.
- Cursors used in PL/pgSQL execute their queries on opening. This can affect performance and resource usage.
- Cursors cannot be declared with parameters.
RECORDandROW-type variables cannot be declared in PL/pgSQL.NOT NULLvariables cannot be declared in PL/pgSQL.- PL/pgSQL arguments cannot be referenced with ordinals (e.g.,
$1,$2). - PL/pgSQL
EXCEPTIONblocks cannot catch . FORloops (includingFORcursor loops andFORquery loops) andFOREACHloops are not supported.RETURN NEXTandRETURN QUERYstatements are not supported.CASEstatements are not supported.EXITandCONTINUElabels and conditions are not supported.- Variable shadowing (e.g., declaring a variable with the same name in an inner block) is not supported in PL/pgSQL.
- When using the
RAISEstatement, schema objects related to the error cannot be named usingCOLUMN,CONSTRAINT,DATATYPE,TABLE, andSCHEMA. - The
INTOstatement in PL/pgSQL does not support theSTRICToption. PERFORM,EXECUTE,GET DIAGNOSTICS, andNULLstatements are not supported for PL/pgSQL.

