SQL recursively going up in a tree


Example

WITH RECURSIVE ManagersOfJonathon AS (
    -- start with this row
    SELECT *
    FROM Employees
    WHERE ID = 4

    UNION ALL

    -- get manager(s) of all previously selected rows
    SELECT Employees.*
    FROM Employees
    JOIN ManagersOfJonathon
        ON Employees.ID = ManagersOfJonathon.ManagerID
)
SELECT * FROM ManagersOfJonathon;
IdFNameLNamePhoneNumberManagerIdDepartmentId
4JohnathonSmith121212121221
2JohnJohnson246810121411
1JamesSmith1234567890NULL1