0

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.

Chris Williams
  • 11,647
  • 15
  • 60
  • 97

1 Answers1

2

Instead of using LEVEL and trying to manage the results in a clever way, it's possible to use START WITH and ORDER SIBLINGS BY to get the result you're looking for:

SQL Fiddle

SELECT t.*
FROM thing t
CONNECT BY PRIOR t.id = t.parent_id
START WITH t.parent_id IS NULL
ORDER SIBLINGS BY t.name

Results:

| 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) |

This chains through the hierarchy, starting with the root (parent_id IS NULL) and orders the results.

Ben
  • 1,902
  • 17
  • 17