We’ve got an Oracle self-referencing table to represent a hierarchy similar to:
THING
---------
ID
PARENT_ID
NAME
SOME_DATA
The top-level THING has a null PARENT_ID.
I’d like to be able to select from this table and order my data by each row’s position in the hierarchy (from top to bottom) and then by name such that the data set:
ID PARENT_ID NAME SOME_DATA
1 null top null
2 1 cat null
3 1 dog null
4 2 frog null
5 1 bird null
6 2 fish null
… becomes:
ID PARENT_ID NAME SOME_DATA
1 null top null
5 1 bird null
2 1 cat null
6 2 fish null
4 2 frog null
3 1 dog null
When I started typing this question, I was curious as to any whether or not there was a way to do this without adding a LEVEL column to the table but now I’m not even certain it can be done by adding that column.
A ‘no’ answer is perfectly acceptable here as I’m already resigned to the fact that I’m going to have to do this in my Java code.
Instead of using
LEVELand trying to manage the results in a clever way, it’s possible to useSTART WITHandORDER SIBLINGS BYto get the result you’re looking for:SQL Fiddle
Results:
This chains through the hierarchy, starting with the root (
parent_id IS NULL) and orders the results.