I\'m currently having some trouble understanding and writing recursive queries. I understand that recursive queries are used to search through hierarchies of information, bu
If I wanted to write a recursive query that travelled up this family tree, collecting all parents until origin, how should I go about this?
Use a hierarchical query and the SYS_CONNECT_BY_PATH( column_name, delimiter ) function:
Oracle 18 Setup:
create table family_tree (
child varchar(10),
parent varchar(10)
);
INSERT INTO family_tree ( child, parent )
SELECT 'B', 'A' FROM DUAL UNION ALL
SELECT 'C', 'B' FROM DUAL UNION ALL
SELECT 'D', 'C' FROM DUAL UNION ALL
SELECT 'E', 'D' FROM DUAL UNION ALL
SELECT 'F', 'C' FROM DUAL;
Query 1:
SELECT SYS_CONNECT_BY_PATH( parent, ' -> ' ) || ' -> ' || child AS path
FROM family_tree
START WITH parent = 'A'
CONNECT BY PRIOR child = parent;
Results:
PATH
-------------------------
-> A -> B
-> A -> B -> C
-> A -> B -> C -> D
-> A -> B -> C -> D -> E
-> A -> B -> C -> F