43.3. Declarations
All variables used in a block must be declared in the declarations section of the block. (The only exceptions are that the loop variable of a FOR
loop iterating over a range of integer values is automatically declared as an integer variable, and likewise the loop variable of a FOR
loop iterating over a cursor's result is automatically declared as a record variable.)
PL/pgSQL variables can have any SQL data type, such as integer
, varchar
, and char
.
Here are some examples of variable declarations:
The general syntax of a variable declaration is:
The DEFAULT
clause, if given, specifies the initial value assigned to the variable when the block is entered. If the DEFAULT
clause is not given then the variable is initialized to the SQL null value. The CONSTANT
option prevents the variable from being assigned to after initialization, so that its value will remain constant for the duration of the block. The COLLATE
option specifies a collation to use for the variable (see Section 43.3.6). If NOT NULL
is specified, an assignment of a null value results in a run-time error. All variables declared as NOT NULL
must have a nonnull default value specified. Equal (=
) can be used instead of PL/SQL-compliant :=
.
A variable's default value is evaluated and assigned to the variable each time the block is entered (not just once per function call). So, for example, assigning now()
to a variable of type timestamp
causes the variable to have the time of the current function call, not the time when the function was precompiled.
Examples:
Once declared, a variable's value can be used in later initialization expressions in the same block, for example:
43.3.1. Declaring Function Parameters
Parameters passed to functions are named with the identifiers $1
, $2
, etc. Optionally, aliases can be declared for $
n
parameter names for increased readability. Either the alias or the numeric identifier can then be used to refer to the parameter value.
There are two ways to create an alias. The preferred way is to give a name to the parameter in the CREATE FUNCTION
command, for example:
The other way is to explicitly declare an alias, using the declaration syntax
The same example in this style looks like:
Note
These two examples are not perfectly equivalent. In the first case, subtotal
could be referenced as sales_tax.subtotal
, but in the second case it could not. (Had we attached a label to the inner block, subtotal
could be qualified with that label, instead.)
Some more examples:
When a PL/pgSQL function is declared with output parameters, the output parameters are given $
n
names and optional aliases in just the same way as the normal input parameters. An output parameter is effectively a variable that starts out NULL; it should be assigned to during the execution of the function. The final value of the parameter is what is returned. For instance, the sales-tax example could also be done this way:
Notice that we omitted RETURNS real
— we could have included it, but it would be redundant.
To call a function with OUT
parameters, omit the output parameter(s) in the function call:
Output parameters are most useful when returning multiple values. A trivial example is:
As discussed in Section 38.5.4, this effectively creates an anonymous record type for the function's results. If a RETURNS
clause is given, it must say RETURNS record
.
This also works with procedures, for example:
In a call to a procedure, all the parameters must be specified. For output parameters, NULL
may be specified when calling the procedure from plain SQL:
However, when calling a procedure from PL/pgSQL, you should instead write a variable for any output parameter; the variable will receive the result of the call. See Section 43.6.3 for details.
Another way to declare a PL/pgSQL function is with RETURNS TABLE
, for example:
This is exactly equivalent to declaring one or more OUT
parameters and specifying RETURNS SETOF
sometype
.
When the return type of a PL/pgSQL function is declared as a polymorphic type (see Section 38.2.5), a special parameter $0
is created. Its data type is the actual return type of the function, as deduced from the actual input types. This allows the function to access its actual return type as shown in Section 43.3.3. $0
is initialized to null and can be modified by the function, so it can be used to hold the return value if desired, though that is not required. $0
can also be given an alias. For example, this function works on any data type that has a +
operator:
The same effect can be obtained by declaring one or more output parameters as polymorphic types. In this case the special $0
parameter is not used; the output parameters themselves serve the same purpose. For example:
In practice it might be more useful to declare a polymorphic function using the anycompatible
family of types, so that automatic promotion of the input arguments to a common type will occur. For example:
With this example, a call such as
will work, automatically promoting the integer inputs to numeric. The function using anyelement
would require you to cast the three inputs to the same type manually.
43.3.2. ALIAS
ALIAS
The ALIAS
syntax is more general than is suggested in the previous section: you can declare an alias for any variable, not just function parameters. The main practical use for this is to assign a different name for variables with predetermined names, such as NEW
or OLD
within a trigger function.
Examples:
Since ALIAS
creates two different ways to name the same object, unrestricted use can be confusing. It's best to use it only for the purpose of overriding predetermined names.
43.3.3. Copying Types
%TYPE
provides the data type of a variable or table column. You can use this to declare variables that will hold database values. For example, let's say you have a column named user_id
in your users
table. To declare a variable with the same data type as users.user_id
you write:
By using %TYPE
you don't need to know the data type of the structure you are referencing, and most importantly, if the data type of the referenced item changes in the future (for instance: you change the type of user_id
from integer
to real
), you might not need to change your function definition.
%TYPE
is particularly valuable in polymorphic functions, since the data types needed for internal variables can change from one call to the next. Appropriate variables can be created by applying %TYPE
to the function's arguments or result placeholders.
43.3.4. Row Types
A variable of a composite type is called a row variable (or row-type variable). Such a variable can hold a whole row of a SELECT
or FOR
query result, so long as that query's column set matches the declared type of the variable. The individual fields of the row value are accessed using the usual dot notation, for example rowvar.field
.
A row variable can be declared to have the same type as the rows of an existing table or view, by using the table_name
%ROWTYPE
notation; or it can be declared by giving a composite type's name. (Since every table has an associated composite type of the same name, it actually does not matter in PostgreSQL whether you write %ROWTYPE
or not. But the form with %ROWTYPE
is more portable.)
Parameters to a function can be composite types (complete table rows). In that case, the corresponding identifier $
n
will be a row variable, and fields can be selected from it, for example $1.user_id
.
Here is an example of using composite types. table1
and table2
are existing tables having at least the mentioned fields: