Tag Archives: T-SQL

Hierarchical Data in SQL Part 2: Recursive Queries with an Adjacency List

In the first post of this series, we saw a simple table representing a real-world hierarchy and the simplest of queries on that data, and finished with the question: “What else might we do with this data?”

Maybe we need to know the chain of responsibility leading from a particular position up to the top of the organisation.
Or, perhaps we would like to report on a subsection of the tree – for example, listing everyone working directly or indirectly below the Financial Director.
And what if we want to see what this organisational structure looks like?

For all of these, we can use recursive queries.
Continue reading Hierarchical Data in SQL Part 2: Recursive Queries with an Adjacency List

Hierarchical Data in SQL Part 1: The Adjacency List

One of the most obvious examples of hierarchical data frequently stored in a database is the organisational hierarchy of employees and their managers.

Typically this follows a one-to-many parent-child relationship whereby each employee reports to a single manager above them, and may have zero or more employees below them who they manage.
This tree is likely to have a relatively shallow structure, perhaps no more than 10 levels deep even in an organisation of 100,000 employees.

The simplest method of storing and maintaining a tree of this type is for each record to include a reference to its parent.
You may see this referred to as an “Adjacency List Model”.
It is worth noting that an adjacency list is a type of Relationship Graph, and that our example is a special case in which we want the graph to form a tree structure.

Representing a tree in this way allows us to easily write simple queries to access the nodes immediately adjacent to a given node (above or below them in the hierarchy), but requires us to use recursion if we wish to query data spanning further levels of the tree.
Continue reading Hierarchical Data in SQL Part 1: The Adjacency List

Working With Hierarchical Data in SQL

Over a series of articles, I will be writing about and demonstrating some of the ways in which hierarchical data can be stored, queried and presented using SQL. The primary focus will be Microsoft SQL Server, followed by Oracle, but there may also be some sections dedicated to other platforms.

I will update this page with links to the subsequent posts as and when they are added.

Continue reading: