Recursive CTE Employee Hierarchy Query – Sql One
Clear professional description of the code solution
You are an expert SQL developer tasked with creating a complete, production‑ready solution for retrieving an employee hierarchy using a recursive Common Table Expression (CTE). Follow the steps below and produce the final answer in the exact format specified.
Task Overview
-
Schema Definition – Assume a single table named
Employeeswith the following columns:EmployeeIDINT PRIMARY KEYEmployeeNameVARCHAR(100) NOT NULLManagerIDINT NULL (foreign key referencingEmployees.EmployeeID;NULLindicates a top‑level manager)
-
Requirements
- Write a recursive CTE named
EmployeeHierarchythat returns, for every employee:EmployeeIDEmployeeNameManagerIDHierarchyLevel(1 for top‑level managers, incremented by 1 for each subordinate level)Path(a slash‑separated string of employee names from the top manager down to the current employee, e.g.,CEO/VP Sales/John Doe)
- Ensure the query safely handles potential cycles in the hierarchy by limiting recursion depth to 100 and excluding rows that would create a loop.
- Provide the query in a SQL Server dialect (
WITHrecursive CTE). Additionally, include equivalent versions for PostgreSQL and Oracle (usingCONNECT BY). - Include inline comments explaining each major clause of the CTE.
- Supply a sample data set (INSERT statements) containing at least 7 employees that illustrate:
- One top‑level manager (CEO)
- Two direct reports to the CEO
- Two levels of sub‑reports under one of those direct reports
- One employee with no subordinates
- Show the expected result set (as a markdown table) when the query is run against the sample data.
- Provide a brief performance discussion (indexes, statistics, execution plan hints) and a note on how to modify the query if the hierarchy needs to be filtered by a specific manager.
- End with a quick FAQ (2‑3 bullet points) covering common pitfalls such as circular references and missing manager records.
- Write a recursive CTE named
Output Format
Your response must be structured exactly as follows (use markdown headings and code fences):
- Schema Definition – a markdown code block with the
CREATE TABLEstatement. - Sample Data – a markdown code block with all
INSERTstatements. - Recursive CTE (SQL Server) – a markdown code block containing the full query with comments.
- Recursive CTE (PostgreSQL) – a markdown code block with the PostgreSQL‑specific syntax.
- Recursive CTE (Oracle) – a markdown code block using
CONNECT BY. - Result Set Example – a markdown table showing the output columns (
EmployeeID,EmployeeName,ManagerID,HierarchyLevel,Path) for the sample data. - Performance Considerations – a concise paragraph (or bullet list) describing indexes, statistics, and any query hints.
- Filtering by Manager – a short snippet showing how to add a
WHEREclause to retrieve a subtree. - FAQ – a bullet list of at least three common questions and answers.
Make sure every code block is properly fenced with the language identifier (sql). Do not include any explanatory text outside the sections described above.
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