![]() |
VOOZH | about |
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 queries with better readability and reusability. Recursive queries, a subset of CTEs, are particularly useful for working with hierarchical data structures, such as organizational charts, file systems, or any scenario where data is linked in parent-child relationships.
The WITH statement in PostgreSQL provides a way to define temporary result sets (or CTEs) that can be referenced within a larger query. Recursive CTEs are queries that refer back to themselves, making them ideal for handling scenarios involving hierarchical data.
WITH RECURSIVE cte_name AS( CTE_query_definition <-- non-recursive term UNION [ALL] CTE_query definition <-- recursive term ) SELECT * FROM cte_name;
Let's analyze the above syntax:
First, we create a sample table using the below commands to perform examples:
Now that the table is ready we can look into some examples.
The below query returns all subordinates of the manager with the id 3.
Query:
WITH RECURSIVE subordinates AS ( SELECT employee_id, manager_id, full_name FROM employees WHERE employee_id = 3 UNIONSELECT e.employee_id, e.manager_id, e.full_name FROM employees e INNER JOIN subordinates s ON s.employee_id = e.manager_id ) SELECT * FROM subordinates;
Output:
👁 PostgreSQL Recursive Query ExampleExplanation: The query starts by selecting the employee with 'employee_id = 3' (R. Sharma) as the base case. It then recursively finds all employees who report directly or indirectly to him.
The below query returns all subordinates of the manager with the id 4.
Query:
WITH RECURSIVE subordinates AS ( SELECT employee_id, manager_id, full_name FROM employees WHERE employee_id = 4 UNIONSELECT e.employee_id, e.manager_id, e.full_name FROM employees e INNER JOIN subordinates s ON s.employee_id = e.manager_id ) SELECT* FROM subordinates;
Output:
👁 PostgreSQL Recursive Query ExampleExplanation: The recursion starts with S. Raina and finds all employees reporting to him, either directly or indirectly.
Recursive queries in PostgreSQL are powerful tools for handling hierarchical data. By leveraging the WITH RECURSIVE statement, you can simplify complex queries and enhance your ability to query relationships within your data. Understanding the different components of recursive queries and how they work is crucial for building efficient and scalable PostgreSQL applications.