![]() |
VOOZH | about |
PostgreSQL provides powerful features that allow developers to pass data between a calling program and a procedure or function. This is achieved through the use of parameters, which are essential for flexible and dynamic database operations. Parameters enable you to supply data to a function or procedure and receive data back, making your database interactions more efficient and versatile.
Parameters in PostgreSQL functions and procedures are variables that pass data from the calling program to the function or procedure. There are two types of parameters:
A Parameter mode is used to decide the behavior of the parameters. PL/pgSQL supports three parameter modes: 'in', 'out', and 'inout'. By default, a parameter uses the IN mode.
The following table illustrates the three parameter mode:
| IN | OUT | INOUT |
|---|---|---|
| Taken by default | Need to be specified explicitly | Need to be specified explicitly |
| Values are passed to a function | Value is returned by a function | A value is passed to the function which returns another updated value |
| Behaves like constants | Behaves like an uninitialized variable | Behaves like an initialized variable |
| Values cannot be assigned | Must assign a value | Should assign a value |
Let us look at some of the examples of Function Parameter Modes in PostgreSQL to better understand the concept. For testing, we create a sample table using the below commands to perform examples:
The table is:
👁 Sample TableThe following function is created to find the name of the employee along with its manager id given the employee id and its manager id.
Query:
CREATE OR REPLACE FUNCTION get_stats( IN eid INT, OUT name VARCHAR, INOUT mid INT) LANGUAGE plpgsql AS $$ BEGINSELECT full_name, manager_id INTO name, mid FROM employees WHERE employee_id = eid AND manager_id = mid; END; $$;
To call this function, we need to provide employee id and then manager id. As an example,
SELECT * FROM get_stats(2,1);Output:
👁 PostgreSQL Function Parameter Modes ExampleExplanation:
The following function is used to get the count of employees in the employee table.
Query:
CREATE OR REPLACEFUNCTION empcount( OUT ecount INT) LANGUAGE plpgsql AS $$ BEGINSELECT COUNT(*) INTO ecount FROM employees; END; $$;
To call this function:
SELECT * FROM empcount();Output:
👁 PostgreSQL Function Parameter Modes ExampleExplanation: The function will return the total count of employees in the table.
The following function is used to swap the contents of 2 variables
CREATE OR REPLACE FUNCTION swapper( INOUT x INT, INOUT y INT) LANGUAGE plpgsql AS $$ BEGINSELECT x, y INTO y, x; END; $$;
To call this function :
SELECT * FROM swapper(198, 457);Output:
👁 PostgreSQL Function Parameter Modes ExampleAs we need to change the values and then display the changed values, we use INOUT mode.
Explanation: The function will return the swapped values of 'x' and 'y'.