Recursive Queries
WITH Clause
SQL> SELECT EName , Empno, Mgr FROM SQL> select e1.mgr,e2.ename mgrName
EMP; ,e1.empno ,e1.ename Ename
2 from emp e1, emp e2 where
e1.mgr=e2.empno;
Display each Manger detail and employee
Data in Emp(Empno,Ename,Mgr) table
details who report to the manger.
WITH Clause
Find all the employees who reports to What if we want to find out who are all
Manager with employee id 7566 under manger 7655(i.e. who are all directly
or indirectly report to 7566)
SQL> SELECT e.MGR, e.EMPNO MGR EMPNO *This output is the rows indicated
---------- ---------- by arrow in previous slide
2 FROM EMP e
3 WHERE e.MGR = 7566; 7566 7902
7788 7876
7902 7369
7566 7788
If this is the nature of output
displayed, then we need to apply left
side query recursively.
7566
7902 7788
7369 7876
Recursive Query-WITH Clause
• Recursive query is applied to query hierarchical data using recursive subquery factoring.
Recursion is implemented in standard SQL-99 using Common Table Expressions (CTEs).
• A CTE can be thought of as a named temporary table within a SQL statement that is retained
for the duration of that statement.
• A CTE is defined at the beginning of a query using the WITH clause.
• There can be multiple CTE and each CTE must have Unique name.
In general, in recursion there has to be seed and recursion stopping criteria.
WITH R as (<Base Query > /*base member*/
UNION ALL
<Recursive Query involving R>); /* recursive member references
R*/
<Query involving R>;
Any recursive view must be defined as the union of two subqueries: a base query
that is nonrecursive and a recursive query that uses the recursive view. In
Example-Recursive Query(WITH Clause)
Find all the employees who reports directly or indirectly to the Manager
with employee id 7566
WITH Empl_ReportTo_7566 (MGR, EMPNO) AS
(
SELECT e1.MGR, e1.EMPNO
FROM EMP e1
WHERE e1.MGR = 7566
UNION ALL
SELECT CHILD.MGR, CHILD.EMPNO
FROM Empl_ReportTo_7566 PARENT, EMP CHILD
WHERE PARENT.EMPNO = CHILD.MGR
)
SELECT DISTINCT MGR, EMPNO
FROM Empl_ReportTo_7566;