connect by prior oracle

Potinos picture Potinos · Oct 5, 2012 · Viewed 8.1k times · Source

I have a table that contains an hierarchic element

Table :

A       B 
P1      -
P2      P1
C1      P2
C2      P2

B is a foreign key coming from the same table

The query is :

SELECT level niveau, A
from table parent, table child
START WITH A IN
( 'P0','P1','C2')
CONNECT BY PRIOR  A= B

The result

1 P1
1 P2
  2 C1
  2 C2
1 C2

Why the "2 C2" apears?

The result desired is in spite of it's not the correct, i:

1 P1
1 P2
  2 C1
1 C2

Answer

ivanhoe1982 picture ivanhoe1982 · Oct 5, 2012

Connect by condition is evaluated first, start with later. In your case C2 is both a child of P2 AND a root of the hierarchy. This is why it appears in your result twice.

From Oracle Documentaion

Oracle processes hierarchical queries as follows:

A join, if present, is evaluated first, whether the join is specified in the FROM clause or with WHERE clause predicates.

The CONNECT BY condition is evaluated.

Any remaining WHERE clause predicates are evaluated.

Oracle then uses the information from these evaluations to form the hierarchy using the following steps:

Oracle selects the root row(s) of the hierarchy--those rows that satisfy the START WITH condition.

Oracle selects the child rows of each root row. Each child row must satisfy the condition of the CONNECT BY condition with respect to one of the root rows.

Oracle selects successive generations of child rows. Oracle first selects the children of the rows returned in step 2, and then the children of those children, and so on. Oracle always selects children by evaluating the CONNECT BY condition with respect to a current parent row.

If the query contains a WHERE clause without a join, then Oracle eliminates all rows from the hierarchy that do not satisfy the condition of the WHERE clause. Oracle evaluates this condition for each row individually, rather than removing all the children of a row that does not satisfy the condition.

Oracle returns the rows in the order shown in Figure 9-1. In the diagram, children appear below their parents. For an explanation of hierarchical trees,