The hierarchical database model is one of the oldest types of database models, primarily characterized by its tree-like structure. In this model, data is organized into a hierarchy, resembling a parent-child relationship. Each parent can have multiple children, but each child can only have one parent. This structure is well-suited for applications where the relationships between data are clear and fixed.
To represent a hierarchical database model, we often use tree diagrams. Below is a simple example of a hierarchical structure for a company.
While SQL databases can simulate a hierarchical model, some dedicated hierarchical DBMS include:
Let’s consider a company database that includes information about departments and employees. We will define the structure, create tables, and perform operations using SQL.
In a relational database, the hierarchical model can be simulated using tables with foreign key relationships. Here’s how we might structure our tables for the company example:
Department Table
Employee Table
CREATE TABLE Department (
DepartmentID INT PRIMARY KEY,
DepartmentName VARCHAR(100),
ManagerID INT,
FOREIGN KEY (ManagerID) REFERENCES Employee(EmployeeID)
);
CREATE TABLE Employee (
EmployeeID INT PRIMARY KEY,
EmployeeName VARCHAR(100),
DepartmentID INT,
FOREIGN KEY (DepartmentID) REFERENCES Department(DepartmentID)
);
Now, let’s populate the tables with sample data.
-- Inserting Employees
INSERT INTO Employee (EmployeeID, EmployeeName) VALUES (1, 'Alice');
INSERT INTO Employee (EmployeeID, EmployeeName) VALUES (2, 'Bob');
INSERT INTO Employee (EmployeeID, EmployeeName) VALUES (3, 'Charlie');
INSERT INTO Employee (EmployeeID, EmployeeName) VALUES (4, 'Diana');
INSERT INTO Employee (EmployeeID, EmployeeName) VALUES (5, 'Eve');
-- Inserting Departments
INSERT INTO Department (DepartmentID, DepartmentName, ManagerID) VALUES (1, 'Department A', 1);
INSERT INTO Department (DepartmentID, DepartmentName, ManagerID) VALUES (2, 'Department B', 2);
INSERT INTO Department (DepartmentID, DepartmentName, ManagerID) VALUES (3, 'Department C', 1);
-- Assigning Employees to Departments
UPDATE Employee SET DepartmentID = 1 WHERE EmployeeID IN (1, 2);
UPDATE Employee SET DepartmentID = 2 WHERE EmployeeID IN (3, 4);
UPDATE Employee SET DepartmentID = 3 WHERE EmployeeID = 5;
In hierarchical databases, certain queries become necessary to traverse the hierarchy. For instance, to find all employees under a specific department, we can use a recursive Common Table Expression (CTE) in SQL:
WITH RECURSIVE EmployeeHierarchy AS (
SELECT EmployeeID, EmployeeName, DepartmentID
FROM Employee
WHERE DepartmentID = 1 -- Start with Department A
UNION ALL
SELECT e.EmployeeID, e.EmployeeName, e.DepartmentID
FROM Employee e
JOIN EmployeeHierarchy eh ON e.DepartmentID = eh.DepartmentID
)
SELECT * FROM EmployeeHierarchy;