Open In App

PostgreSQL – Function Returning A Table

Last Updated : 16 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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.

Sample Database

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 theget_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 Function Returning A Table

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

PostgreSQL Function Returning A Table

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 and p_year.
  • Looping through Results: The function uses a FOR loop to iterate through the results of the SELECT 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

PostgreSQL Function Returning A Table

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

  1. Dynamic Filtering: Easily filter data based on various parameters without complex logic.
  2. Aggregated Results: Combine multiple queries to return a single result set.
  3. 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. Use RETURN 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 in INSERT, UPDATE, and DELETE statements to return values from modified rows, such as the inserted or updated data.



Next Article

Similar Reads

three90RightbarBannerImg