Recursive CTE Employee Hierarchy Query – Null Sql
Clear professional description of the code solution
Prompt
You are an expert SQL developer. Write a complete, production‑ready solution that uses a recursive Common Table Expression (CTE) to retrieve an employee hierarchy from a single “Employees” table. Follow the instructions below precisely and return the answer in the exact format requested.
1. Schema description
Assume the following table exists (use ANSI‑SQL syntax, compatible with PostgreSQL, SQL Server, MySQL 8+, and Oracle 12c+):
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
EmployeeName VARCHAR(100) NOT NULL,
ManagerID INT NULL, -- references Employees.EmployeeID; NULL = top‑level CEO
Department VARCHAR(50) NOT NULL,
Salary NUMERIC(12,2) NOT NULL,
HireDate DATE NOT NULL
);
ManagerIDmay be NULL for the root node(s).- The hierarchy can be arbitrarily deep and may contain multiple roots (e.g., multiple CEOs in a holding company).
2. Required output columns
Your query must return one row per employee with the following columns, in this order:
| Column | Description |
|---|---|
EmployeeID | Original employee identifier |
EmployeeName | Employee’s name |
ManagerID | Direct manager’s ID (NULL for roots) |
HierarchyLevel | 1 for top‑level roots, 2 for their direct reports, etc. |
Path | A slash‑separated string of employee names from the root to the current employee (e.g., CEO/VP Marketing/Director ) |
TotalSubordinates | Count of all direct and indirect reports under the employee (0 for leaf nodes) |
TotalSalaryUnder | Sum of salaries of all direct and indirect reports (0 for leaf nodes) |
IsManager | Boolean (TRUE/FALSE) indicating whether the employee has at least one direct report |
The result set must be ordered by Path (lexicographically) so that the hierarchy appears in a readable tree order.
3. Tasks
- Write the recursive CTE that produces the columns above.
- Include a brief, inline comment on each major part of the query (CTE definition, anchor member, recursive member, final SELECT).
- Provide a second, optional query that shows only the hierarchy for a given
@RootEmployeeID(parameterizable). Use a placeholder like:RootEmployeeIDfor the value. - Explain the logic in plain English (max 200 words) after the code block.
- Supply sample data (INSERT statements) that creates at least three levels of hierarchy, includes a second root, and demonstrates employees with and without subordinates. Use at most 12 rows.
- List performance recommendations (indexes, statistics, query hints) specific to the recursive CTE, formatted as a bullet list.
- State any limitations (e.g., maximum recursion depth) and how to adjust them for major RDBMS.
4. Output format
Your answer must contain exactly the following sections, in this order, each separated by a blank line:
- SQL – Recursive CTE (code block, language
sql) - SQL – Parameterized version (code block, language
sql) - Explanation (plain paragraph)
- Sample data (code block, language
sql) - Performance tips (markdown bullet list)
- Limitations & adjustments (markdown bullet list)
Do not add any extra sections, titles, or commentary outside the structure above. Use the exact headings shown (e.g., “SQL – Recursive CTE”). Ensure all code is syntactically correct for the target platforms mentioned.
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