Depending on the platform, there are different SQL operators available to handle recursive parent/child connections for nested PK/FK relationships in a single table. Oracle uses a CONNECT BY clause while Postgres offers a WITH RECURSIVE/UNION ALL clause. Note the below Postgres query uses a CTE (common table expression) to add the Level column using AS. Once the Level column is established further queries allow creating a path of every tree vs. jus the results below that show where the children exist in the tree.
-- Create the Organization table
CREATE TABLE Organization (
ID SERIAL PRIMARY KEY,
ParentID INTEGER,
Name TEXT
);
-- Insert sample data
INSERT INTO Organization (ParentID, Name) VALUES
(NULL, 'CEO'),
(1, 'Manager1'),
(1, 'Manager2'),
(2, 'Employee1'),
(2, 'Employee2'),
(3, 'Employee3'),
(3, 'Employee4');
WITH RECURSIVE HierarchyCTE AS (
SELECT
ID,
ParentID,
Name,
0 AS Level
FROM
Organization
WHERE
ParentID IS NULL
UNION ALL
----------
SELECT
t.ID,
t.ParentID,
t.Name,
h.Level + 1
FROM
Organization t
JOIN
HierarchyCTE h ON t.ParentID = h.ID
)
---------
SELECT
ID,
ParentID,
Name,
Level
FROM
HierarchyCTE
ORDER BY
Level, ID;