PostgreSQL – Create Recursive Views
Last Updated :
22 Aug, 2024
A view in PostgreSQL can be defined as a virtual table that is derived from underlying base tables or previously defined views. A view is nothing but a SQL statement that is stored in the database with an associated name. We have looked at what is the recursive query. To store the recursive query or to make a view out of a recursive query, PostgreSQL provides recursive views. So, recursive views are nothing but stored recursive queries.
In this article, we will learn about recursive views in PostgreSQL. We will introduce you to the concept of recursive views, show how recursive views are created, And most importantly we will also see how recursive views can be implemented in PostgreSQL.
Why Use Recursive Views?
Recursive views simplify complex recursive queries by allowing you to store them as a reusable virtual table. This makes your code cleaner and easier to maintain while also improving query performance by reducing repetition.
Creating PostgreSQL Recursive Views
PostgreSQL provides two types of syntax for creating a recursive view.
Syntax:
CREATE RECURSIVE VIEW view_name(columns)
AS
SELECT ...; -- SQL query
Which is equivalent to:
CREATE VIEW view_name AS
WITH RECURSIVE view_name (column_names) AS
-- recursive SQL query
SELECT ...
)
SELECT column_names
FROM view_name;
Examples of Recursive Views in PostgreSQL
Let’s see some examples of recursive views.
Example 1: Calculating Factorials Using Recursive Views
Let’s start with a simple example of calculating factorials using a recursive view:
Query:
CREATE RECURSIVE VIEW fact(n, factorial) AS
(
SELECT 1 as n, 5 as factorial
UNION ALL
SELECT n+1, factorial*n FROM fact WHERE n < 5
);
SELECT * FROM fact;
In this example:
- The first SELECT statement defines the base case with ‘n = 1′ and ‘factorial = 5′.
- The second SELECT statement performs the recursive computation, incrementing ‘n’ and multiplying the current factorial by ‘n’.
- The UNION ALL combines the results of both queries.
This code will create a view of the factorial of a natural number. which is the same as:
Query:
CREATE VIEW fact AS
WITH RECURSIVE fact(n, factorial) AS
(
SELECT 1 as n, 5 as factorial
UNION ALL
SELECT n + 1, factorial * n FROM fact WHERE n < 5
)
SELECT * FROM fact;
Both will give you the same output.
Here in this example, we are only considering ‘n=5′. We can print only the last row but here we can see how the iteration and calculation take place.
Output:
CREATE VIEW
n | factorial
---+-----------
1 | 5
2 | 5
3 | 10
4 | 30
5 | 120
(5 rows)
Example 2: Generating a Sequence of Numbers Recursively
Let’s take a look at another sample example, which is producing 1 to 10 numbers recursively.
Query:
CREATE RECURSIVE VIEW tens(n) AS
(
SELECT 1 as n
UNION ALL
SELECT n+1 FROM tens
);
SELECT * FROM tens limit 10;
Output:
Example 3: Managing Organizational Hierarchies
Now let’s look at some real-life examples of recursive view, with the help of recursive view we can find the organizational hierarchy.
Step 1: Create a table.
Query:
PostgreSQL
CREATE TABLE emp (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(50),
manager_id INT
);
INSERT INTO emp (emp_id, emp_name, manager_id)
VALUES
(1, 'Onkar', NULL),
(2, 'Isaac', 1),
(3, 'Jack', 1),
(4, 'Aditya', 1),
(5, 'Albert', 1),
(6, 'Alex', 2),
(7, 'Brian', 2),
(8, 'Harry', 3),
(9, 'Paul', 3),
(10, 'Kunal', 4),
(11, 'Pranav', 5);
Step 2: Create a Recursive View to Display the Organizational Hierarchy
This data represent hierarchy, e.g., Isaac is working under Onkar and Alex is working under Isaac. Thus Onkar is on top level. This example will give us results of which employee is working at which level.
Query:
CREATE RECURSIVE VIEW subordinates(emp_id, manager_id, emp_name, level) AS
(
SELECT emp_id, manager_id, emp_name, 0 AS level
FROM emp
WHERE manager_id IS NULL
UNION ALL
SELECT e.emp_id, e.manager_id, e.emp_name, s.level + 1
FROM emp e
INNER JOIN subordinates s ON s.emp_id = e.manager_id
);
SELECT * FROM subordinates ORDER BY level, emp_id;
Output:

Conclusion
Recursive views in PostgreSQL are a powerful feature for handling hierarchical data, generating sequences, and solving other recursive problems. By storing recursive queries as views, you can simplify complex data relationships, making your queries more efficient and easier to manage.
Similar Reads
PostgreSQL - Create updatable Views
Views in PostgreSQL provide a way to represent a subset of a real table, selecting certain columns or rows from an ordinary table. They are particularly useful for restricting access to the original table, allowing users to see only a specific portion of it. The table from which a view is created is
3 min read
PostgreSQL - Recursive Query Using CTEs
Recursive queries are a powerful feature in PostgreSQL that allow you to perform iterative operations within a database. While strictly speaking, this process is iteration, the SQL standards committee chose the term RECURSIVE. This article will provide an in-depth understanding of PostgreSQL recursi
4 min read
PostgreSQL - Recursive Query
PostgreSQL is a powerful relational database management system, widely recognized for its advanced capabilities, one of which is the ability to write recursive queries using the WITH statement. This statement, often referred to as Common Table Expressions (CTEs), allows developers to write complex q
3 min read
PostgreSQL - CREATE TABLE
In PostgreSQL, the CREATE TABLE statement is used to define a new table within a database. It allows us to specify the table's structure, including column names, data types, and constraints, ensuring data integrity and consistency. Understanding the PostgreSQL table creation process is essential for
5 min read
PostgreSQL - DROP VIEWS Statement
A view in PostgreSQL can be seen as a virtual table that can contain all rows of a table or selected rows from one or more tables. Views allow us to see limited data instead of the complete information stored in a table. A view can be created from one or many base tables (the table from which the vi
4 min read
PostgreSQL - Materialized Views
Materialized Views in PostgreSQL are a powerful tool that can significantly enhance query performance by physically storing the result of a complex query. Unlike standard views, which compute their result set every time they are queried, materialized views store the query result and can be refreshed
3 min read
PostgreSQL - CREATE TABLE AS
The CREATE TABLE AS statement in PostgreSQL is a powerful tool used to create a new table and populate it with data returned by a query. This functionality allows you to generate tables on the fly based on query results, which can be very useful for reporting, analysis, and other tasks. Let us bette
3 min read
PL/SQL CREATE VIEW
PL/SQL CREATE VIEW is a statement used to create a virtual table based on the result of a query. Views in PL/SQL allow users to access and manipulate data stored in one or more underlying tables as if it were a single table. In this article, We will learn about the PL/SQL CREATE VIEW by understandin
3 min read
SQL CREATE VIEW Statement
The SQL CREATE VIEW statement is a very powerful feature in RDBMSs that allows users to create virtual tables based on the result set of a SQL query. Unlike regular tables, these views do not store data themselves rather they provide a way of dynamically retrieving and presenting data from one or ma
4 min read
PostgreSQL - Managing Views
Views in PostgreSQL are a powerful tool that allows you to simplify complex queries by abstracting them into virtual tables. They are derived from base tables or previously defined views, offering a convenient way to organize and manage your data without creating physical copies. In this article, we
4 min read