Recursive CTE Employee Hierarchy Query – Employeeid Sql
Clear professional description of the code solution
Task: Write a complete, production‑ready solution for retrieving an employee hierarchy using a recursive Common Table Expression (CTE) in SQL Server (or PostgreSQL compatible syntax). The solution must include the SQL query, a brief explanation of how it works, sample data insertion statements, an example of the expected result set, and performance considerations (including index recommendations and cycle detection).
Requirements:
-
Schema Definition
- Table name:
Employees - Columns:
EmployeeID(INT, primary key)EmployeeName(NVARCHAR(100), NOT NULL)ManagerID(INT, NULL, foreign key referencingEmployees.EmployeeID)Title(NVARCHAR(100), NOT NULL)HireDate(DATE, NOT NULL)
- Provide a
CREATE TABLEstatement that includes primary key and foreign‑key constraints.
- Table name:
-
Sample Data
- Insert at least 10 rows that form a multi‑level hierarchy (e.g., CEO → VP → Director → Manager → Staff).
- Include at least one case where
ManagerIDisNULL(top‑level) and one case that would create a cycle if not handled (e.g., Employee 9 reports to Employee 5, and Employee 5 reports to Employee 9). Show how the cycle is prevented.
-
Recursive CTE Query
- The query must accept a parameter
@RootEmployeeID(or$root_idfor PostgreSQL) to start the hierarchy at any employee. - Output columns:
EmployeeIDEmployeeNameTitleHireDateManagerIDHierarchyLevel(1 for the root, 2 for direct reports, etc.)Path– a string showing the chain ofEmployeeIDs from the root to the current row, separated by>(e.g.,1>4>7).
- Include a safeguard against infinite recursion (e.g.,
OPTION (MAXRECURSION 1000)for SQL Server orMAXRECURSIONequivalent). - Order the final result set by
Path.
- The query must accept a parameter
-
Explanation
- Provide a concise (≤150 words) description of how the recursive CTE builds the hierarchy, how
HierarchyLevelandPathare calculated, and how the cycle‑prevention logic works.
- Provide a concise (≤150 words) description of how the recursive CTE builds the hierarchy, how
-
Performance & Indexing
- Recommend at least one index (or index combination) that optimizes the recursive query.
- Explain why the index helps and any trade‑offs.
- Mention any additional settings (e.g.,
SET ANSI_NULLS ON) that are advisable for production.
-
Output Format
- All SQL code must be enclosed in triple backticks with the appropriate language tag (
sql). - The explanation and performance notes should be plain text sections with clear headings.
- Example result set should be presented as a markdown table.
- All SQL code must be enclosed in triple backticks with the appropriate language tag (
Expected Output Example:
-- 1. Table creation
CREATE TABLE Employees ( ... );
-- 2. Sample data
INSERT INTO Employees ...;
-- 3. Recursive CTE query
DECLARE @RootEmployeeID INT = 1;
WITH EmployeeHierarchy AS ( ... )
SELECT ...;
OPTION (MAXRECURSION 1000);
Explanation: Your brief description here.
Performance & Indexing: Your recommendations here.
Sample Result Set
| EmployeeID | EmployeeName | Title | HireDate | ManagerID | HierarchyLevel | Path |
|---|---|---|---|---|---|---|
| 1 | Alice Smith | CEO | 2005-03-01 | NULL | 1 | 1 |
| 2 | Bob Jones | VP Marketing | 2008-07-15 | 1 | 2 | 1>2 |
| … | … | … | … | … | … | … |
Deliver the entire response exactly as described, with no additional commentary.
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