PostgreSQL – Function Returning A Table
In PostgreSQL, the ability to create functions that return tables enhances the power and flexibility of our database operations. These PostgreSQL RETURN TABLE functions allow us to execute complex queries and return structured data efficiently.
In this article, we will explain the PostgreSQL function syntax and demonstrate how to define and utilize functions that give tabular results, streamlining our data management tasks.
What is a Function Returning a Table in PostgreSQL?
A function that returns a table in PostgreSQL allows users to encapsulate logic in a reusable manner while outputting a set of records. This can be particularly useful when dealing with complex data queries that require multiple steps or when we need to pass parameters to filter results. By utilizing these functions, developers can streamline data retrieval and enhance the efficiency of their database operations.
Creating a Function to Return Films Based on Title Pattern
Let’s start with a basic example. The following function returns all films whose titles match a specific pattern using the ILIKE
operator, which performs a case-insensitive search. This approach enables users to easily find relevant films without needing to know the exact title.
Query:
CREATE OR REPLACE FUNCTION get_film (p_pattern VARCHAR)
RETURNS TABLE (
film_title VARCHAR,
film_release_year INT
)
AS $$
BEGIN
RETURN QUERY
SELECT
title,
CAST( release_year AS INTEGER)
FROM
film
WHERE
title ILIKE p_pattern ;
END; $$
LANGUAGE 'plpgsql';
Explanation:
In the function, we return a query that is a result of a SELECT statement. Notice that the columns in the SELECT statement must match with the columns of the table that we want to return. Because the data type of ‘release_yearof’ the film table is not an integer, we have to convert it into an integer using CAST.
Testing the Function
We called the ‘get_film(varchar)’ function to get all films whose title starts with Al. We can test the function using the following statement. This will allow us to see the filtered results based on the specified pattern.
SELECT * FROM get_film('Al%');
Output
PostgreSQL returns a table with one column that holds the array of films. Notice that if we call the function using below query.
Query:
SELECT get_film ('Al%');.
Output
Creating a Function with Multiple Parameters
In real-world scenarios, we often need to filter results based on multiple criteria. Let’s create a function that accepts both a title pattern and a release year. This approach enables users to easily find relevant films without knowing the exact title.
Query:
CREATE OR REPLACE FUNCTION get_film (p_pattern VARCHAR, p_year INT)
RETURNS TABLE (
film_title VARCHAR,
film_release_year INT
) AS $$
DECLARE
var_r record;
BEGIN
FOR var_r IN(
SELECT
title,
release_year
FROM
film
WHERE
title ILIKE p_pattern AND
release_year = p_year)
LOOP
film_title := upper(var_r.title) ;
film_release_year := var_r.release_year;
RETURN NEXT;
END LOOP;
END; $$
LANGUAGE 'plpgsql';
Explanation:
- Multiple Parameters: This function, also named
get_film
, accepts two parameters:p_pattern
andp_year
. - Looping through Results: The function uses a
FOR
loop to iterate through the results of theSELECT
statement. - RETURN NEXT: This statement adds each row to the result set as the loop iterates.
Testing the Function with Multiple Parameters
This command will return a list of films that match the specified title pattern and release year, demonstrating the function’s capability to handle multiple filtering criteria effectively. We can test the function using the following PostgreSQL command:
Query:
SELECT * FROM
get_film ('%er', 2006);
Output
Explanation:
This query retrieves all films whose titles contain “er” and were released in 2006. The output will display a list of films that match these criteria.
Understanding PostgreSQL RETURN QUERY
The RETURN QUERY
command is essential when creating functions that return a set of results. It allows us to execute a query and return its results directly without the need for looping. This can simplify our code and improve performance.
Use Cases for RETURN QUERY
- Dynamic Filtering: Easily filter data based on various parameters without complex logic.
- Aggregated Results: Combine multiple queries to return a single result set.
- Simplified Logic: Reduces the need for manual iteration and record handling.
Conclusion
In summary, mastering how to create functions that return tables in PostgreSQL can significantly enhance our database management capabilities. By being aware of common casting errors in PostgreSQL functions, we can avoid potential downfalls that may arise during implementation.
Understanding PostgreSQL RETURN QUERY and its various use cases empowers us to use the full potential of functions, enabling efficient data retrieval and manipulation. Implement these practices to optimize our PostgreSQL experience.
FAQs
How to return a table in PostgreSQL function?
In PostgreSQL, you can return a table by using a function with the
RETURNS TABLE
clause and specifying the table structure. UseRETURN QUERY
to return the result set.
Can a function return a table?
Yes, PostgreSQL functions can return tables by using the
RETURNS TABLE
clause to define the output structure of the table.
What is the returning command in PostgreSQL?
The
RETURNING
command is used inINSERT
,UPDATE
, andDELETE
statements to return values from modified rows, such as the inserted or updated data.