postgresql_16:6.6.3 Declarations
PostgreSQL 16 > Server Programming > PL/pgSQL — SQL Procedural Language > 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: user_id integer; quantity numeric(5); url varchar; myrow tablename%ROWTYPE; myfield tablename.columnname%TYPE; arow RECORD;
The general syntax of a variable declaration is: *name* CONSTANT *type* COLLATE *collation_name* NOT NULL { DEFAULT | := | = } *expression* ; 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 (see postgresql_16:6.6.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: quantity integer DEFAULT 32; url varchar := 'http://mysite.com'; transaction_time CONSTANT timestamp with time zone := now();
Once declared, a variable's value can be used in later initialization expressions in the same block, for example: DECLARE x integer := 1; y integer := x + 1;
Subsections
- postgresql_16:6.6.3.1 Declaring Function Parameters
- postgresql_16:6.6.3.2
ALIAS - postgresql_16:6.6.3.3 Copying Types
- postgresql_16:6.6.3.4 Row Types
- postgresql_16:6.6.3.5 Record Types
- postgresql_16:6.6.3.6 Collation of PL/pgSQL Variables