PL/pgSQL Declaration
Introduction
All variables must be declared in the declarations section of the block (marked in red color).
Version: 9.3
Syntax:
[ <<label>> ] [ DECLARE declarations ] BEGIN statements END [ label ];
Note: 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.
The types of PL/pgSQL variables are similar to SQL data types, such as integer, varchar, and char.
Examples:
roll_no integer; qty numeric(5); description varchar; myrow tablename%ROWTYPE; myfield tablename.columnname%TYPE; arow RECORD;
Here is the general syntax of a variable declaration:
Syntax:
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. A variable's default value is evaluated and assigned to the variable each time the block is entered.
Examples:
qty integer DEFAULT 1; roll_no CONSTANT integer := 10; url varchar := 'http://example.com';
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. The preferred way is to give a name to the parameter in the CREATE FUNCTION command, for example :
Code:
CREATE FUNCTION sum_of_two_numbers(m integer, n integer)
RETURNS integer AS $$
BEGIN
RETURN m + n;
END;
$$ LANGUAGE plpgsql;
Here is another example:
Code:
CREATE FUNCTION FUN_TO_TEST () RETURNS double precision
AS $TEST$
BEGIN
RETURN 4.295806896E-29;
END;
$TEST$ LANGUAGE PLPGSQL
Here is the same function whose body is delimited by single quotes:
Code:
CREATE FUNCTION FUN_TO_TEST ()
RETURNS double precision AS '
BEGIN
RETURN 4.295806896E-29;
END;
'
LANGUAGE PLPGSQL
Here is another one which will make you understand that the usage of the apostrophe as a delimiter of the body is not the best solution:
Code:
CREATE FUNCTION TODAY_IS () RETURNS CHAR(22) AS '
BEGIN
RETURN ''Today''''is '' || CAST(CURRENT_DATE AS CHAR(10));
END;
'
LANGUAGE PLPGSQL
ALIAS
The ALIAS is used to assign a different name for variables with predetermined names, such as NEW or OLD within a trigger procedure. Here is the syntax :
Code:
newname ALIAS FOR oldname;
Examples:
Code:
CREATE FUNCTION FUN_TO_TEST(dt DATE, ing INTEGER)
RETURNS DATE AS $test$
DECLARE ss ALIAS FOR dt;
ff ALIAS FOR ing;
BEGIN
RETURN ss + ff * INTERVAL '2 DAY';
END;
$test$
LANGUAGE PLPGSQL
The above function returns the date passed as the number of days added to ing desired argument.
In the following example you can use the $ and the positron of the variable passed in the argument instead of the new variable name with an alias.
Code:
CREATE FUNCTION FUN_TO_TEST(dt DATE, ing INTEGER)
RETURNS DATE AS $test$
DECLARE ss ALIAS FOR $1;
ff ALIAS FOR $2;
BEGIN
RETURN ss + ff * INTERVAL '2 DAY';
END;
$test$
LANGUAGE PLPGSQL
Variable Types
%TYPE is used to get the data type of a variable or table column. In the following example roll_no is a column in student table. To declare a variable with the same data type as student.roll_no you should write:
Syntax:
variable_name table_name.column_name%TYPE
Examples:
Code:
DECLARE
roll_no student.roll_no%TYPE;
Here is another Example:
Code:
CREATE FUNCTION get_employee(text) RETURNS text AS '
DECLARE
frst_name ALIAS FOR $1;
lst_name employees.last_name%TYPE;
BEGIN
SELECT INTO lst_name last_name FROM employees
WHERE first_name = frst_name;
return frst_name || '' '' || lst_name;
END;
' LANGUAGE 'plpgsql';
Here in the above example, an alias has been declared for the function argument which should be the first name of an employee and a variable with the same type as the last_name field of the employees table.
This statement retrieves the last name of an employee from the employees table whose first name matches the argument received by the function, and insert it into the lst_name variable and return the first name and last name, separated by a space.
Here are the results of using the get_employee() function.
postgres=# SELECT get_employee('John'); get_first_name ---------------- John Chen (1 row)
Row Types
A variable of a composite type is called a row variable which 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.
name table_name%ROWTYPE; name composite_type_name;
The individual fields of the row value are accessed using the usual dot notation, for example, rowvar.table_field. The fields of the row type inherit the table's field size or precision for data types such as char(n). See the following example:
Code:
CREATE FUNCTION get_employee (integer) RETURNS text AS '
DECLARE
emp_id ALIAS FOR $1;
found_employee employees%ROWTYPE;
BEGIN
SELECT INTO found_employee * FROM employees WHERE employee_id = emp_id;
RETURN found_employee.first_name || '' '' || found_employee.last_name;
END;
' LANGUAGE 'plpgsql';
The above PL/pgSQL shows an alias for the function argument have been declared, which should be the id of the employee and a variable found_employee that uses the structure of the employees table have also been declared. A row is being retrieve of employee information for the employee whose id number matches the argument received by the function.
Here are the results of using the get_employee() function.
postgres=# SELECT get_employee(108); get_employee ----------------- Nancy Greenberg (1 row)
Record Types
Record variables are similar to row-type variables, but they have no predefined structure. They take on the actual row structure of the row they are assigned during a SELECT or FOR command. The substructure of a record variable can change each time it is assigned to. RECORD is not a true data type, only a placeholder, when a PL/pgSQL function is declared to return type record, this is not quite the same concept as a record variable.
Syntax:
name RECORD;
Example:
Code:
CREATE FUNCTION get_employee (integer) RETURNS text AS '
DECLARE
emp_id ALIAS FOR $1;
found_employee RECORD;
BEGIN
SELECT INTO found_employee * FROM employees WHERE employee_id = emp_id;
RETURN found_employee.first_name || '' '' || found_employee.last_name;
END;
' LANGUAGE 'plpgsql';
Collation of PL/pgSQL Variables
When a PL/pgSQL function has one or more parameters of collatable data types, a collation is identified for each function call depending on the collations assigned to the actual arguments, as described in Section 22.2. If a collation is successfully identified (i.e., there are no conflicts of implicit collations among the arguments) then all the collatable parameters are treated as having that collation implicitly. This will affect the behavior of collation-sensitive operations within the function. For example, consider
Here is the sample table 'jobs '
job_id | job_title | min_salary | max_salary ------------+---------------------------------+------------+------------ AD_PRES | President | 20000 | 40000 AD_VP | Administration Vice President | 15000 | 30000 AD_ASST | Administration Assistant | 3000 | 6000 FI_MGR | Finance Manager | 8200 | 16000 FI_ACCOUNT | Accountant | 4200 | 9000 AC_MGR | Accounting Manager | 8200 | 16000 AC_ACCOUNT | Public Accountant | 4200 | 9000 SA_MAN | Sales Manager | 10000 | 20000 SA_REP | Sales Representative | 6000 | 12000 PU_MAN | Purchasing Manager | 8000 | 15000 PU_CLERK | Purchasing Clerk | 2500 | 5500 ST_MAN | Stock Manager | 5500 | 8500 ST_CLERK | Stock Clerk | 2000 | 5000 SH_CLERK | Shipping Clerk | 2500 | 5500 IT_PROG | Programmer | 4000 | 10000 MK_MAN | Marketing Manager | 9000 | 15000 MK_REP | Marketing Representative | 4000 | 9000 HR_REP | Human Resources Representative | 4000 | 9000 PR_REP | Public Relations Representative | 4500 | 10500
Here is the example
Code:
CREATE FUNCTION not_equal(maxa decimal, minb decimal)
RETURNS boolean AS $$
BEGIN
RETURN maxa <> minb;
END;
$$ LANGUAGE plpgsql;
Here is the results of using the not_equal() function.
postgres=# SELECT not_equal(max_salary, min_salary) FROM jobs; not_equal ----------- t t t t t t t t t t t t t t t t t t t (19 rows)
The use of not_equal will use the common collation of maxa and minb for the comparison, while the use of C collation which is not support in integer data type. Furthermore, the identified collation is also assumed as the collation of any local variables that are of collatable types.
Here is another example:
Code:
CREATE FUNCTION not_equal(fstnm text, lstnm text)
RETURNS boolean AS $$
BEGIN
RETURN fstnm <> lstnm;
END;
$$ LANGUAGE plpgsql;
Now see the usage of C collation.
postgres=# SELECT not_equal(first_name, last_name COLLATE "C") FROM employees; not_equal ----------- t t t t t t t t t .. ..
Here is another example:
Code:
CREATE FUNCTION not_equal(fst_number integer, snd_number integer)
RETURNS boolean AS $$
DECLARE
fstnum integer := fst_number;
sndname integer:= snd_number;
BEGIN
RETURN fstnum<> sndname;
END;
$$ LANGUAGE plpgsql;
Now see the example of not_equal()
postgres=# SELECT not_equal(15, 20);
If there are no parameters of collatable data types, or no common collation can be identified for them, then parameters and local variables use the default collation of their data type (which is usually the database's default collation, but could be different for variables of domain types). A local variable of a collatable data type can have a different collation associated with it by including the COLLATE option in its declaration, for example
Code:
DECLARE
local_a text COLLATE "en_US";
This option overrides the collation that would otherwise be given to the variable according to the rules above. Also, of course, explicit COLLATE clauses can be written inside a function if it is desired to force a particular collation to be used in a particular operation. For example,
Code:
CREATE FUNCTION get_employee(fstnm text, lstnm text)
RETURNS boolean AS $$
BEGIN
RETURN fstnm < lstnm COLLATE "C";
END;
$$ LANGUAGE plpgsql;
Now see the example of get_employee()
postgres=# SELECT get_employee(first_name, last_name COLLATE "C") FROM employees; get_employee -------------- f f f t t f f .. ..
Next:
- Basic Statements
- Control Structures
Previous: Introduction to plpgSQL
Next: Basic Statements
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/PostgreSQL/pl-pgsql-declarations.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics