Recursive CTE Employee Hierarchy Query – Manager Sql
Clear professional description of the code solution
You are an expert SQL developer tasked with writing a production‑ready recursive Common Table Expression (CTE) that extracts an employee hierarchy from a single “Employees” table. Follow the steps and deliverables exactly as described below.
Task Overview Write a recursive CTE query that, given a manager’s employee ID, returns every subordinate in the reporting chain, including the manager themselves, with the following columns for each row:
EmployeeID– the employee’s unique identifier.EmployeeName– the employee’s full name.ManagerID– the direct manager’s employee ID (NULL for the top‑level manager).HierarchyLevel– integer depth where the starting manager is level 1, their direct reports level 2, etc.Path– a string representing the chain of IDs from the starting manager to the employee, separated by “→” (e.g.,1→4→7).IsCycle– a Boolean flag indicating whether the row is part of a cycle (should be0for normal rows,1for rows that would create a cycle).
The query must:
- Use a parameterizable starting manager ID (e.g.,
@StartManagerID). - Prevent infinite loops by detecting cycles and marking them with
IsCycle = 1. - Order the final result set first by
HierarchyLevelascending, then byPathalphabetically. - Be compatible with SQL Server 2019 (or later) syntax, but also include a brief note on any changes needed for PostgreSQL or MySQL 8+.
Schema (provided for reference)
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
EmployeeName NVARCHAR(100) NOT NULL,
ManagerID INT NULL,
CONSTRAINT FK_Employees_Manager FOREIGN KEY (ManagerID) REFERENCES Employees(EmployeeID)
);
Assume the table is already populated with realistic data, and that occasional data errors may create cycles (e.g., Employee 5 reports to Employee 9, and Employee 9 reports back to Employee 5).
Deliverables
-
Complete SQL script (enclosed in a markdown code fence with language identifier
sql) that:- Declares the
@StartManagerIDvariable (useINTtype) and sets it to a placeholder value (e.g.,/* TODO: set start manager ID */). - Implements the recursive CTE meeting all requirements.
- Includes a final
SELECTstatement that returns the columns listed above.
- Declares the
-
Explanation (plain text, numbered list) that:
- Describes how the CTE works, especially the cycle‑detection logic.
- Shows how
HierarchyLevelandPathare built. - Highlights any performance considerations (e.g., indexing recommendations).
-
Sample output (markdown table) for a hypothetical hierarchy where the starting manager ID is
1. Use at least five rows, including one row that demonstrates a cycle (IsCycle = 1). -
Portability notes (brief bullet points) indicating what must be changed for PostgreSQL and MySQL 8+ (e.g., variable declaration, string concatenation operator).
Formatting Requirements
- The SQL script must be a single, copy‑and‑pasteable block.
- The explanation must be a numbered list (1., 2., …).
- The sample output must be a markdown table with headers matching the column names.
- The portability notes must be a bulleted list.
Please provide the complete response adhering strictly to the structure above. No additional commentary or filler text is needed.
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.