Introduction to Hierarchical and alphabetical sorting
To sort the data hierarchically and alphabetically means sorting a tree using depth-first search algorithm and selecting nodes with the same parent in the alphabetical order of their names.
The hierarchical sorting along with the level of nesting is a good way to emulate an expanded tree or a table of a book's contents using just a flat list of objects without the necessity to build a tree of objects.
Just fetch the records, sort them hierachically and alphabetically, indent each record n times ( where n is the level of nesting), and you'll get the expanded tree for UI and reports.
Two approaches
There are several approaches to structure a relational database to store the hierarchical data. The one, which is being used more frequently, is the Id-ParentId approach.
The Id-ParentId approach has a few drawbacks that make it necessary to seek alternative methods of storing hierarchical data.
The most difficult and expensive tasks in Id-ParentId approach are those which require recursive methods. For example -
- find all descendants,
- find all ancestors,
- calculate the level of nesting,
- sort flat records hierarchically and then alphabetically.
As a response to these difficulties, Microsoft added the HierarchyId data type to SQL Server since version 2008.
The HierarchyId data type,
- helps find descendants and ancestors without recursion,
- has fast GetLevel() method,
- contains the information about a node position in hierarchy,
- contains the information about a node order within its parent children.
If you want to build a clustered index on HierarchyId, then all the node-records will physically be stored in the order in which they are most frequently fetched.
But the HierarchyId data type still has drawbacks, which are the trade-offs for its useful properties,
- Impossibility to use HierarchyId as a foreign key to a parent, i.e. self-referencing; (actially a foreign key to a parent can be substituted with PERSISTED REFERENCES as described in this article, but all the pros and cons of such a solution are waiting for their researchers)
- Difficult ways to generate HierarchyId for added and changed records to keep required order, SQL Server does not do this automatically, it is up to programmer to manage it.
- Difficult use of the HierarchyId as a primary and foreign key: it may regularly change,
- It has no corresponding type in JavaScript (for example).
So what to choose: Id-ParentId or HierarchyId?
An acceptable solution to this dilemma of choice may be the combination of two approaches: Id-ParentId and HierarchyId.
This combination will allow us to,
- Use Id as an integer, ever increasing and unchangeable primary key,
- Use ParentId as a self-referencing foreign key,
- Use HierrarchyId to keep the records physically sorted in hierarchical and alphabetical order.
This article describes the way to unite the both approaches and ensure their normal operation.
Some Facts about HierarchyId
Column and field names in this article and source code,
- Hid — column of HierarchyId data type
- HidPath — string column for human-readable path of HierarchyId
- HidCode — a binary presentation of HierarchyId converted to a string and without leading 0x.
To human-readable format
The HierarchyId data type is a materialized path encoded into binary format. It can be decoded to human-readable string path with ToString() method,
- select Hid, Hid.ToString() as HidPath, Hid.GetLevel() as Level from Folders order by Hid;
- -- Note: ToString() and GetLevel() are case sensitive!!!
0x58 /1/ 1
0x5AC0 /1/1/ 2
0x5AD6 /1/1/1/ 3
0x5AD6B0 /1/1/1/1/ 4
0x5AD6B580 /1/1/1/1/1/ 5
0x5AD6B680 /1/1/1/1/2/ 5
0x5AD6B780 /1/1/1/1/3/ 5
0x5AD6D0 /1/1/1/2/ 4
0x5AD6D580 /1/1/1/2/1/ 5
0x5AD6D680 /1/1/1/2/2/ 5
0x5AD6D780 /1/1/1/2/3/ 5
...
From human-readable format
The opposite operation from string path to binary format works also.
- declare @Hid hierarchyid = '/1/1/1/1/3/';
- select @Hid
Results
------------
0x5AD6B780
The above is the implicit conversion. HierarchyId has the explicit Parse() method, although a call format is a little strange.
- declare @Hid hierarchyid = hierarchyid::Parse('/1/1/1/1/3/');
- -- Parse() is case sensitive!!!
- select @Hid
Results
------------
0x5AD6B780
Tricky numbering system of paths
The interesting thing about the HierarchyId is the way how it manages the numeration of a node inserted between two other nodes.
To get a Hid for a new node, HierarchyId uses GetDescendant() method from parent Hid and uses two Hids of nodes between which the new has to be inserted.
- declare @Parent hierarchyid = 0x;
- print @Parent.GetDescendant('/1/', '/2/').ToString() -- /1.1/
- print @Parent.GetDescendant('/1/', '/1.1/').ToString() -- /1.0/
- print @Parent.GetDescendant('/1/', '/1.0/').ToString() -- /1.-1/
- print @Parent.GetDescendant('/1/', '/1.-1/').ToString() -- /1.-2/
- print @Parent.GetDescendant('/1.1/', '/2/').ToString() -- /1.2/
- print @Parent.GetDescendant('/1.2/', '/2/').ToString() -- /1.3/
- print @Parent.GetDescendant('/1.3/', '/2/').ToString() -- /1.4/
- print @Parent.GetDescendant('/1.3/', '/1.4/').ToString() -- /1.3.1/
- print @Parent.GetDescendant('/1.2.3.4.5.6.7.8/', '/1.2.3.4.5.6.7.9/').ToString()
-- /1.2.3.4.5.6.7.8.1/ - -- by the way
- declare @Hid hierarchyid = '/1.2.3.4.5.6.7.8.1/';
- select @Hid; -- 0x63A08A49A85258
- declare @Hid hierarchyid = '/-1.-2.-3.-4.-5.-6.-7.-8.-1234567890/';
- select @Hid; -- 0x41F8F87A3C1D8E87216D9A81A73A
- -- special cases with null
- print @Parent.GetDescendant(null, null).ToString() -- /1/
- print @Parent.GetDescendant('/1/', null).ToString() -- /2/
- print @Parent.GetDescendant(null, '/1/').ToString() -- /0/
Why do we need binary encoding?
If we can build a string path, why do we need this HierarchyId binary encoding?
Could we just sort the hierarchical data by this string path?
Look at this example,
- select hierarchyid::Parse('/1/') as Hid, '/1/' as HidPath union all
- select hierarchyid::Parse('/2/') , '/2/' union all
- select hierarchyid::Parse('/10/') , '/10/'
- order by HidPath;
Results
--------------
Hid HidPath
----- --------
0x58 /1/
0xAA /10/
0x68 /2/
The same query but ordered by Hid makes the right sorting:
Results
--------------
Hid HidPath ----- -------- 0x58 /1/ 0x68 /2/ 0xAA /10/
Microsoft uses the sophisticated algorithm of HierarchyId to encode the string path so that it can be used for hierarchical sorting just by the Hid column value.
The Solution
Master and slave
So, let's combine Id-ParentId self referencing approach with HierarchyId.
The Id-ParentId part will be responsible for Id primary key, self-reference ParentId foreign key and be the leading, or master. The HierarchyId part will be a calculated field, or slave.
Of course, Hid as a persistent calculated field is the denormalization. But this is a conscious step and a compromise for the advantages of HierarchyId.
The best place and moment to calculate the HierarchyId and keep it in coordinated state is a stored procedure and while saving the node.
User Catalog for experiments
Let's imagine we have a multi-user application where each of user keeps its own Catalog. This Catalog keeps information in hierarchical Folders.
The table for these Folders might look like this,
- create table dbo.Folders
- (
- UserId int not null ,
- Hid hierarchyid not null ,
- Id int not null identity,
- ParentId int null ,
- Name nvarchar(50) not null ,
- constraint CU_Folders unique clustered (UserId asc, Hid asc),
- constraint PK_Folders primary key nonclustered (Id asc),
- constraint FK_Folders_UserId foreign key (UserId) references dbo.Users (Id),
- constraint FK_Folders_ParentId foreign key (ParentId) references dbo.Folders (Id)
- constraint CH_Folders_ParentId check (Hid = 0x and ParentId is null or Hid <> 0x and ParentId is not null)
- );
Note, that the clustered index is build on UserId and Hid, but the primary key is build on Id column.
This allows to keep all the records of the user's folders hierarchically sorted physically. And, at the same time, use the integer primary key as a foreign key for another tables and DTOs.
It is well known, that the hierarchy built on HierarchyId may have one root only.
Because the clustered key is the combination of UserId and Hid columns, a table dbo.Folders may have one root for each user.
The root node is mandatory, every user's catalog must have one, so the root is mostly a system record that is not edited by users.
Once the root node is a system record, every other nodes must have a parent and ParentId must be not null.
The best place to make calculation
As Microsoft states it here: "It is up to the application to generate and assign HierarchyId values in such a way that the desired relationship between rows is reflected in the values."
The best way to create and keep integrity and consistency of hierarchical data in our case is always use the same stored procedure to insert and update a Folder node.
A user-defined table type that represents saving Folder may serve as a parameter to the SaveFolder stored procedure,
- create type dbo.FolderTableType as table
- (
- Id int not null primary key clustered,
- ParentId int not null ,
- Name nvarchar(50) not null
- );
And here is the SaveFolder stored procedure itself,
- create procedure dbo.SaveFolder
- @Folder dbo.FolderTableType readonly
- as
- begin
- set nocount on;
- begin -- variable declaration
- declare
- @ParamId int ,
- @ParentId int ,
- @UserId int ,
- @ParentHid hierarchyid ,
- @StartTranCount int ,
- @OldHid hierarchyid ,
- @NewHid hierarchyid ;
- declare @FolderIds table (
- InsertedId int not null,
- OldHid hierarchyid null,
- NewHid hierarchyid null
- );
- end;
- begin try
- set @StartTranCount = @@trancount;
- if @StartTranCount = 0
- begin
- set transaction isolation level serializable;
- begin transaction;
- end;
- begin -- init variables and lock parent for update
- select
- @ParamId = Id,
- @ParentId = ParentId
- from
- @Folder;
- select
- @UserId = UserId,
- @ParentHid = Hid
- from
- dbo.Folders
- where
- Id = @ParentId;
- end;
- begin -- save the @Folder
- merge into dbo.Folders as target
- using
- (
- -- full join in this 'select' allows to see picture as if
- -- the change already applied,
- -- thus coalesce(t.Id, f.Id) take new value
- -- if t.Id exists and old value if not
- select
- -- LAG and LEAD functions help to find the previous
- -- and next Hid values if to sort by Name
- Hid = @ParentHid.GetDescendant (
- LAG (case when t.Id is null then f.Hid end)
- over(order by coalesce(t.Name, f.Name)),
- LEAD(case when t.Id is null then f.Hid end)
- over(order by coalesce(t.Name, f.Name))
- ),
- Id = coalesce( t.Id , f.Id ),
- ParentId = coalesce( t.ParentId , f.ParentId ),
- Name = coalesce( t.Name , f.Name )
- from
- (select * from dbo.Folders where ParentId = @ParentId) f
- full join @Folder t on t.Id = f.Id
- )
- -- for LAG and LEAD functions we need all children of the @ParentId
- -- but for merge we need the Folder where source.Id = @ParamId
- as source on source.Id = @ParamId and source.Id = target.Id
- -- target.UserId = @UserId here just to make sure
- -- that we do not reparent a Folder to another user
- when matched and target.UserId = @UserId then
- update set
- Hid = source.Hid ,
- Name = source.Name ,
- ParentId = source.ParentId
- -- source.Id = 0 here just to make sure that we insert a new Folder
- -- and not already deleted one
- -- not matched Id can be deleted by another user and we can try to add it again
- when not matched by target and source.Id = 0 then
- insert (
- UserId ,
- Hid ,
- ParentId ,
- Name )
- values (
- @UserId ,
- source.Hid ,
- source.ParentId ,
- source.Name )
- output
- inserted.Id ,
- deleted.Hid ,
- inserted.Hid
- into @FolderIds (
- InsertedId ,
- OldHid ,
- NewHid );
- end;
- begin -- reparent children
- -- saving folder might change its ParentId
- -- in that case Hid of all its children should reflect the change also
- select top 1 @OldHid = OldHid, @NewHid = NewHid from @FolderIds;
- if @OldHid <> @NewHid
- update dbo.Folders set
- Hid = Hid.GetReparentedValue(@OldHid, @NewHid)
- where
- UserId = @UserId
- and Hid.IsDescendantOf(@OldHid) = 1;
- end;
- if @StartTranCount = 0 commit transaction;
- end try
- begin catch
- if xact_state() <> 0 and @StartTranCount = 0 rollback transaction;
- declare @ErrorMessage nvarchar(4000) = dbo.GetErrorMessage();
- raiserror (@ErrorMessage, 16, 1);
- return;
- end catch;
- end;

Join the conversation! Your thoughts help the community grow.