From time to time I find myself writing a hierarchial query in Oracle DB. It helps me a lot when I need to understand hierarchial data, mostly residesĀ in the source systems of the Datawarehouse. Yesterday I've seen that a lot of my colleagues haven't heard about these kind of queries, even the most experienced ones. So here is a tiny tutorial for this subject which you can go back to any time. The important thing here is that you'll know that these kind of queries exists even if you'll google it the next time you'll need it (search for "
start with" or "
connect by").
Let's say you have a table which looks like this:
| Key |
Father |
Description |
| 1 |
10 |
Renault |
| 2 |
20 |
Jambo |
| 3 |
20 |
Airbus |
| 4 |
10 |
Hyundai |
| 5 |
10 |
Toyota |
| 6 |
10 |
Honda |
| 7 |
20 |
F16 |
| 8 |
20 |
F15 |
| 9 |
10 |
Alpha Romeo |
| 10 |
-1 |
Cars |
| 20 |
-1 |
Airplanes |
| -1 |
-99 |
Transportation |
You want to see the data in a tree form, meaning that you'll see Renault, its parent, its grandparent and so on. All you need to write is the following query:
select * from MyTable
start with KEY = 2
connect by prior FATHER = KEY
That's it. The result is:
| Key |
Father |
Description |
| 1 |
10 |
Renault |
| 10 |
-1 |
Cars |
| -1 |
-99 |
Transportation |
Note that the recursion stops only when it cannot find the next parent. In addition, many times you'll want only one row from the tree (the root, its son or some other criteria). In this case you can simply add a where clause to the query.
Unfortunately, doing the same with SQL Server is much more
difficult (tell me if I'm wrong).
Enjoy.