I've successfully mananaged to understand how the connect by level works with the below example:
SELECT
level,
t.*
FROM
(
SELECT
'a' AS col1,
'b' AS col2
FROM
dual
UNION ALL
SELECT
'c',
'd'
FROM
dual
) t
CONNECT BY
level <= 3
However, I'm struggling to understand the 'start with' and 'prior' concepts and what use cases do they have in real life. Could someone please walk me through using the provided example?
If you have a parent/child relationship:
And you want to get the family tree starting from
band get all of the descendants then you can:Which outputs:
Level 1 starts with
bthen level 2 hasb's childcthen level 3 hasb's child's child (grandchild)dand they are all connected by the relationship that thePRIORchildis the (current)parent.More examples of how to get different relationships can be found in this answer.
As an aside, your example in the question is a little confusing as it is finding all paths to a depth of 3 recursions. If you show the paths it has taken through the data using
SYS_CONNECT_BY_PATHthen you get a better idea:Which outputs:
You get 14 rows because you get 2 rows at level 1 (one for each combination of input row) and then 4 rows at level 2 (one for each input row for each level 1 row) and then 8 rows at level 2 (one for each input row for each level 2 row) and your output is growing exponentially.
db<>fiddle here