PL/pgSQL Returns SetOf
Summary: in this tutorial, you will learn how to use the returns setof
option to define a function that returns one or more rows.
Defining a function with returns setof option
PostgreSQL functions allow you to encapsulate reusable logic within the database. To return one or more rows from a function, you can use the returns setof
option.
The returns setof
option allows you to return one or more rows with a predefined structure from a function.
Here’s the syntax for creating a function that returns a set of rows:
In this syntax:
- First, specify the function name after the
create or replace function
keywords. - Second, use the
returns setof
with a predefined row structure. The row structure can be a composite type defined in the database. - Third, return rows inside the function body using the
return query
statement followed by a select statement.
Calling the function
To call a function with the returns setof
, you use the following statement:
It’ll return a single column containing an array of all columns of the returned rows.
To retrieve data from a specific column of the return rows, you specify the dot (.) and column name after the function call:
If you want to retrieve data from all columns of the returned rows, you can use the .*
like this:
Alternatively, you can call the function using the SELECT...FROM
statement:
PL/pgSQL Returns SetOf example
We’ll use the film
table from the sample database for the demonstration.
First, define a function that retrieves a film by its id from the film
table:
Second, call the find_film_by_id()
function:
Output:
The output is an array that contains column data.
Third, retrieve the title of the film with id 100:
Output:
Fourth, retrieve the data from all columns of the returned row:
Output:
Note that we use \x
command in psql to display the result set vertically.
Summary
- Use the
returns setof
to return one or more rows from a function.