Recursive CTE Employee Hierarchy Query – Name Table
Clear professional description of the code solution
Task: You are a senior SQL database architect. Create a complete, production‑ready solution for retrieving an employee hierarchy using a recursive Common Table Expression (CTE). The solution must include the table definition, sample data, the recursive query, an example result set, a detailed explanation of how the query works, and performance recommendations (indexes, pitfalls, and alternatives).
Requirements:
-
Schema Definition – Provide the exact
CREATE TABLEstatement for anemployeestable that stores:employee_id(primary key, integer, auto‑increment)first_name(varchar)last_name(varchar)manager_id(integer, nullable, foreign key toemployee_id)hire_date(date)salary(decimal(12,2))department_id(integer)
-
Sample Data – Insert at least 12 rows that illustrate a multi‑level hierarchy (e.g., CEO → VP → Director → Manager → Individual Contributor). Include at least one case where an employee has no manager (top‑level) and one case with a circular reference to demonstrate how the query prevents infinite loops.
-
Recursive CTE Query – Write a single SQL statement that:
- Starts from a given root employee (parameter
@RootEmployeeId). - Returns each descendant with the following columns:
employee_idfull_name(concatenation of first and last name)manager_idlevel(1 for the root, 2 for direct reports, etc.)path(a string showing the chain of employee IDs from the root to the current row, separated by->)salary
- Limits recursion depth to 10 levels to avoid runaway queries.
- Detects and excludes circular references, adding a column
is_cycle(0 = normal, 1 = cycle detected).
- Starts from a given root employee (parameter
-
Result Example – Show the output of the query when
@RootEmployeeId = 1(the CEO) using the sample data. Present the result as a markdown table. -
Explanation – Provide a step‑by‑step walkthrough of the CTE, covering:
- Anchor member
- Recursive member
- How
levelandpathare built - How the cycle detection works (
WHERE NOT EXISTSorOPTION (MAXRECURSION ...)etc.) - Why limiting recursion depth is important.
-
Performance Tips – List:
- Recommended indexes (including covering indexes) for optimal execution.
- Potential pitfalls (e.g., large hierarchies, missing manager records, deep recursion).
- Alternative approaches (e.g., materialized path, nested set, hierarchyid) and when to prefer them.
-
Output Format – Deliver the answer in markdown with the following sections and headings exactly as shown:
## 1. Schema Definition## 2. Sample Data## 3. Recursive CTE Query## 4. Result Example (Root Employee ID = 1)## 5. Explanation of the Query## 6. Performance Tips & Index Recommendations
Deliverable: A single, self‑contained markdown document that fulfills all the requirements above, ready to be copied into an SQL client or documentation repository. No additional commentary outside the specified sections.
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