In Oracle:
SELECT LEVEL, Id, Name, LPAD(' ', LEVEL) || Name AS IndentedName
FROM Categories
START WITH
ParentID IS NULL
CONNECT BY
ParentID = PRIOR Id
ORDER SIBLINGS BY
Name
You can use IndentedNameor create custom formatting based on pseudocolumn LEVEL(it shows the depth of each category)
PS This is an idea to baduse NULLas the parent’s main identifier, since you cannot use the index to access it. Use instead 0.
Update:
SQL Server:
WITH q (id, parentid, name, level, bc) AS
(
SELECT id, parentid, name, 1, CAST(ROW_NUMBER() OVER (ORDER BY name) AS VARCHAR(MAX))
FROM Categories
WHERE ParentID IS NULL
UNION ALL
SELECT c.id, c.parentid, c.name, q.level + 1, q.bc + '.' + CAST(ROW_NUMBER() OVER (ORDER BY c.name) AS VARCHAR(MAX))
FROM q
JOIN Categories c
ON c.parentId = q.id
)
SELECT *
FROM q
ORDER BY
bc
Oracle, SQL Server NULL , NULL .