Team Size under Each Manager
In employees, manager_id points to the manager. The team of an employee is everyone who reports to them directly or through other managers.
Return employee_id, name and team_size (the number of people in the team, not counting the employee themselves) for every employee whose team is not empty. Sort by team_size from high to low, then employee_id.
Hint 1
Recursion: start with every direct report as a pair (manager, report), then keep adding the reports of the reports, but keep the original manager.
Reference solution
WITH RECURSIVE team(manager_id, member_id) AS (
SELECT manager_id, employee_id
FROM employees
WHERE manager_id IS NOT NULL
UNION ALL
SELECT t.manager_id, e.employee_id
FROM team AS t
JOIN employees AS e ON e.manager_id = t.member_id
)
SELECT m.employee_id, m.name, COUNT(*) AS team_size
FROM team AS t
JOIN employees AS m ON m.employee_id = t.manager_id
GROUP BY m.employee_id, m.name
ORDER BY team_size DESC, m.employee_id;
The recursive step walks down one level at a time, and carries the starting manager along (t.manager_id), so at the end every row says "this member is somewhere below that manager". Counting those rows per manager gives the full team size. Keeping a constant "root" column through the recursion is the key trick for subtree totals: total sales of a region tree, size of a folder, headcount of a department.