I have sql table like below. I have to show it in tree view
id parentid name 1 NULL outlook 2 1 overcast 3 1 rainy 4 1
WITH q AS ( SELECT * FROM mytable WHERE ParentID IS NULL -- this condition defines the ultimate ancestors in your chain, change it as appropriate UNION ALL SELECT m.* FROM mytable m JOIN q ON m.parentID = q.ID ) SELECT * FROM q