How to Implement Recursive CTE for Hierarchical Query to MariaDB?
Last Updated :
07 May, 2024
Hierarchical data structures such as organizational hierarchies, file systems or product sections are common to find in the database. MariaDB an open-source relational database management system, offers several methods for querying hierarchical information, among them Recursive Common Table Expressions (CTEs) as a highly efficient and versatile option.
In this article, we will learn various methods of using Recursive CTEs in hierarchical queries of MariaDB to serve to different situations.
Understanding Recursive CTEs
- Recursive CTEs carry out repetitive queries on hierarchical data by doing SELECT statement which contains CTE itself an infinite number of times.
- This functionality is primarily useful when dealing with and querying data which is presented in a hierarchical structure to optimize the output results.
Employees Table:
To understand How to Implement Recursive CTE for Hierarchical Query to MariaDB we need a table on which we will perform various operations and queries. Here we will consider a table called employees which contains employee_id, name, and manager_id as Columns.
+-------------+---------------+------------+
| employee_id | name | manager_id |
+-------------+---------------+------------+
| 1 | John Doe | NULL |
| 2 | Jane Smith | 1 |
| 3 | Alice Johnson | 2 |
+-------------+---------------+------------+
Method 1: Direct Recursive CTE
This method directly defines a Recursive Common Table Expression (CTE) within the query. It recursively traverses the hierarchical data structure in a single query, making it concise and efficient.
Steps to follows:
- Define the Recursive CTE with an anchor member and a recursive member.
- Use the CTE in subsequent SQL statements to retrieve hierarchical data.
Example:
WITH RECURSIVE EmployeeHierarchy AS (
SELECT employee_id, name, manager_id
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.employee_id, e.name, e.manager_id
FROM employees e
JOIN EmployeeHierarchy eh ON e.manager_id = eh.employee_id
)
SELECT * FROM EmployeeHierarchy;
Output:
+-------------+-------------+------------+
| employee_id | name | manager_id |
+-------------+-------------+------------+
| 1 | John Doe | NULL |
| 2 | Jane Smith | 1 |
| 3 | Alice Johnson | 2 |
+-------------+-------------+------------+
Explanation:
- The hierarchical structure of employees in the organization is shown on the output. Each line stands for a employee with his employee_id, name, and manager_id among the data columns.
- The manager_id attribute points to an employee's manager, where NULL values shows top-level employees who have no manager.
Method 2: Use Temporary Table with Recursive CTE
It is an approach where a table is formed usually on a temporary basis to contain the hierarchical data on it. It offers more freedom in complex querying scenarios and performance for repeated queries can be increased.
Steps to follows:
- Define the Recursive CTE within a CREATE TEMPORARY TABLE statement.
- Query the temporary table to retrieve hierarchical data.
- Optionally drop the temporary table when it is no longer needed.
Example:
CREATE TEMPORARY TABLE TempHierarchy AS (
WITH RECURSIVE Hierarchy AS (
SELECT employee_id, name, manager_id
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.employee_id, e.name, e.manager_id
FROM employees e
JOIN Hierarchy h ON e.manager_id = h.employee_id
)
SELECT * FROM Hierarchy
);
SELECT * FROM TempHierarchy;
DROP TEMPORARY TABLE IF EXISTS TempHierarchy;
Output:
+-------------+-------------+------------+
| employee_id | name | manager_id |
+-------------+-------------+------------+
| 1 | John Doe | NULL |
| 2 | Jane Smith | 1 |
| 3 | Alice Johnson | 2 |
+-------------+-------------+------------+
Explanation: This method involves creating a temporary table named TempHierarchy to store the hierarchical data temporarily. The output of and the temporary table is the same as Method 1. After querying, the temporary table is dropped to release resources
Conclusion
Overall, MariaDB provides flexible techniques of creating Recursive "Common Table Expressions" to navigate the hierarchical data precisely. Direct usage of CTEs, writing views or temporary tables and any of these methods has its own benefits as it is based on the exact requirements of your application.
Similar Reads
How to Create a SQLite Hierarchical Recursive Query? SQLite is a powerful database management system that supports hierarchical recursive queries. These queries are useful for working with hierarchical data structures like organizational charts, file systems, and nested categories. In this article, we will explore how to create hierarchical recursive
3 min read
How to Manage Hierarchical Data in MySQL? Managing hierarchical data in MySQL poses a unique set of challenges due to the relational nature of traditional database systems. Hierarchical data structures, such as organizational charts or category hierarchies, require thoughtful strategies for storage and retrieval. In this article, we will ex
3 min read
How to Run Hierarchical Queries with PostgreSQL? In the area of database management, dealing with hierarchical data structures has unique challenges. Whether it's organizational charts, category hierarchies, or file systems, efficiently querying and traversing hierarchical data is essential for many applications. PostgreSQL, a powerful relational
3 min read
How to Efficiently Convert Rows to Columns in MariaDB? In the area of database management, the ability to convert rows to columns efficiently is a valuable skill. MariaDB, a popular open-source relational database management system offers various methods to achieve this transformation. In this article, we'll learn about How to Convert Rows into Columns
3 min read
How to Enable MariaDB General Query Logs MariaDB is a commonly used open-source database management system. Logging capabilities are one of the features that aims to help administrators to track database activities accurately. Among these log features, a general log for logging all SQL queries executed on the server is a very useful instru
3 min read
How to List all Stored Procedures in MariaDB? When working with MariaDB, it's important to be able to manage and maintain stored procedures effectively. Listing all stored procedures in a database can provide valuable insights into its structure and functionality. In this article, we'll explore how to list all stored procedures in MariaDB by un
4 min read