How to Create a SQLite Hierarchical Recursive Query?
Last Updated :
12 Mar, 2024
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 queries, allowing us to efficiently write query and manipulate hierarchical data in our applications.
How to Create Hierarchical Recursive Query in SQLite?
Hierarchical data structures often require complex queries to retrieve and manipulate data. SQLite provides several approaches to handle hierarchical data efficiently Below are the approaches that help us to create a hierarchical recursive query SQLite as follows:
- Recursive Query using UNION ALL
- Using JOIN and LEVEL
- Using Path Concatenation
Let's set up an environment
To understand How to create a SQLite hierarchical recursive query we need a table on which we will perform various operations and queries. Here we will consider a table called Categories which contains CategoryID, ParentCategoryID, and CategoryName as Columns.
-- Create the Categories table
CREATE TABLE Categories (
CategoryID INTEGER PRIMARY KEY,
ParentCategoryID INTEGER,
CategoryName TEXT
);
-- Insert sample data
INSERT INTO Categories (CategoryID, ParentCategoryID, CategoryName) VALUES
(1, NULL, 'Electronics'),
(2, 1, 'Mobile Phones'),
(3, 1, 'Laptops'),
(4, 2, 'Smartphones'),
(5, 2, 'Feature Phones'),
(6, 3, 'Gaming Laptops'),
(7, 3, 'Business Laptops');
Our Table Looks like:
Table1. Recursive Query using UNION ALL
In this approach, a Common Table Expression (CTE) named OrgHierarchy is created with a recursive part using UNION ALL. The initial query selects top-level nodes where ParentNodeID is NULL, and the recursive part continues to select child nodes by joining the CTE with the original table using the relationship between NodeID and ParentNodeID. This method efficiently retrieves a hierarchical structure.
WITH RECURSIVE CategoryHierarchy AS (
SELECT CategoryID, ParentCategoryID, CategoryName
FROM Categories
WHERE ParentCategoryID IS NULL
UNION ALL
SELECT c.CategoryID, c.ParentCategoryID, c.CategoryName
FROM Categories c
JOIN CategoryHierarchy ch ON c.ParentCategoryID = ch.CategoryID
)
SELECT * FROM CategoryHierarchy;
Output:
Recursive Query using UNION ALL output2. Using JOIN and LEVEL
This approach utilizes the WITH RECURSIVE clause and a CTE named OrgHierarchy. It introduces a Level column to keep track of the depth in the hierarchy. The anchor member selects top-level nodes, and the recursive member continues to join the CTE with the original table, updating the level as it traverses the hierarchy.
This technique provides a straightforward way to determine the depth of each node in the hierarchy.
WITH RECURSIVE CategoryHierarchy AS (
SELECT CategoryID, ParentCategoryID, CategoryName, 0 AS Level
FROM Categories
WHERE ParentCategoryID IS NULL
UNION ALL
SELECT c.CategoryID, c.ParentCategoryID, c.CategoryName, ch.Level + 1
FROM Categories c
JOIN CategoryHierarchy ch ON c.ParentCategoryID = ch.CategoryID
)
SELECT * FROM CategoryHierarchy;
Output:
Using JOIN and LEVEL output3. Using Path Concatenation
In this approach, the OrgHierarchy CTE includes a column named Path, where the path to each node is represented as a concatenated string. The anchor member selects top-level nodes, and the recursive member appends each child node's NodeID to the path of its parent. This method is useful when you need to track the path or lineage of each node in the hierarchy.
WITH RECURSIVE CategoryHierarchy AS (
SELECT CategoryID, ParentCategoryID, CategoryName, CAST(CategoryID AS TEXT) AS Path
FROM Categories
WHERE ParentCategoryID IS NULL
UNION ALL
SELECT c.CategoryID, c.ParentCategoryID, c.CategoryName, ch.Path || '->' || c.CategoryID
FROM Categories c
JOIN CategoryHierarchy ch ON c.ParentCategoryID = ch.CategoryID
)
SELECT * FROM CategoryHierarchy;
Output:
Using Path ConcatenationConclusion
Overall, the implementation of hierarchical recursive queries using the WITH RECURSIVE clause and Common Table Expressions (CTEs) provides a powerful tool for traversing tree-like structures within tables, allowing efficient retrieval of hierarchical data.
The presented approaches, including recursive queries with UNION ALL, JOIN and LEVEL, and Path Concatenation, offer flexibility in managing hierarchical relationships in SQLite databases.
Similar Reads
How to Implement Recursive CTE for Hierarchical Query to MariaDB?
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 Expressi
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 Remove All Duplicate Rows Except One in SQLite?
SQLite is a lightweight and open-source relational database management system (RDBMS). SQLite does not require any server to process since it is a serverless architecture that can run operations and queries without any server. In this article, we will understand how to remove duplicate rows except o
5 min read
SQL Query to Return Rows Matching a Certain Condition
In SQL, sometimes we need to select matching a certain condition from the table. We will use the SELECT command along with the WHERE clause to apply a condition to achieve this in SQL. For this article. We will be using the Microsoft SQL Server as our database. Syntax: SELECT COLUMN_NAME_1, COLUMN_N
2 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
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
3 min read
How to Create View in SQLite
SQLite is a self-contained, serverless, and open-source relational database management system. It is used for simplicity, efficiency, and portability, SQLite is widely employed in diverse applications, from embedded systems to mobile devices and large-scale software. It is serverless, zero-configura
6 min read
How to delete duplicate rows in SQLite?
SQLite is an open-source and serverless database system that does not require any server to perform various queries also it is widely used in the development of embedded software like television and mobile phones Sometimes it might happen that we by mistake insert multiple times similar data into ta
3 min read
How to Get SQLite Database Size
SQLite is a lightweight and serverless SQL database. It is widely used in mobile devices and embedded systems due to its simplicity and efficiency. To understand how to manage SQLite databases efficiently, it is very important to know the Database size in SQLite. In this article, we will learn about
5 min read
How to Check if a Row Already Exists in SQLite?
SQLite is a widely used relational database management system due to its simplicity, lightweight design and energy efficiency features. When working with SQLite databases, It is very important to ensure data integrity therefore it is necessary to avoid accidentally inserting duplicated records. In t
3 min read