I'm having trouble understanding this recursive CTE in SQL, I can understand most parts but one of the areas that throw me off is the second subquery the recursive member. It joins the EmployeeCTE to the employees table, but by my logic, there will be only one row in the EmployeeCTE up to that point. It will contain only the row that contains managerID = NULL. Also, I get that after it loops through the recursive member it will add 1 to rank but how does it select the correct employee to increment by 1 and not any of the other rows?
USE Examples;
WITH EmployeesCTE AS
(
-- Anchor member
SELECT EmployeeID,
FirstName + ' ' + LastName As EmployeeName,
1 As Rank
FROM Employees
WHERE ManagerID IS NULL
UNION ALL
-- Recursive member
SELECT Employees.EmployeeID,
FirstName + ' ' + LastName,
Rank + 1
FROM Employees
JOIN EmployeesCTE
ON Employees.ManagerID = EmployeesCTE.EmployeeID
)
SELECT *
FROM EmployeesCTE
ORDER BY Rank, EmployeeID;
SELECT *
FROM Employees