- Advanced SQL
-
Overview
- Indexing for Performance Optimization
- Transactions and ACID Properties
- Triggers and Event Scheduling in SQL
- Window Functions and Ranking
- Pivoting Data in SQL
- JSON and XML Data Handling
- Recursive Queries in SQL
- Performance Tuning and Query Optimization
- Role-Based Access Control in Databases
- Handling Large Datasets in SQL
Recursive Queries in SQL
Add to BookmarkIntroduction
Recursive queries allow SQL databases to process hierarchical or tree-structured data, such as organizational charts, category trees, and ancestry relationships. They are implemented using Common Table Expressions (CTEs) with the WITH RECURSIVE
clause.
This tutorial covers the fundamentals of recursive queries, their syntax, and practical examples.
Why Use Recursive Queries?
Recursive queries are useful when working with:
- Hierarchical data (e.g., employee-manager relationships).
- Tree structures (e.g., category-subcategory systems).
- Graph traversal (e.g., shortest path algorithms).
Instead of performing multiple self-joins, recursive queries efficiently retrieve multi-level hierarchical data in a single execution.
Understanding Recursive CTEs
A recursive CTE consists of two parts:
- Anchor Query – The base case that retrieves the first level of data.
- Recursive Query – The recursive part that joins data with itself to retrieve subsequent levels.
Basic Syntax
WITH RECURSIVE cte_name AS (
-- Anchor Query (Base Case)
SELECT column1, column2 FROM table WHERE condition
UNION ALL
-- Recursive Query (Recursive Case)
SELECT column1, column2 FROM table, cte_name WHERE join_condition
)
SELECT * FROM cte_name;
The recursive query repeatedly executes until no more rows are returned.
Example 1: Employee Hierarchy
Consider an employees table where each employee has a manager_id
.
Table Structure
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(100),
manager_id INT
);
Sample Data
id | name | manager_id |
---|---|---|
1 | Alice | NULL |
2 | Bob | 1 |
3 | Charlie | 1 |
4 | David | 2 |
5 | Eve | 2 |
6 | Frank | 3 |
Recursive Query to Get Employee Hierarchy
WITH RECURSIVE EmployeeHierarchy AS (
-- Anchor Query: Get the top-level manager (Alice)
SELECT id, name, manager_id, 1 AS hierarchy_level
FROM employees
WHERE manager_id IS NULL
UNION ALL
-- Recursive Query: Get employees reporting to previous level
SELECT e.id, e.name, e.manager_id, eh.hierarchy_level + 1
FROM employees e
INNER JOIN EmployeeHierarchy eh ON e.manager_id = eh.id
)
SELECT * FROM EmployeeHierarchy;
Output
id | name | manager_id | hierarchy_level |
---|---|---|---|
1 | Alice | NULL | 1 |
2 | Bob | 1 | 2 |
3 | Charlie | 1 | 2 |
4 | David | 2 | 3 |
5 | Eve | 2 | 3 |
6 | Frank | 3 | 3 |
Explanation:
- Alice (Level 1) has no manager.
- Bob and Charlie (Level 2) report to Alice.
- David, Eve, and Frank (Level 3) report to Bob or Charlie.
Example 2: Category-Subcategory Relationship
Consider a categories table for an e-commerce website.
Table Structure
CREATE TABLE categories (
id INT PRIMARY KEY,
category_name VARCHAR(100),
parent_id INT
);
Sample Data
id | category_name | parent_id |
---|---|---|
1 | Electronics | NULL |
2 | Phones | 1 |
3 | Laptops | 1 |
4 | Android | 2 |
5 | iPhone | 2 |
6 | Gaming Laptops | 3 |
Recursive Query to Fetch Category Tree
WITH RECURSIVE CategoryTree AS (
-- Anchor Query: Fetch top-level categories
SELECT id, category_name, parent_id, 1 AS level
FROM categories
WHERE parent_id IS NULL
UNION ALL
-- Recursive Query: Get subcategories
SELECT c.id, c.category_name, c.parent_id, ct.level + 1
FROM categories c
INNER JOIN CategoryTree ct ON c.parent_id = ct.id
)
SELECT * FROM CategoryTree ORDER BY level;
Output
id | category_name | parent_id | level |
---|---|---|---|
1 | Electronics | NULL | 1 |
2 | Phones | 1 | 2 |
3 | Laptops | 1 | 2 |
4 | Android | 2 | 3 |
5 | iPhone | 2 | 3 |
6 | Gaming Laptops | 3 | 3 |
Explanation:
- Electronics (Level 1) is the parent category.
- Phones & Laptops (Level 2) are subcategories of Electronics.
- Android, iPhone & Gaming Laptops (Level 3) are further subcategories.
Performance Considerations
Recursive queries can be slow if the hierarchy is too deep. To optimize:
- Use indexing on
id
andparent_id
columns. - Limit recursion depth with
OPTION (MAXRECURSION n)
(SQL Server). - Use JSON/XML storage for deeply nested structures.
Conclusion
- Recursive queries help process hierarchical data efficiently.
WITH RECURSIVE
CTEs allow self-referencing queries in SQL.- They are widely used for employee hierarchies, category trees, and graph-based relationships.
Understanding and optimizing recursive queries can greatly enhance database performance when handling hierarchical data.
Prepare for Interview
- JavaScript Interview Questions for 5+ Years Experience
- JavaScript Interview Questions for 2–5 Years Experience
- JavaScript Interview Questions for 1–2 Years Experience
- JavaScript Interview Questions for 0–1 Year Experience
- JavaScript Interview Questions For Fresher
- SQL Interview Questions for 5+ Years Experience
- SQL Interview Questions for 2–5 Years Experience
- SQL Interview Questions for 1–2 Years Experience
- SQL Interview Questions for 0–1 Year Experience
- SQL Interview Questions for Freshers
- Design Patterns in Python
- Dynamic Programming and Recursion in Python
- Trees and Graphs in Python
- Linked Lists, Stacks, and Queues in Python
- Sorting and Searching in Python
Random Blogs
- What to Do When Your MySQL Table Grows Too Wide
- AI Agents & Autonomous Systems – The Future of Self-Driven Intelligence
- AI in Cybersecurity: The Future of Digital Protection
- Store Data Into CSV File Using Python Tkinter GUI Library
- Datasets for analyze in Tableau
- Python Challenging Programming Exercises Part 3
- The Ultimate Guide to Machine Learning (ML) for Beginners
- Understanding Data Lake, Data Warehouse, Data Mart, and Data Lakehouse – And Why We Need Them
- AI in Marketing & Advertising: The Future of AI-Driven Strategies
- Downlaod Youtube Video in Any Format Using Python Pytube Library
- The Ultimate Guide to Starting a Career in Computer Vision
- Top 10 Knowledge for Machine Learning & Data Science Students
- What is YII? and How to Install it?
- How AI Companies Are Making Humans Fools and Exploiting Their Data
- How to Install Tableau and Power BI on Ubuntu Using VirtualBox
Datasets for Machine Learning
- Awesome-ChatGPT-Prompts
- Amazon Product Reviews Dataset
- Ozone Level Detection Dataset
- Bank Transaction Fraud Detection
- YouTube Trending Video Dataset (updated daily)
- Covid-19 Case Surveillance Public Use Dataset
- US Election 2020
- Forest Fires Dataset
- Mobile Robots Dataset
- Safety Helmet Detection
- All Space Missions from 1957
- OSIC Pulmonary Fibrosis Progression Dataset
- Wine Quality Dataset
- Google Audio Dataset
- Iris flower dataset