Recursive CTE Employee Hierarchy Query – Cycledetected Advanced
Clear professional description of the code solution
Task: Create a complete, production‑ready SQL script that uses a recursive Common Table Expression (CTE) to generate an employee hierarchy from a single “Employees” table. The script must handle arbitrary depth, detect and prevent cycles, calculate additional hierarchy metrics, and be fully documented.
Requirements:
-
Schema Assumption The table
Employeeshas the following columns (you may add indexes if needed):EmployeeID(INT, PK)ManagerID(INT, nullable, FK toEmployeeID) –NULLfor top‑level executivesEmployeeName(VARCHAR)JobTitle(VARCHAR)Salary(DECIMAL(12,2))HireDate(DATE)
-
Recursive CTE Output Columns The final result set must include:
EmployeeIDEmployeeNameJobTitleManagerIDHierarchyLevel(1 for top‑level, 2 for direct reports, etc.)Path(a string showing the chain ofEmployeeNamefrom the root to the current row, separated by “ >”)SubordinateCount(total number of direct + indirect reports under the employee)CumulativeSalary(sum of salaries of the employee and all of their subordinates)CycleDetected(YES/NO flag indicating whether the row participates in a cycle)
-
Cycle Detection
- The CTE must stop recursion when a cycle is detected and set
CycleDetected = 'YES'for all rows involved in the cycle. - For non‑cyclic rows,
CycleDetected = 'NO'.
- The CTE must stop recursion when a cycle is detected and set
-
Performance Considerations
- Include an
OPTION (MAXRECURSION 0)(or the equivalent for the target RDBMS) to allow unlimited depth. - Suggest appropriate indexes (e.g., on
ManagerID) and any necessary statistics hints.
- Include an
-
Documentation
- Add clear, line‑by‑line comments explaining the purpose of each part of the script.
- Provide a brief “How it works” section after the query, describing the recursion logic, the calculation of
SubordinateCountandCumulativeSalary, and the cycle‑handling mechanism.
-
Sample Data & Expected Output
- Supply
INSERTstatements for at least 8 employees that illustrate:- A normal hierarchy (CEO → VP → Manager → Staff)
- A branch with multiple direct reports
- A deliberate cycle (e.g., Employee 7 reports to Employee 8, and Employee 8 reports back to Employee 7)
- Show the expected result set (as a markdown table) for the sample data, highlighting the
HierarchyLevel,Path,SubordinateCount,CumulativeSalary, andCycleDetectedcolumns.
- Supply
-
Compatibility
- Write the script for Microsoft SQL Server (T‑SQL). If you use any syntax that is specific to another RDBMS, note the required changes.
Expected Output Format:
- SQL Script – a single code block fenced with triple backticks (
```sql). - Explanation – a plain‑text section titled “How it works” with bullet points.
- Sample Data –
INSERTstatements inside a fenced SQL block. - Result Example – a markdown table showing the query output for the sample data.
Deliver the entire answer in the order listed above, ensuring the script can be copied and run unchanged on a fresh SQL Server database.
Related Prompts
More prompts in Data & Analytics
Sql Agent System Prompt
LangChain Hub prompt: langchain-ai/sql-agent-system-prompt
Buyer Persona Legend
Generate detailed User Personas for your Business with data neatly organized into a table.
Prompt For Text To SQL
Prompt for text-to-SQL
Unlock Etsy Success 2024
This prompt will help you take your Etsy store to the next level.
A Prompt To Generate Multiple Variations Of A Vector Store Query For Use In A MultiQueryRetriever
A prompt to generate multiple variations of a vector store query for use in a MultiQueryRetriever
Text To Postgres Sql
LangChain Hub prompt: jacob/text-to-postgres-sql