PL pgSQL Declaration

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

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 :

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 :

  1. CREATE FUNCTION sum_of_two_numbers(m integer, n integer)   
  2. RETURNS integer AS $$  
  3.         BEGIN  
  4.                 RETURN m + n;  
  5.         END;  
  6. $$ LANGUAGE plpgsql;  

Here is another example :

  1. CREATE FUNCTION FUN_TO_TEST () RETURNS double precision   
  2. AS $TEST$   
  3. BEGIN   
  4.    RETURN 4.295806896E-29;   
  5. END;      
  6. $TEST$  LANGUAGE PLPGSQL  

Here is the same function whose body is delimited by single quotes :

  1. CREATE FUNCTION FUN_TO_TEST ()   
  2. RETURNS double precision AS '   
  3. BEGIN   
  4. RETURN 4.295806896E-29;   
  5. END;      
  6. '    
  7. 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 :

  1. CREATE FUNCTION TODAY_IS () RETURNS CHAR(22) AS  '   
  2. BEGIN   
  3.   RETURN ''Today''''is '' || CAST(CURRENT_DATE AS CHAR(10));   
  4. END;   
  5. '   
  6. 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 :

  1. newname ALIAS FOR oldname;  

Examples :

  1. CREATE FUNCTION FUN_TO_TEST(dt DATE, ing INTEGER)   
  2. RETURNS DATE AS $test$    
  3. DECLARE ss     ALIAS FOR dt;    
  4.         ff     ALIAS FOR ing;   
  5. BEGIN    
  6.    RETURN ss + ff * INTERVAL '2 DAY';    
  7. END;    
  8. $test$    
  9. 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.

  1. CREATE FUNCTION FUN_TO_TEST(dt DATE, ing INTEGER)   
  2. RETURNS DATE AS $test$    
  3. DECLARE ss     ALIAS FOR $1;    
  4.         ff     ALIAS FOR $2;   
  5. BEGIN    
  6.    RETURN ss + ff * INTERVAL '2 DAY';    
  7. END;    
  8. $test$    
  9. 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 :

  1. DECLARE  
  2. roll_no student.roll_no%TYPE;  

Here is another Example:

  1. CREATE FUNCTION get_employee(text) RETURNS text AS '  
  2.   DECLARE  
  3.      frst_name ALIAS FOR $1;  
  4.      lst_name employees.last_name%TYPE;  
  5.   BEGIN  
  6.      SELECT INTO lst_name last_name FROM employees   
  7.      WHERE first_name = frst_name;  
  8.      return frst_name || '' '' || lst_name;  
  9.   END;  
  10. ' 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:

  1. CREATE FUNCTION get_employee (integerRETURNS text AS '  
  2.   DECLARE  
  3.     emp_id ALIAS FOR $1;  
  4.     found_employee employees%ROWTYPE;  
  5.   BEGIN  
  6.    SELECT INTO found_employee * FROM employees WHERE employee_id = emp_id;  
  7.     RETURN found_employee.first_name || '' '' || found_employee.last_name;  
  8.   END;  
  9. ' 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 :

  1. CREATE FUNCTION get_employee (integerRETURNS text AS '  
  2.   DECLARE  
  3.     emp_id ALIAS FOR $1;  
  4.     found_employee RECORD;  
  5.   BEGIN  
  6.    SELECT INTO found_employee * FROM employees WHERE employee_id = emp_id;  
  7.     RETURN found_employee.first_name || '' '' || found_employee.last_name;  
  8.   END;  
  9. ' 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

  1. CREATE FUNCTION not_equal(maxa decimal, minb decimal)   
  2. RETURNS boolean AS $$  
  3. BEGIN  
  4.     RETURN maxa <> minb;  
  5. END;  
  6. $$ 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:

  1. CREATE FUNCTION not_equal(fstnm text, lstnm text)   
  2. RETURNS boolean AS $$  
  3. BEGIN  
  4.     RETURN fstnm <> lstnm;  
  5. END;  
  6. $$ 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:

  1. CREATE FUNCTION not_equal(fst_number integer, snd_number integer)   
  2. RETURNS boolean AS $$  
  3. DECLARE  
  4.     fstnum integer := fst_number;  
  5.     sndname integer:= snd_number;  
  6. BEGIN  
  7.     RETURN fstnum<> sndname;  
  8. END;  
  9. $$ 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

  1. DECLARE  
  2.     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,

  1. CREATE FUNCTION get_employee(fstnm text, lstnm text)   
  2. RETURNS boolean AS $$  
  3. BEGIN  
  4.     RETURN fstnm < lstnm COLLATE "C";  
  5. END;  
  6. $$ 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
 ..
 ..