Sub topic 14
CONNECT BY compared with recursive WITH
This chapter assumes you can write a basic START WITH ... CONNECT BY PRIOR query and know LEVEL, ORDER SIBLINGS BY, pruning, and NOCYCLE. You will see the same org-chart query written both ways. You will then learn which CONNECT BY features have a recursive WITH equivalent and which choice fits which job.
Two ways to walk a tree
Oracle has two mechanisms for hierarchical queries:
CONNECT BYis Oracle's own syntax. It has existed for decades and has built-in pseudocolumns and operators.- Recursive subquery factoring is a recursive
WITHclause. It is ANSI-style, and Oracle supports it from 11g Release 2.
Both read the same self-referencing employees table, and both can return the same rows. They differ in how you express the walk, which helpers come built in, and how much you can do inside the recursive step.
The same query, twice
Here is the basic top-down query in CONNECT BY form.
SELECT employee_id, last_name, manager_id, LEVEL
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id;Here is the recursive WITH form.
WITH org (employee_id, last_name, manager_id, lvl) AS (
SELECT employee_id, last_name, manager_id, 1
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.employee_id, e.last_name, e.manager_id, o.lvl + 1
FROM employees e
JOIN org o ON e.manager_id = o.employee_id
)
SELECT employee_id, last_name, lvl
FROM org;A recursive WITH has two parts joined by UNION ALL:
- The anchor member is the first
SELECT. It plays the role ofSTART WITHand produces the root rows. - The recursive member is the second
SELECT. It refers to the query name (org) and plays the role ofCONNECT BY. Each pass joins the rows found in the previous pass to the table and produces the next level.
Three details differ from what you may expect:
- Oracle needs the column list after the query name,
org (employee_id, ...). This is how Oracle knows the column names for the recursive reference. - You write
WITH, notWITH RECURSIVE. Oracle infers recursion from the self-reference. - You must maintain the depth yourself.
LEVELdoes not exist here, so you carry a counter column such aslvl.
Mapping the features
Most CONNECT BY features have a recursive WITH counterpart. Some you build by hand.
| Need | CONNECT BY | Recursive WITH |
|---|---|---|
| Choose root rows | `START WITH` | `WHERE` in the anchor member |
| Parent-child link | `CONNECT BY PRIOR parent = child` | join condition in the recursive member |
| Depth | `LEVEL` | your own counter, such as `o.lvl + 1` |
| Sort within branches | `ORDER SIBLINGS BY` | `SEARCH DEPTH FIRST BY ... SET` |
| Path from root | `SYS_CONNECT_BY_PATH` | carry a string column and concatenate |
| Root's value | `CONNECT_BY_ROOT` | carry the root value as a column |
| Leaf flag | `CONNECT_BY_ISLEAF` | no built-in; test for children with `NOT EXISTS` |
| Cycle handling | `NOCYCLE`, `CONNECT_BY_ISCYCLE` | `CYCLE ... SET ... TO ... DEFAULT ...` |
| Prune a branch | extra condition in `CONNECT BY` | extra condition in the recursive member's join |
| Generate numbers | `CONNECT BY LEVEL <= n` | recursive member with `WHERE x < n` |
Ordering a tree in recursive WITH
Without extra help, a recursive WITH returns rows in no guaranteed order. For a tree display, CONNECT BY gives you ORDER SIBLINGS BY. In recursive WITH you use the SEARCH clause, which adds a sequence column that you then sort by.
WITH org (employee_id, last_name, manager_id, lvl, path) AS (
SELECT employee_id, last_name, manager_id, 1,
CAST('/' || last_name AS VARCHAR2(4000))
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.employee_id, e.last_name, e.manager_id, o.lvl + 1,
o.path || '/' || e.last_name
FROM employees e
JOIN org o ON e.manager_id = o.employee_id
)
SEARCH DEPTH FIRST BY last_name SET seq
SELECT LPAD(' ', 2 * (lvl - 1)) || last_name AS org_chart,
lvl,
path
FROM org
ORDER BY seq;SEARCH DEPTH FIRST BY last_name SET seq visits each row's children before its next sibling, and it orders siblings by last_name. The seq column numbers the rows in that visiting order, so ORDER BY seq gives the same layout as ORDER SIBLINGS BY last_name.
The query also carries path by hand, where CONNECT BY would use SYS_CONNECT_BY_PATH(last_name, '/'). The CAST in the anchor member matters. If the anchor's string column is only as long as the literal expression, Oracle can reject the recursive member for a type or length mismatch as the string grows. Casting the anchor to a wide VARCHAR2 avoids that.
SEARCH BREADTH FIRST BY is also available. It numbers rows level by level, which has no direct CONNECT BY equivalent.
Cycles
In CONNECT BY you add NOCYCLE and can read CONNECT_BY_ISCYCLE. In a recursive WITH, a looping dataset recurses until Oracle raises an error. You prevent that with the CYCLE clause.
WITH org (employee_id, manager_id, lvl) AS (
SELECT employee_id, manager_id, 1
FROM employees
WHERE employee_id = 100
UNION ALL
SELECT e.employee_id, e.manager_id, o.lvl + 1
FROM employees e
JOIN org o ON e.manager_id = o.employee_id
)
CYCLE employee_id SET is_cycle TO 'Y' DEFAULT 'N'
SELECT employee_id, manager_id, lvl, is_cycle
FROM org;CYCLE employee_id tells Oracle to watch the employee_id value. When a row's employee_id already appears among its ancestors, Oracle sets is_cycle to 'Y' (the TO value) on that row and does not expand it further. All other rows get the DEFAULT value 'N'.
The two flags do not mark the same row:
CONNECT_BY_ISCYCLEis 1 on the row whose child is also one of its ancestors. It marks the row just before the loop closes.is_cyclefromCYCLEmarks the repeated row, the one that duplicates an ancestor.
When you use both SEARCH and CYCLE, write SEARCH first.
Pruning in each form
In CONNECT BY, a condition placed in the CONNECT BY clause prunes the whole branch below a failing row. In recursive WITH, the equivalent is a condition in the recursive member.
WITH org (employee_id, last_name, lvl) AS (
SELECT employee_id, last_name, 1
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.employee_id, e.last_name, o.lvl + 1
FROM employees e
JOIN org o ON e.manager_id = o.employee_id
WHERE e.salary > 5000
)
SELECT employee_id, last_name, lvl
FROM org;An employee who fails salary > 5000 is never produced by the recursive member. That means nobody below them is reached either, which matches CONNECT BY PRIOR employee_id = manager_id AND salary > 5000. A WHERE on the outer SELECT would remove only the single row, as it does with CONNECT BY.
Where recursive WITH is stronger
Recursive WITH is better in several situations:
- Standard SQL. The pattern is close to what PostgreSQL, SQL Server, and DB2 support, so the idea transfers even though details differ.
- Joins and computation in each step. The recursive member is a normal query that joins the previous level to other tables and computes new columns. You can accumulate running totals, such as a cost that multiplies down a bill of materials.
- Several parents or non-tree graphs. You control the join, so you can follow edges stored in a separate link table.
- Explicit breadth-first order.
SEARCH BREADTH FIRSTis built in.
Where CONNECT BY is stronger
CONNECT BY is better in other situations:
- Brevity. The basic query is three lines, with no column list or counter.
- Built-in helpers.
LEVEL,SYS_CONNECT_BY_PATH,CONNECT_BY_ROOT, andCONNECT_BY_ISLEAFreplace columns you would otherwise write and carry yourself. - Bottom-up walks. Moving
PRIORto the other side reverses direction in one change. In recursiveWITHyou reverse the join condition and choose the anchor row yourself. - Row generation and long-standing code.
CONNECT BY LEVEL <= nis the common Oracle idiom for number lists, and most existing Oracle code uses it.
Recursive WITH also has restrictions in its recursive member. It must reference the query name exactly once, and Oracle does not allow constructs such as DISTINCT or GROUP BY there. The two parts must also be joined with UNION ALL.
WITH n (x) AS (
SELECT 1 FROM dual
UNION ALL
SELECT x + 1 FROM n WHERE x < 10
)
SELECT x FROM n;This returns 1 through 10, the same as SELECT LEVEL FROM dual CONNECT BY LEVEL <= 10. The WHERE x < 10 is what stops the recursion. Without it, the query never terminates on its own.
Choosing between them
Both forms usually perform well on a table indexed on the parent column. On large trees, test both with your own data and compare execution plans.
Exercise
You write a recursive WITH over employees that starts at the top manager and joins each level on e.managerid = o.employeeid. You want the output in the same order as CONNECT BY with ORDER SIBLINGS BY last_name, and you want to stop safely if the data contains a loop. Which two clauses do you add after the WITH block's closing parenthesis, in what order, and what do you put in the final ORDER BY?
Show answer
Add SEARCH DEPTH FIRST BY lastname SET seq first, then CYCLE employeeid SET is_cycle TO 'Y' DEFAULT 'N'. SEARCH must come before CYCLE. The final SELECT then uses ORDER BY seq, so rows appear depth first with siblings sorted by last name.
Exercise
In a CONNECT BY query, LEVEL is built in. How do you get the depth in a recursive WITH, and what does the anchor member supply?
Show answer
You carry a counter column yourself. The anchor member supplies the starting value, usually 1 for root rows. The recursive member then computes the next value as o.lvl + 1, where o is the reference to the recursive query name.