PostgreSQL - Function Returning A Table
Last Updated :
16 Oct, 2024
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
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

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.
Similar Reads
PostgreSQL String Functions
PostgreSQL is a powerful, open-source relational database management system that offers a rich set of functions and operators for working with string data. String manipulation is an essential task in many applications, and PostgreSQL provides a variety of built-in functions to make working with text
8 min read
RETURNING in PostgreSQL
The RETURNING clause in PostgreSQL is a powerful feature that allows developers to retrieve data directly after executing SQL operations such as INSERT, UPDATE, or DELETE. This feature eliminates the need for multiple queries to fetch modified data, resulting in optimized performance, cleaner code,
4 min read
PostgreSQL - RIGHT Function
The PostgreSQL RIGHT() function, allows you to extract a specified number of characters from the right side of a string. This function can be incredibly useful for various text-processing tasks.Let us get a better understanding of the RIGHT Function in PostgreSQL from this article.SyntaxRIGHT(string
2 min read
PostgreSQL REVERSE() Function
The REVERSE() function in PostgreSQL is a simple yet powerful tool used to reverse the order of characters in a given string. It takes one input which is a string and returns the characters in reverse order. This function is helpful when you need to transform data, run tests or validate information.
4 min read
PostgreSQL - UPPER Function
In PostgreSQL, the UPPER function is utilized to convert a string into uppercase. This function is handy when you need to standardize text data by converting it to a uniform case, especially for comparison or display purposes.Let us get a better understanding of the UPPER Function in PostgreSQL from
2 min read
PostgreSQL - CURRENT_TIME Function
The PostgreSQL CURRENT_TIME function returns the current time and the current time zone. This function is handy when you need to work with time-sensitive data in your database applications.Let us better understand the CURRENT_TIME Function in PostgreSQL from this article.SyntaxCURRENT_TIME(precision
2 min read
PostgreSQL - SUM() Function
The SUM() function in PostgreSQL is used to calculate the sum of values in a numeric column. This article will guide you through the syntax, important considerations, and practical examples of using the SUM() function in PostgreSQL.SyntaxSUM(column) The following points need to be kept in mind while
2 min read
PostgreSQL - CREATE FUNCTION Statement
PostgreSQL allows developers to create user-defined functions to encapsulate reusable logic, making database operations more efficient and modular. The CREATE FUNCTION statement is used to define a new function, supporting various procedural languages, with plpgsql being the most commonly used in Po
5 min read
PostgreSQL - ASCII Function
When working with PostgreSQL, you might need to derive the ASCII (American Standard Code for Information Interchange) code of a character. The PostgreSQL ASCII() function is a handy tool for this purpose. In the case of UTF-8 encoding, the ASCII() function returns the Unicode code point of the chara
2 min read
PostgreSQL - Create Tables in Python
Creating tables in PostgreSQL using Python is an essential skill for developers working with databases. This article will explore the process of creating new tables in the PostgreSQL database using Python.Why Create PostgreSQL Tables with Python?Using Python to create PostgreSQL tables is beneficial
4 min read