Sub topic 6
Sorting within branches with ORDER SIBLINGS BY
This chapter assumes you can already write a top-down query with START WITH, CONNECT BY PRIOR and LEVEL, and that you have seen the LPAD indentation trick. Here you learn how to control the order of rows inside each branch without breaking the tree layout.
Why a plain ORDER BY breaks the tree
A hierarchical query returns rows in tree order by default. Oracle walks the tree depth first, so each child appears right after its parent. That order depends on how Oracle happens to read the table, so you can't predict how siblings are arranged. Siblings are rows that share the same parent.
The obvious fix is an ORDER BY, but it sorts the whole result set after the tree walk is finished. The parent-child layout is lost.
Use this small table to see the difference.
CREATE TABLE staff (
id NUMBER PRIMARY KEY,
name VARCHAR2(20) NOT NULL,
boss_id NUMBER REFERENCES staff (id),
salary NUMBER NOT NULL
);
INSERT INTO staff VALUES (1, 'Ada', NULL, 9000);
INSERT INTO staff VALUES (2, 'Zoe', 1, 7000);
INSERT INTO staff VALUES (3, 'Bob', 1, 7000);
INSERT INTO staff VALUES (4, 'Carl', 2, 5000);
INSERT INTO staff VALUES (5, 'Abe', 2, 6000);
INSERT INTO staff VALUES (6, 'Dina', 3, 4000);
COMMIT;Ada manages Zoe and Bob. Zoe manages Carl and Abe. Bob manages Dina.
SELECT LPAD(' ', 2 * (LEVEL - 1)) || name AS org_chart
FROM staff
START WITH boss_id IS NULL
CONNECT BY PRIOR id = boss_id
ORDER BY name;The result is Abe, Ada, Bob, Carl, Dina, Zoe. The names are alphabetical, but the indentation no longer matches the structure. Abe is indented under nobody, and Ada, the root, appears second.
Sorting by LEVEL first doesn't help either. ORDER BY LEVEL, name lists all the managers, then all the people one level below them, and so on. That produces a level-by-level listing, not a tree.
The ORDER SIBLINGS BY clause
ORDER SIBLINGS BY sorts rows among siblings only. Oracle still walks the tree depth first, but at each parent it visits the children in the order you specify.
SELECT LPAD(' ', 2 * (LEVEL - 1)) || name AS org_chart,
LEVEL
FROM staff
START WITH boss_id IS NULL
CONNECT BY PRIOR id = boss_id
ORDER SIBLINGS BY name;The output is:
| org_chart | LEVEL |
|---|---|
| Ada | 1 |
| Bob | 2 |
| Dina | 3 |
| Zoe | 2 |
| Abe | 3 |
| Carl | 3 |
Under Ada, Bob comes before Zoe. Under Zoe, Abe comes before Carl. Every child stays directly beneath its own parent.
The numbers in the diagram are the row positions in the result. Oracle finishes the whole Bob branch (rows 2 and 3) before it moves to Zoe (row 4).
How the sort is applied
Think of the clause as a sort that restarts at every parent. Oracle compares only rows that have the same parent. It never compares Dina, who works under Bob, with Abe, who works under Zoe. Their position is decided by where their parents sit.
This has several consequences:
- Each
START WITHrow is a sibling of the other root rows. If your query returns several roots,ORDER SIBLINGS BYsorts those roots too. - The sort keys are ordinary expressions. You can use columns you don't select, functions such as
UPPER(name), andCASEexpressions. - The usual modifiers apply:
ASC,DESC,NULLS FIRSTandNULLS LAST. - Sort keys can use the current row's columns and the hierarchical pseudocolumns. They are evaluated against each sibling row, not against its parent.
Multiple keys and descending order
You can list several sort keys, exactly as in a normal ORDER BY. This query puts the best-paid people first within each branch and uses the name to break ties.
SELECT LPAD(' ', 2 * (LEVEL - 1)) || name AS org_chart,
salary
FROM staff
START WITH boss_id IS NULL
CONNECT BY PRIOR id = boss_id
ORDER SIBLINGS BY salary DESC, name;Bob and Zoe both earn 7000, so the name decides: Bob first. Under Zoe, Abe (6000) comes before Carl (5000). The row order is Ada, Bob, Dina, Zoe, Abe, Carl.
The salary sort never moves Dina above Bob, even though Dina earns less than Zoe and more than nobody. Sibling sorting cannot reorder rows across branches.
Limits and common errors
ORDER SIBLINGS BY replaces the ORDER BY in a query block. You can't write both in the same block, because a query block takes one ordering clause.
Oracle also rejects ORDER SIBLINGS BY in places where the tree order can't survive, such as with GROUP BY or DISTINCT. The error is ORA-30929. The aggregation query from a later chapter, which groups by CONNECT_BY_ROOT, can't be sorted this way. If you need to aggregate and keep a tree layout, put the aggregation in an outer query and carry a sort key through, for example a SYS_CONNECT_BY_PATH string.
Here is a pattern that does that. It assigns each row a sequence number in tree order, then sorts by that number.
SELECT t.*
FROM (
SELECT name, LEVEL AS lvl, ROWNUM AS tree_pos
FROM staff
START WITH boss_id IS NULL
CONNECT BY PRIOR id = boss_id
ORDER SIBLINGS BY name
) t
ORDER BY t.tree_pos;ROWNUM is assigned before the ORDER SIBLINGS BY sort is applied in some plans, so check the output on your version before you depend on this. A safer approach for a guaranteed order is a path key built with SYS_CONNECT_BY_PATH and sorted in the outer query.
Choosing between sibling sorting and a path sort
You can also get a tree order by sorting on a full path string.
SELECT LPAD(' ', 2 * (LEVEL - 1)) || name AS org_chart
FROM staff
START WITH boss_id IS NULL
CONNECT BY PRIOR id = boss_id
ORDER BY SYS_CONNECT_BY_PATH(name, '/');For simple names this gives the same order as ORDER SIBLINGS BY name, but it differs in important ways.
| Aspect | ORDER SIBLINGS BY | ORDER BY on a path |
|---|---|---|
| Tree layout kept | Always | Only if the path sorts correctly |
| Sort key | Any expression | A string you build |
| Compatible with GROUP BY | No | Yes, in an outer query |
| Cost | Sort done during the walk | Sort on the full result |
The path sort can go wrong. With / as the separator, Ann/Bob sorts before Ann-Lee/Bob only if / sorts lower than - in your character set, which isn't the order you might expect. Sorting by numbers as text has the same problem, because 10 sorts before 9. ORDER SIBLINGS BY has no such problem, because it compares the real values.
Stable output in practice
If two siblings tie on every sort key, Oracle can return them in either order, and the order may change between runs. Add a unique column, such as the primary key, as the last key to make the output repeatable.
SELECT LPAD(' ', 2 * (LEVEL - 1)) || name AS org_chart
FROM staff
START WITH boss_id IS NULL
CONNECT BY PRIOR id = boss_id
ORDER SIBLINGS BY salary DESC, name, id;Exercises
Exercise
A query returns an employee tree with ORDER BY last_name. The names are alphabetical, but the indentation looks scrambled. Why, and what clause fixes it?
Show answer
ORDER BY sorts the entire result after the tree walk, so children are separated from their parents. Replace it with ORDER SIBLINGS BY last_name, which sorts only the rows that share a parent and keeps each child under its parent.
Exercise
Using the staff table, write a query that shows the tree with the lowest-paid person first within each branch, and makes the result repeatable when salaries tie. What order do the rows come back in?
Show answer
Use ORDER SIBLINGS BY salary, name, id after START WITH boss_id IS NULL CONNECT BY PRIOR id = boss_id. Under Ada, Bob and Zoe both earn 7000, so the name puts Bob first. Under Zoe, Carl (5000) comes before Abe (6000). The rows are Ada, Bob, Dina, Zoe, Carl, Abe.