13. Hierarchical Queries
Last updated
-- Self join the table
select a.ename || ' works for ' || b.ename as emps_and_mgrs
from emp a, emp b
where a.mgr = b.empnoselect ltrim(
sys_connect_by_path(ename,'-->'),
'-->') leaf___branch___root
from emp
where level = 3
start with ename = 'MILLER'
connect by prior mgr = empnoselect ltrim(
sys_connect_by_path(ename,' - '),
' - ') emp_tree
from emp
start with mgr is null
connect by prior empno=mgr
order by 1ENAME
----------
JONES
SCOTT
ADAMS
FORD
SMITH-- Oracle
select ename
from emp
start with ename = 'JONES'
connect by prior empno = mgrselect
ename,
connect_by_isleaf is_leaf,
(select count(*) from emp e
where e.mgr = emp.empno
and emp.mgr is not null
and rownum = 1) is_branch,
decode(ename,connect_by_root(ename),1,0) is_root
from emp
start with mgr is null
connect by prior empno = mgr
order by 4 desc, 3 desc