PL/pgSQL Function Parameter Modes: IN, OUT, INOUT
Summary: in this tutorial, you will learn about parameter modes of functions including: in
, out
, and inout
.
Introduction to PL/pgSQL parameter modes
The parameter modes determine the behaviors of parameters. PL/pgSQL supports three parameter modes: in
, out
, and inout
. A parameter takes the in
mode by default if you do not explicitly specify it.
The following table illustrates the parameter modes:
IN | OUT | INOUT |
---|---|---|
The default | Explicitly specified | Explicitly specified |
Pass a value to function | Return a value from a function | Pass a value to a function and return an updated value. |
in parameters act like constants | out parameters act like uninitialized variables | inout parameters act like initialized variables |
Cannot be assigned a value | Must assign a value | Should be assigned a value |
The IN mode
The following function finds a film by its id and returns the title of the film:
Because we don’t specify the mode for p_film_id
parameter, it takes the in
mode by default.
The following shows how to call the find_film_by_id() function to find the title of the film with the id 100:
Output:
The OUT mode
The out
parameters are defined as a part of the argument list and are returned as a part of the result.
The out
parameters are very useful in functions that need to return multiple values.
Note that PostgreSQL has supported the out
parameters since version 8.1.
To define out
parameters, you explicitly precede the parameter name with the out
keyword as follows:
The following example defines the get_film_stat
function that has three out
parameters:
In the get_film_stat
function, we select the min, max, and average film length from the film
table using the min
, max
, and avg
aggregate functions and assign the results to the corresponding out
parameters.
The following statement calls the get_film_stat
function:
Output:
The output of the function is a record. To make the output separated as columns, you use the following statement:
Output:
The INOUT mode
The inout
mode is the combination in
and out
modes.
It means that the caller can pass an argument to a function. The function changes the argument and returns the updated value.
The following swap
function accepts two integers and swap their values:
The following statement calls the swap()
function:
Output:
Summary
- PL/pgSQL supports three parameter modes:
in
,out
, andintout
. By default, a parameter takes thein
mode. - Use the
in
mode if you want to pass a value to the function. - Use the
out
mode if you want to return a value from a function. - Use the
inout
mode when you want to pass in an initial value, update the value in the function, and return its updated value.