Some time we save parent and child records in a single table. We have a key like ParentId, all those records that are not child of any record they have ParentId equal to zero or NULL. All those records which are children of a particular record must have ParentId equal to the Id of that particular record. For example we have table like below.
Table Name: tblCategories
Columns:
Id INT
Name VARCHAR(200)
ParentId INT
if we have data in this table like below
Id=1 Name=Hardware and ParentId=NULL
Id=2 Name=Software and ParentId=NULL
above are parent records because they have ParentId=NULL.
Following are child records
Id=3 Name=Mouse and ParentId=1
Id=4 Name=Keyboard and ParentId=1
Id=5 Name=Web Applications and ParentId=2
Id=6 Name= Mobile Applications and ParentId=2
Id=7 Name= Monitor and ParentId=1
Now we want to query this data in such a way that, first parent record appears then all its child, then second parent record and then all its child or in other words we want the result like below
ID |
Name |
Parent Id |
1 |
Hardware |
NULL |
3 |
Mouse |
1 |
4 |
Keyboard |
1 |
7 |
Monitor |
1 |
2 |
Software |
NULL |
5 |
Web Applications |
2 |
6 |
Mobile Applications |
2 |
Then write the query like below
WITH result AS(
SELECT *
FROM tblCategories
UNION ALL
SELECT t.*
FROM tblCategories t INNER JOIN
result r ON t.ParentId = r.Id
)
SELECT distinct *
FROM result
Tip: You can get categories using this technique to show in navigational menus or where to show records in table format on a webpage just check the ParentId of each record if it is not null then give it some left padding and you are done.