liveBook · Manning

Hierarchyid

As explained in 100 SQL Server Mistakes and How to Avoid Them

hierarchyid is a SQL Server system data type that represents positions in a hierarchical structure and provides methods for hierarchical operations.

Mistake: writing a new recursive CTE for every hierarchy request. A self-referenced employee table can handle simple queries, but deeper variations become difficult to maintain. SQL Server’s hierarchyid type stores each position in a hierarchy and supplies methods for traversing it. section 3.3 section 3.6

A hierarchyid path uses slash-delimited levels: / is the root, /1/ and /2/ identify children, and deeper paths identify descendants such as /1/2/1/. SQL Server stores these paths internally as bit strings and displays them as hexadecimal values unless ToString() is called. section 3.3

Use the type and its methods for common organizational queries:

  • Add a nullable hierarchyid column, then populate paths from the root through each employee’s manager relationship. section 3.3
  • Call ToString() to inspect readable paths, IsDescendantOf() to return direct and indirect reports, and GetAncestor() to find an employee’s managers. section 3.3
  • Use GetLevel() when comparing employees at the same organizational depth, such as Amy Fry’s organizational siblings. section 3.3

Sanjay Gupta’s reports

Retrieve a manager’s hierarchyid, then filter employees with IsDescendantOf(@Manager) = 1 to return direct and indirect reports without writing a traversal CTE for that query. section 3.3

Figure 3.2 MagicChoc management org chart

Use the management org chart to relate slash-delimited hierarchy paths to positions in a concrete organization. section 3.3

How 100 SQL Server Mistakes and How to Avoid Them covers it

How deep it goes
Explains path modeling, internal representation, column population, and traversal methods through executable employee queries.
Examples
Uses a management org chart and employee queries for descendants, ancestors, hierarchy levels, and generated hierarchy paths.
What it assumes
Assumes an employee table with manager relationships and teaches hierarchy paths and traversal from the organizational model.
What you can do after
Apply via SQL Server T-SQL to model hierarchies and query descendants, ancestors, and same-level employees.
How it connects
Connects hierarchyid with recursive CTEs, self-referenced tables, organizational hierarchies, and manager relationships.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 SQL Server Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.