2

Currently in one of our products we have a query with logic as explained below:

create table temp (emp_id varchar2(3), manager_id varchar2(3) )

Data :

E10 E20
E20 E50
E30 E50
E50 E90

Query:

select *
from Temp
    Start with EMP_ID = 'E90'
    Connect by Prior EMP_ID = MANAGER_ID and EMP_ID != MANAGER_ID
order by EMP_ID

I understand the concept of the query [& connect by] which is that we need to fetch all the children records of the employee specified including the current employee record. I have doubts about the need of adding EMP_ID != MANAGER_ID in the end.

The question is why was it added & in what situation will it be useful [if any].

1 Answer 1

3

The last condition does not apply to your data, but it is very important to avoid infinite recursion.

To illustrate this point, consider what would happen if you added another line to your table:

E40 E40

If you start with E40 instead of E90, Oracle would spin into an infinite recursion without EMP_ID != MANAGER_ID condition, because E40 would connect back to E40.

Note that a better approach to writing this query is to use NOCYCLE option instead of coding in an explicit check:

SELECT *
FROM Temp
    START WITH EMP_ID = 'E90'
    CONNECT BY NOCYCLE PRIOR EMP_ID = MANAGER_ID
ORDER BY EMP_ID
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.