Oracle interview questions

                   

CONNECT BY PRIOR

 

 

Using CONNECT BY PRIOR along with a select statement, we could retrieve data in a hierarchical manner



 

If we have to query the employees reporting to a Manager James, directly, we do

 

SELECT EMPNAME, EMP_ID, MANAGER

FROM EMPLOYEE

WHERE  MANAGER= James 

 

EMPNAME                            EMP_ID        MANAGER

 

Bob                              3257                 James

Stacy                            9968                 James

Richy                            3689                 James

Richard                        4204                 James

Jones                            1147                 James

 

But how to find all employees who report to the Manager James, directly and indirectly?

We could use the CONNECT BY PRIOR facility in Oracle.

 

Thus goes the query:

 

SELECT EMPNAME, MANAGER, LEVEL

FROM EMPLOYEE

START WITH MANAGER= James 

CONNECT BY PRIOR EMPNAME = MANAGER

 

EMPNAME

MANAGER

LEVEL

James

Michael

1

Bob

James

2

Stacy

James

2

Ricky

James

2

Richard

James

2

Jones

James

2

Stan

Jones

3

Mathew

Richard

3

Perry

Stacy

3



 

 

Explanation:

 

START WITH   Specifies the root of the hierarchy, i.e. where to start from.

 

Here, MANAGER= James  gives the starting point for the hierarchical query.

 

CONNECT BY PRIOR  explains the relationship between the parent and the child.

 

It connects to the next level using EMPNAME = MANAGER. i.e. it connects to the next level Employee, to whom

 EMPNAME  is  MANAGER  to. Thus it goes down the levels  recursively.

PRIOR   This is used to achieve the recursive condition.




 

 

Now, what if you want to find all Direct and Indirect managers of James?

 

We just need to reverse the direction of the query. And it s simple.

Just change the sides of EMPNAME and MANAGER. That s it.

 

 

SELECT EMPNAME, MANAGER, LEVEL

FROM EMPLOYEE

START WITH MANAGER= James 

CONNECT BY PRIOR MANAGER= EMPNAME

 

 

EMPNAME

MANAGER

LEVEL

James

Bastin

1

Stephen

John

4

John

Gates

5

Mike

Stephen

3

Bastin

Mike

2

Gates

 

6

 

 

Note: Here the Level starts from James, since he is the root. This Level only indicates the relative position of others to the Root.

This has nothing to do with the Level of a Manager or an employee.



Oracle PL/SQL Table versus Nested Table, differences between PL/SQL and Nested Tables

Read Next:

Oracle PL/SQL Table & Nested Table: Insert data - Nested Table & PL/SQL Table etc



   
Also See: Forum Updates: