Connect by clause to get the top of hierarchy

user2133005 picture user2133005 · Aug 7, 2013 · Viewed 14.6k times · Source

I am facing an issue while using the CONNECT BY clause in Oracle for finding hierarchical data. Let me give an example: A is my parent part which has child part B and B also has a child part C. When I am using the CONNECT BY clause I am able to get all the three levels but I only want the top most level, i.e. A.

Answer

Ed Gibbs picture Ed Gibbs · Aug 7, 2013

Oracle has a LEVEL pseudocolumn that you can use:

SELECT
  myTable.ID,
  myTable.ParentID
FROM myTable
WHERE LEVEL = 1
CONNECT BY PRIOR myTable.ID = myTable.ParentID

To find a top-level (root) value from any level, precede the column name with the CONNECT_BY_ROOT operator:

SELECT
  myTable.ID,
  myTable.ParentID,
  CONNECT_BY_ROOT myTable.ID AS "Top Level ID"
FROM myTable
CONNECT BY PRIOR myTable.ID = myTable.ParentID