I am using postgresql. I have the table as like below
parent_id child_id
----------------------
101 102
103 104
104 105
105 106
I want to write a sql query which will give the final parent of input.
i.e suppose i pass 106 as input then , its output will be 103.
(106 --> 105 --> 104 --> 103)
Use
WITH RECURSIVE
to create a Common Table Expression (CTE). For the non-recursive term, get the rows in which the child is immediately below the parent:For the recursive term, you want the children of these children.
You can filter the children when querying the CTE:
Here's a complete example. First the
DDL
:...and some data...
This performs a recursive query on every id in node:
This gets all of the descendents WHERE node.id = 1:
The following will get the path of the node with id 4:
And let's assume you want to limit your search to descendants with a
depth
less than three (note thatdepth
hasn't been incremented yet):I'd recommend using an
ARRAY
data type instead of a string for demonstrating the "path", but the arrow is more illustrative of the parent<=>child relationship.