Recursive CTE Employee Hierarchy Query – Name Manager
Clear professional description of the code solution
Task: Write a complete, production‑ready SQL script that uses a recursive Common Table Expression (CTE) to retrieve an employee hierarchy from a relational database. The script must be ready to run on a standard ANSI‑SQL compliant system (e.g., PostgreSQL, SQL Server, MySQL 8.0+).
Requirements:
-
Source Table: Assume a single table named
employeeswith the following columns:employee_id(PK, integer)manager_id(FK toemployees.employee_id, nullable) –NULLindicates a top‑level executive.first_name(varchar)last_name(varchar)title(varchar)department_id(integer)salary(numeric)
-
Recursive CTE Output Columns:
employee_idfull_name– concatenation offirst_nameandlast_name.titledepartment_idsalarymanager_idhierarchy_level– integer starting at 1 for the root node(s).path– a slash‑separated string of employee IDs from the root to the current row (e.g.,1/4/7).total_subtree_salary– the sum of salaries for the employee and all of their direct and indirect reports.
-
Parameters:
@start_manager_id(or a placeholder like:start_manager_id) – the employee ID from which to begin the hierarchy. IfNULL, the CTE should start from all top‑level executives (manager_id IS NULL).
-
Cycle Detection: The query must safely detect and break potential reporting loops (e.g., an employee mistakenly set as their own manager) by limiting recursion depth to a reasonable maximum (e.g., 100) and excluding rows that would cause a cycle.
-
Ordering: Final result set should be ordered first by
hierarchy_levelascending, then bypathascending. -
Performance Considerations: Include appropriate indexes (as comments) that would support the recursive query efficiently.
-
Output Format: Provide the following sections, each clearly labeled:
- SQL Script: The full query wrapped in a markdown code block (
sql). - Explanation: A concise, bullet‑point description of how the CTE works, how the parameters are used, and how cycle detection is implemented.
- Index Recommendations: SQL
CREATE INDEXstatements (as comments) that would improve performance for large employee tables.
- SQL Script: The full query wrapped in a markdown code block (
Example Output:
### SQL Script
```sql
-- Replace :start_manager_id with the desired root employee ID or leave NULL for all CEOs
WITH RECURSIVE employee_hierarchy AS (
-- Anchor member: start nodes
SELECT
e.employee_id,
CONCAT(e.first_name, ' ', e.last_name) AS full_name,
e.title,
e.department_id,
e.salary,
e.manager_id,
1 AS hierarchy_level,
CAST(e.employee_id AS VARCHAR(1000)) AS path,
e.salary AS total_subtree_salary,
ARRAY[e.employee_id] AS visited_ids -- for cycle detection
FROM employees e
WHERE ( :start_manager_id IS NULL AND e.manager_id IS NULL )
OR e.employee_id = :start_manager_id
UNION ALL
-- Recursive member: walk down the hierarchy
SELECT
e.employee_id,
CONCAT(e.first_name, ' ', e.last_name) AS full_name,
e.title,
e.department_id,
e.salary,
e.manager_id,
eh.hierarchy_level + 1,
CONCAT(eh.path, '/', e.employee_id),
eh.total_subtree_salary + e.salary,
visited_ids || e.employee_id
FROM employees e
JOIN employee_hierarchy eh
ON e.manager_id = eh.employee_id
WHERE NOT e.employee_id = ANY(eh.visited_ids) -- prevent cycles
AND eh.hierarchy_level < 100 -- safety cap
)
SELECT
employee_id,
full_name,
title,
department_id,
salary,
manager_id,
hierarchy_level,
path,
total_subtree_salary
FROM employee_hierarchy
ORDER BY hierarchy_level, path;
Explanation
- Anchor member selects the root(s) based on
:start_manager_id. - Recursive member joins each manager to their direct reports, incrementing
hierarchy_leveland extending thepath. visited_ids(an array) tracks IDs already seen in the current branch; theWHERE NOT … = ANY(visited_ids)clause prevents infinite loops caused by circular references.- The recursion depth is limited to 100 to guard against pathological data.
total_subtree_salaryaggregates salaries on‑the‑fly, giving the cumulative cost for each manager’s entire reporting tree.
Index Recommendations
-- Index to quickly locate an employee’s direct reports
CREATE INDEX idx_employees_manager_id ON employees(manager_id);
-- Index to support look‑ups by employee_id (usually already PK)
CREATE INDEX idx_employees_employee_id ON employees(employee_id);
Related Prompts
More prompts in Coding & Development
This Prompt Ads Sequential Function Calling To Models Other Than GPT 0613
This prompt ads sequential function calling to models other than GPT-0613
Create a personalized workout routine
Tailor a workout routine specifically designed for individual fitness goals
GODMODE CHEATCODE
God Writes You a Letter Today. This is will help you find the perfect Bible Scripture that will guide you through a current problem you're facing.
Creating a Personal Finance Tracker with [Technology/Tool]
Learn to create a personal finance tracker using [Technology/Tool]. Get code samples and budgeting tips.
Build an entire application using bubble.io with ChatGPT4
Build an entire app with bubble.io, assisted by chatGPT4, that knows bubble very well and is accurate 95% of the time. This prompt will help you maximize the quality of chatGPT assistance. Having detailed and step-by-step instructions is essential to progress fast with Bubble. This initial prompt will help you get started on a good basis. Follow it because I will make it even better.
Become LawyerGPT
Are you in a legal bind? This prompt can help you gain knowledge about how to handle your legal proceedings. DISCLAIMER: Please meet with a real lawyer to discuss your options.