⬅ Previous Topic
SQL Pivot and UnpivotNext Topic ⮕
SQL with Python⬅ Previous Topic
SQL Pivot and UnpivotNext Topic ⮕
SQL with PythonImagine you want to generate a sequence of roll numbers, calculate cumulative totals, or traverse a hierarchy like class monitors → captains → principal. You could use loops in programming — but in SQL, you can use recursive queries. These powerful tools let your query call itself, opening doors to solving problems that are inherently stepwise or hierarchical.
A recursive query is a query that refers to itself. It’s most commonly written using a Recursive Common Table Expression (CTE). It starts with a base query, and then repeatedly applies a rule to build new rows from the previous result.
WITH RECURSIVE cte_name AS (
-- Anchor query (base case)
SELECT ...
UNION ALL
-- Recursive query (refers to cte_name)
SELECT ... FROM cte_name WHERE ...
)
SELECT * FROM cte_name;
WITH RECURSIVE roll_list AS (
SELECT 1 AS roll_no
UNION ALL
SELECT roll_no + 1 FROM roll_list WHERE roll_no < 5
)
SELECT * FROM roll_list;
roll_no
--------
1
2
3
4
5
Let’s define a simple leadership structure:
CREATE TABLE school_leaders (
name VARCHAR(50),
reports_to VARCHAR(50)
);
INSERT INTO school_leaders VALUES
('Head Boy', 'Vice Principal'),
('Class Monitor', 'Head Boy'),
('Sports Captain', 'Head Boy'),
('Vice Principal', 'Principal'),
('Principal', NULL);
WITH RECURSIVE leadership_chain AS (
SELECT name, reports_to
FROM school_leaders
WHERE name = 'Class Monitor'
UNION ALL
SELECT sl.name, sl.reports_to
FROM school_leaders sl
JOIN leadership_chain lc ON sl.name = lc.reports_to
)
SELECT * FROM leadership_chain;
name | reports_to
------------------+------------
Class Monitor | Head Boy
Head Boy | Vice Principal
Vice Principal | Principal
Principal | NULL
reports_to
is NULLUNION ALL
— NOT just UNIONLIMIT
or WHERE
filters to restrict depthRecursive queries are SQL’s way of thinking step-by-step. Whether you're generating data sequences, traversing hierarchies, or building dynamic relationships in school data, recursive CTEs give your SQL logic a structured, powerful toolset — all without writing loops or procedures.
Up next: SQL Interview Questions — test your understanding with real-world problems and their solutions.
student_id | mentor_id
1001 | NULL
1002 | 1001
1003 | 1002
Which technique would best retrieve the full mentorship chain for student 1003?⬅ Previous Topic
SQL Pivot and UnpivotNext Topic ⮕
SQL with PythonYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.