How does Oracle identify "cycles" in a hierarchical query?
If it's documented, it's not done very well. Anyway, I think we found the correct and complete (and, really, pretty simple) answer in an OTN discussion: https://community.oracle.com/thread/3999985
Anyway: When you run a hierarchical query, for each row generated, Oracle will look at the columns that are operated upon by the PRIOR operator in the connect by
clause, and ONLY to those columns, to see if a newly generated row matches an already existing one.
This is why "select 5 from dual connect by level <= 100" works, even though it generates the same row 100 times. There is no cycle, because "cycle" only looks at columns preceded by PRIOR in CONNECT BY - and there are none.
This is also why you will often see things like connect by [other conditions here] and prior sys_guid() is not null
. sys_guid()
will never be null; but by adding it to connect by
, and very importantly with the PRIOR
operator, you make sure there will never be cycles (because each call is guaranteed to return a different value!) so you are free to break "infinite recursion" by conditions on level
or other means, but not by the identification of "cycles". (Due to this extra "column" to check, Oracle will never see a cycle.)