I have a table with two columns: child
and parent
. This table represents a tree kind structure having multiple trees. Given any child, i need to find its root. In other words, I need to get the parent of that child, and then the parent of the parent and so on until it reaches the root of that child.
child parent
1 2
2 3
9 10
3 4
4 5
5 255
Here, we have two trees. One starts from 255(root) and ends at 1(leaf).
255 -> 5 -> 4 -> 3 -> 2 -> 1
. And the second one starts at 10 and ends at 9. For ex: if 3
is given then it needs to find the root which on this case would be 255.
I am really new to the SQL world. My idea would be to recursively traverse the parent
column for the child until if there is no entry in the child
column for some parent on the way and return that parent. Is there a way to do that in SQL, especially in postgres.?