I\'m currently having some trouble understanding and writing recursive queries. I understand that recursive queries are used to search through hierarchies of information, bu
Are you familiar with the SCOTT.EMP
table? It's in the "standard" SCOTT
schema (which, unfortunately, is no longer pre-packaged with every copy of Oracle database, since version 12.1 or so). Check your database: you may find it there. Or ask your DBA about it.
Anyway: the table shows the 14 employees of a small business, and it includes the employee's ID as well as his or her manager's employee ID. So, suppose you start with a given employee and you want to find his or her highest-level boss. (Similar to your test problem.) In this particular hierarchy, the highest-level "ancestor" is unique, but that is irrelevant; the recursive query would work the same way if each department had a "head of department" and there was no CEO above the heads of department.
In this arrangement, it's easy to identify the "boss of all bosses" - he does not have a boss. In his row, the manager ID is null
. This is a very common arrangement for the "root" (or "roots") of tree-like hierarchies.
Here is how you would find the boss, starting with a specific employee id, and using a recursive query - which is what I understand is what you are looking to practice on. (That is: if I understand correctly, you are not interested in solving the problem "by any means"; rather, you want to see how recursive queries work, in a small example so you can understand EVERYTHING that goes on.)
with
r ( empno, mgr ) as (
select empno, mgr -- ANCHOR leg of recursive query
from scott.emp
where empno = 7499
union all
select e.empno, e.mgr -- RECURSIVE leg of recursive query
from scott.emp e inner join r on e.empno = r.mgr
)
select empno
from r
where mgr is null
;
I will not try to guess where you may have difficulty understanding this example. Instead, I will wait for you to ask.