Skip to content
Advertisement

Sql query to select all the sub items in the same table

I have a table in which one column depends another column. The table I have some what resembles the below

FolderId | ParentFolderID | Name
1        |  null          | ParentFolder 
2        |  1             | Test1
3        |  2             | Test2
4        |  3             | Test3
5        |  null          | Test4
6        |  null          | Test5
7        |  6             | Test6
8        |  5             | Test7

I need to filter out the Parent Folder Id’s which points out the root folderID 1. And the output should be like the below table:

FolderId | ParentFolderID |Name
1        |  null          |ParentFolder
2        |  1             |Test1
3        |  2             |Test2
4        |  3             |Test3

Thanks & Regards,

Advertisement

Answer

Try below query:

WITH CTE1 AS
(
SELECT *
FROM Table1
WHERE ParentFolderID IS NULL
AND FolderID = 1
UNION ALL
SELECT A.*
FROM Table1 A
INNER JOIN CTE1 C
ON A.ParentFolderID = C.FolderID
)
SELECT * FROM CTE1;

dbfiddle Link

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement