0% found this document useful (0 votes)
27 views40 pages

Advanced SQL (Part 2) Nataliya Bogushevskaya

Advanced SQL (Part 2) Nataliya Bogushevskaya

Uploaded by

juliyagorelik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views40 pages

Advanced SQL (Part 2) Nataliya Bogushevskaya

Advanced SQL (Part 2) Nataliya Bogushevskaya

Uploaded by

juliyagorelik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Advanced SQL.

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

Hierarchical query clause

• 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

List all managers for some employee:

SELECT employee_id, manager_id, first_name, last_name


FROM employees

START WITH employee_id = 108 Starting point

CONNECT BY employee_id = PRIOR manager_id;

CONFIDENTIAL 6
EXAMPLE

List all subordinates for some employee:

SELECT employee_id, manager_id, first_name, last_name


FROM employees

START WITH employee_id = 108 Starting point

CONNECT BY PRIOR employee_id = manager_id;

CONFIDENTIAL 7
PRACTICE

Select all subordinates of Steven King

CONFIDENTIAL 8
EXECUTION

Oracle processes hierarchical queries as follows:


1. joins;
2. start with/connect by;
3. where;
4. group by and having;
5. order by.

CONFIDENTIAL 9
OPERATORS AND PSEUDOCOLUMNS

PRIOR

• PRIOR – retrieves previous filed in SELECT-clause

For each employee get his/her manager name

SELECT employee_id, manager_id, first_name, last_name


, PRIOR first_name AS m_first_name, PRIOR last_name
AS m_last_name
FROM employees
CONNECT BY PRIOR employee_id = manager_id
START WITH manager_id IS NULL;

CONFIDENTIAL 10
OPERATORS AND PSEUDOCOLUMNS

LEVEL

• LEVEL – returns 1 for a root row, 2 for a child of a root, and so on.

For each employee determine her/his level in hierarchy

SELECT employee_id, manager_id, first_name, last_name,LEVEL


FROM employees
CONNECT BY PRIOR employee_id = manager_id
START WITH manager_id IS NULL;

CONFIDENTIAL 11
PRACTICE #1

Print list of employees in a tree-view

Note. Use LPAD(' ',(LEVEL-1)*3,'-') for the shifting

CONFIDENTIAL 12
PRACTICE #2

Generate sequential numbers from 1 to 100

CONFIDENTIAL 13
PRACTICE #3

Generate dates from now (sysdate) till the end of the year.

CONFIDENTIAL 14
PRACTICE #4

Select all managers of employee with phone_number = '650.505.2876'. Don't


show the actual employee.

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)

• SYS_CONNECT_BY_PATH – returns the path of a column value from root to node;

For each employee of the 4th level list the full path from the root manager

SELECT e.first_name, e.last_name,


sys_connect_by_path(last_name||' '||first_name,'\') AS org
FROM employees e
WHERE LEVEL = 4
CONNECT BY e.manager_id = PRIOR e.employee_id
START WITH e.employee_id = 100;

CONFIDENTIAL 19
OPERATORS AND PSEUDOCOLUMNS

CONNECT_BY_ROOT

• CONNECT_BY_ROOT - references to the hierarchy root


SELECT last_name Employee,
King CONNECT_BY_ROOT last_name head_manager,
PRIOR last_name AS direct_manager,
LEVEL-1 Pathlen,
Kochhar SYS_CONNECT_BY_PATH(last_name, '/') PATH
FROM employees
Higgins WHERE department_id = 110
CONNECT BY PRIOR employee_id = manager_id
ORDER BY Employee,Pathlen
Gietz

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

• CONNECT_BY_ISLEAF – returns 1 for nodes having no children (a leaf), 0 for others

Print all employees of the 3rd level who hasn’t subordinates


SELECT last_name AS Employee,
LEVEL, SYS_CONNECT_BY_PATH(last_name, '/') Path
FROM employees
WHERE CONNECT_BY_ISLEAF = 1
AND LEVEL = 3
START WITH employee_id = 100
CONNECT BY PRIOR employee_id = manager_id
ORDER BY manager_id;

CONFIDENTIAL 22
PRACTICE

Find the manager with only one subordinate, who, in turn, has no subordinates

CONFIDENTIAL 23
ORDERING DATA

ORDER SIBLINGS BY – preserves hierarchical ordering

SELECT e.first_name, e.last_name,


sys_connect_by_path(last_name,'\') as org
FROM employees e
CONNECT BY e.manager_id = PRIOR e.employee_id
START WITH e.employee_id = 100
ORDER SIBLINGS BY first_name,last_name;

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:

--set Boss for the root row


UPDATE employees
SET manager_id = 145
WHERE employee_id = 100;

SELECT e.first_name, e.last_name,


sys_connect_by_path(last_name,'\') as org
FROM employees e
CONNECT BY e.manager_id = PRIOR e.employee_id
START WITH e.employee_id = 100
ORDER SIBLINGS BY first_name,last_name;

CONFIDENTIAL 26
LOOPS

NOCYCLE parameter is used to avoid an error and to detect which row is cycling

SELECT e.first_name, e.last_name,


sys_connect_by_path(last_name,'\') as org
FROM employees e
CONNECT BY NOCYCLE e.manager_id = PRIOR e.employee_id
START WITH e.employee_id = 100
ORDER SIBLINGS BY first_name,last_name;

CONFIDENTIAL 27
LOOPS

CONNECT_BY_ISCYCLE - pseudocolumn shows which rows contain the cycle

SELECT e.first_name, e.last_name,


sys_connect_by_path(last_name,'\') as org
FROM employees e
WHERE CONNECT_BY_ISCYCLE = 1
CONNECT BY NOCYCLE e.manager_id = PRIOR e.employee_id
START WITH e.employee_id = 100
ORDER SIBLINGS BY first_name,last_name;

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

• The hierarchyid data type is a variable length, system data type.


• A column of type hierarchyid does not automatically represent a tree. 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.
• A value of the hierarchyid data type represents a position in a tree hierarchy.

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

Use the GetDescendant() method, which takes two arguments.

parent.GetDescendant ( child1 , child2 )

• If parent is NULL, GetDescendant returns NULL.


• If parent is not NULL, and both child1 and child2 are NULL, GetDescendant returns a
child of parent.
• If parent and child1 are not NULL, and child2 is NULL, GetDescendant returns a child
of parent greater than child1.
• If parent and child2 are not NULL and child1 is NULL, GetDescendant returns a child of
parent less than child2.
• If parent, child1, and child2 are all not NULL, GetDescendant returns a child of parent
greater than child1 and less than child2.

CONFIDENTIAL 35
INSERT A NEW NODE

DECLARE @Root hierarchyid ;


SELECT @Root = hierarchyid::GetRoot() FROM SimpleDemo;

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.

DECLARE @Node hierarchyid;


SELECT @Node = hierarchyid::GetRoot() FROM SimpleDemo;

--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

You might also like