Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using CONNECT BY to get all parents and one child in Hierarchy through SQL query in Oracle

I was going through some previous posts on CONNECT BY usage. What I need to find is that what to do if I want to get all the parents (i.e, up to root) and just one child for a node, say 4.

It seems Like I will have to use union of the following two:-

 SELECT  * 
 FROM    hierarchy 
 START WITH id = 4
 CONNECT BY id = PRIOR parent
union
     SELECT  *
     FROM    hierarchy
     WHERE LEVEL =<2
     START WITH
     id = 4
     CONNECT BY
     parent = PRIOR id

Is there a better way to do this, some workaround that is more optimized?

like image 882
s khan Avatar asked Feb 27 '23 07:02

s khan


1 Answers

You should be able to do this using a sub-select (and DISTINCT) to find all children of 4:

Select Distinct *
From hierarchy
Start With id In ( Select id
                   From hierarchy
                   Where parent = 4 )
Connect By id = Prior parent

Using UNION you could at least remove the CONNECT BY from your second query:

  Select *
  From hierarchy
  Start With id = 4
  Connect By id = Prior parent
Union
  Select *
  From hierarchy
  Where parent = 4

Never use SELECT *, always name the columns you actually need. This makes your query easier to read, to maintain and to optimize.

like image 104
Peter Lang Avatar answered Mar 02 '23 02:03

Peter Lang