Recursive CTE Employee Hierarchy Query – Name Optional
Clear professional description of the code solution
Task: Write a complete, production‑ready SQL script that uses a recursive Common Table Expression (CTE) to retrieve an employee hierarchy from a relational database. The script must be robust, well‑commented, and include optional filtering and ordering features.
Exact Requirements:
-
Schema Assumption
- Table name:
employees - Columns:
employee_id(PK, integer)first_name(varchar)last_name(varchar)manager_id(FK toemployees.employee_id, nullable) – the direct manager of the employeedepartment_id(integer, optional)hire_date(date)salary(numeric)
- Table name:
-
Recursive CTE Output Columns
employee_idfull_name– concatenation offirst_nameandlast_name(e.g., “John Doe”)manager_idmanager_name– full name of the direct manager (NULL for top‑level)hierarchy_level– integer depth, where the top‑level (no manager) is 1hierarchy_path– a string showing the chain of employee IDs from the root to the current row, separated by>(e.g.,1>4>9)total_subordinates– count of all direct and indirect reports for each employee (calculated in a separate CTE or window function)
-
Cycle Detection
- The query must detect and break potential management loops to avoid infinite recursion. Include a column
is_cycle(boolean) that flags rows where a cycle was encountered.
- The query must detect and break potential management loops to avoid infinite recursion. Include a column
-
Optional Filtering
- Accept two optional parameters (placeholders) that can be replaced when the script is executed:
:dept_filter– if supplied (non‑NULL), return only employees belonging to thatdepartment_id.:min_hire_date– if supplied (non‑NULL), return only employees hired on or after this date.
- Accept two optional parameters (placeholders) that can be replaced when the script is executed:
-
Ordering
- Final result set should be ordered by
hierarchy_path(so the hierarchy appears in depth‑first order) and then byfull_namealphabetically.
- Final result set should be ordered by
-
Performance Considerations
- Include indexes recommendations for the
employeestable that would optimize the recursive query. - Use
OPTION (MAXRECURSION 0)(or the equivalent for the target RDBMS) to allow unlimited depth, but also explain how to limit depth if needed.
- Include indexes recommendations for the
-
Compatibility
- Provide the script for Microsoft SQL Server syntax. Include a brief note on how to adapt it for PostgreSQL and Oracle (e.g.,
WITH RECURSIVE,CONNECT BY).
- Provide the script for Microsoft SQL Server syntax. Include a brief note on how to adapt it for PostgreSQL and Oracle (e.g.,
-
Output Format
- a. The full SQL script, wrapped in a markdown code block with language tag
sql. - b. A concise explanation (max 200 words) of how the recursive CTE works, how cycle detection is implemented, and how
total_subordinatesis calculated. - c. A sample result set (3‑4 rows) in a markdown table that demonstrates the columns and typical values.
- a. The full SQL script, wrapped in a markdown code block with language tag
Deliverable: Produce the script and accompanying documentation exactly as described above, ensuring it can be copied and run without further modification (aside from replacing the optional parameters). Do not include any extraneous 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