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
SQL Tutorial Structured Query Language (SQL) is the standard language used to interact with relational databases. Whether you want to create, delete, update or read data, SQL provides the structure and commands to perform these operations. SQL is widely supported across various database systems like MySQL, Oracl
8 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Normal Forms in DBMS In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
7 min read
Top 60 DBMS Interview Questions with Answers for 2025 A Database Management System (DBMS) is the backbone of modern data storage and management. Understanding DBMS concepts is critical for anyone looking to work with databases. Whether you're preparing for your first job in database management or advancing in your career, being well-prepared for a DBMS
15+ min read
Window Functions in SQL SQL window functions are essential for advanced data analysis and database management. It is a type of function that allows us to perform calculations across a specific set of rows related to the current row. These calculations happen within a defined window of data and they are particularly useful
6 min read
SQL Exercises : SQL Practice with Solution for Beginners and Experienced SQL (Structured Query Language) is a powerful and flexible tool for managing and manipulating relational databases. Regardless of our experience level, practising SQL exercises is essential for improving our skills. Regular practice not only enhances our understanding of SQL concepts but also builds
15+ min read
SQL Cheat Sheet ( Basic to Advanced) Creating and managing databases in SQL involves various commands and concepts that handle the structuring, querying, and manipulation of data. In this guide, we will see a comprehensive cheat sheet for essential SQL operations, offering a practical reference for tasks ranging from database creation
15 min read
MySQL Tutorial This MySQL Tutorial is made for both beginners and experienced professionals. Whether you're starting with MYSQL basics or diving into advanced concepts, this free tutorial is the ideal guide to help you learn and understand MYSQL, no matter your skill level. From setting up your database to perform
11 min read
SQL Views Views in SQL are a type of virtual table that simplifies how users interact with data across one or more tables. Unlike traditional tables, a view in SQL does not store data on disk; instead, it dynamically retrieves data based on a pre-defined query each time itâs accessed. SQL views are particular
7 min read
Indexing in Databases - Set 1 Indexing is a crucial technique used in databases to optimize data retrieval operations. It improves query performance by minimizing disk I/O operations, thus reducing the time it takes to locate and access data. Essentially, indexing allows the database management system (DBMS) to locate data more
8 min read