Advanced SQL (Part 2) Nataliya Bogushevskaya
Advanced SQL (Part 2) Nataliya Bogushevskaya
Hierarchical queries
Nataliya Bogushevskaya
2019
CONFIDENTIAL 1
HIERARCHICAL DATA
Hierarchical data is defined as a set of data items that are related to each
other by hierarchical relationships.
Hierarchical relationships exist where one item of data is the parent of another
item.
Examples of the hierarchical data that is commonly stored in databases include
the following:
• an organizational structure
• a file system
• a set of tasks in a project
• a graph of links between Web pages
CONFIDENTIAL 2
HIERARCHICAL DATA
ROOT
CONFIDENTIAL 3
WITH CONNECT BY
(ORACLE)
CONFIDENTIAL 4
CONNECT BY
• START WITH specifies the root row(s) of the hierarchy (not mandatory);
• PRIOR operator refers to the parent row;
• CONNECT BY specifies the relationship between parent rows and child rows of the
hierarchy.
CONFIDENTIAL 5
EXAMPLE
CONFIDENTIAL 6
EXAMPLE
CONFIDENTIAL 7
PRACTICE
CONFIDENTIAL 8
EXECUTION
CONFIDENTIAL 9
OPERATORS AND PSEUDOCOLUMNS
PRIOR
CONFIDENTIAL 10
OPERATORS AND PSEUDOCOLUMNS
LEVEL
• LEVEL – returns 1 for a root row, 2 for a child of a root, and so on.
CONFIDENTIAL 11
PRACTICE #1
CONFIDENTIAL 12
PRACTICE #2
CONFIDENTIAL 13
PRACTICE #3
Generate dates from now (sysdate) till the end of the year.
CONFIDENTIAL 14
PRACTICE #4
CONFIDENTIAL 15
PRACTICE #5
The table contains the ordered set or numbers, for example (3, 6, 8, 9, 11 , …).
Return three smallest missing numbers (4, 5, 7).
CONFIDENTIAL 16
PRACTICE #6
Table contains one row and one field. This field stores some arithmetical
expression with numbers, arithmetic signs and parenthesis’s. For example,
2*((5+7)+2*(2+3))*8)+9
Write a query that will return each symbol from the string as a separate row.
CONFIDENTIAL 17
PRACTICE #7
Income tax rate is some Banana Republic is changed very often. These changes are
reflected in TAX_RATE table:
• CHANGE_DATE - date when new tax rate is set.
• RATE - tax rate in percent.
Using TAX_RATE table, report rate value for each day between min(change_date) and
max(change_date).
CONFIDENTIAL 18
OPERATORS AND PSEUDOCOLUMNS
SYS_CONNECT_BY_PATH(column, delimiter)
For each employee of the 4th level list the full path from the root manager
CONFIDENTIAL 19
OPERATORS AND PSEUDOCOLUMNS
CONNECT_BY_ROOT
CONFIDENTIAL 20
PRACTICE
For each employee of the 4th level list the full path from and to the root manager
CONFIDENTIAL 21
OPERATORS AND PSEUDOCOLUMNS
CONNECT_BY_ISLEAF
CONFIDENTIAL 22
PRACTICE
Find the manager with only one subordinate, who, in turn, has no subordinates
CONFIDENTIAL 23
ORDERING DATA
CONFIDENTIAL 24
PRACTICE
For each employee show his/her salary and summary salary of all his/her
managers. Preserve tree structure in ascending order by salary in output.
CONFIDENTIAL 25
LOOPS
Let’s assume, that some data were modified in the current table:
CONFIDENTIAL 26
LOOPS
NOCYCLE parameter is used to avoid an error and to detect which row is cycling
CONFIDENTIAL 27
LOOPS
CONFIDENTIAL 28
USEFUL LINKS
Oracle documentation -
https://docs.oracle.com/cd/B19306_01/server.102/b14200/queries003.htm
CONFIDENTIAL 29
WITH HIERARCHYID DATA
TYPE
(MS SQL)
CONFIDENTIAL 30
Hierarchyid data type
CONFIDENTIAL 31
LEVELS
The hierarchyid type logically encodes information about a single node in a hierarchy
tree by encoding the path from the root of the tree to the node. Such a path is logically
represented as a sequence of node labels of all children visited after the root.
A slash starts the representation, and a path that only visits the root is represented by a
single slash
CONFIDENTIAL 32
TO_STRING()
Use the ToString() method to convert the hierarchyid value to the logical representation
as a nvarchar(4000) data type:
SELECT CAST(Level AS nvarchar(100)) AS [Converted Level]
, Level.ToString() as [Converted Level1]
, *
FROM SimpleDemo
ORDER BY Level;
CONFIDENTIAL 33
INSERT THE ROOT OF THE HIERARCHY TREE
Use the GetRoot() method to populate this first record as the root of the hierarchy.
INSERT SimpleDemo
VALUES (hierarchyid::GetRoot(),'Earth','Planet');
CONFIDENTIAL 34
INSERT A NEW NODE
CONFIDENTIAL 35
INSERT A NEW NODE
INSERT SimpleDemo
VALUES (@Root.GetDescendant(NULL, NULL),'Africa','Continent');
DECLARE @Root hierarchyid, @Child1 hierarchyid ,
@Child2 hierarchyid;
SELECT @Root = hierarchyid::GetRoot() FROM
SimpleDemo;
SELECT @Child1 = level FROM SimpleDemo where
Location = 'Africa';
SELECT @Child2 = level FROM SimpleDemo where
Location = 'North America';
INSERT SimpleDemo
VALUES
(@Root.GetDescendant(@Child1,
DECLARE @Root hierarchyid, @Child1 hierarchyid ; @Child2),'Australia','Continent');
SELECT @Root = hierarchyid::GetRoot() FROM SimpleDemo;
SELECT @Child1 = level FROM SimpleDemo where Location = 'Africa';
INSERT SimpleDemo
VALUES (@Root.GetDescendant(@Child1, NULL),'North America','Continent');
CONFIDENTIAL 36
FINDING THE CHILD NODES OF A PARENT
Used to test whether each node in the output has the current node as an ancestor at the
specified level
child.GetAncestor ( n )
n - an int, representing the number of levels to go up in the hierarchy.
--continents (children)
select *, Level.ToString()
from SimpleDemo
WHERE Level.GetAncestor(1) = @Node ;
CONFIDENTIAL 37
LEVEL IN THE HIERARCHY
Returns an integer that represents the depth of the node this in the tree.
node.GetLevel ( )
select *, Level.ToString()
from SimpleDemo
WHERE Level.GetLevel() = 2;
CONFIDENTIAL 38
USEFUL LINKS
MS SQL documentation
https://docs.microsoft.com/en-us/sql/t-sql/data-types/hierarchyid-data-type-method-
reference?view=sql-server-2017
CONFIDENTIAL 39
THANK YOU!
CONFIDENTIAL 40