Recursive CTE Employee Hierarchy Query – Sql Null 2
Clear professional description of the code solution
You are an expert SQL developer specializing in complex hierarchical queries. Using the information below, create a complete, production‑ready solution that retrieves an employee hierarchy with a recursive Common Table Expression (CTE). Follow each requirement precisely and present the answer in the exact output format specified.
Database schema
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
employee_name VARCHAR(100) NOT NULL,
manager_id INT NULL, -- references employees.employee_id
hire_date DATE NOT NULL,
salary DECIMAL(12,2) NOT NULL,
department_id INT NOT NULL
);
manager_idis NULL for top‑level executives.- The table may contain cycles (e.g., erroneous manager references) and employees with missing managers (orphaned rows).
Task
-
Write a single, self‑contained SQL script that:
- Detects and prevents infinite loops caused by cycles.
- Returns the full hierarchy for all employees, even if they are orphaned.
- Includes the following columns in the result set:
employee_idemployee_namemanager_idhierarchy_level(0 for top‑level, 1 for direct reports, etc.)path(a slash‑separated string of employee_ids from the root to the current employee, e.g.,1/4/7)total_subordinates(the count of all direct and indirect reports under each employee)
- Orders the final result by
path.
-
Provide inline comments within the SQL script explaining each major step, especially how cycle detection works.
-
After the script, include a brief explanation (≈150‑200 words) covering:
- How the recursive CTE builds the hierarchy.
- The technique used to break cycles.
- Any assumptions made (e.g., maximum depth).
-
Supply sample data (5‑7 rows) that illustrates:
- A normal hierarchy.
- At least one cycle.
- At least one orphaned employee.
Show the
INSERTstatements and the expected output of the query when run against this sample data (present the output as a markdown table).
-
Recommend performance‑enhancing indexes (including index definitions) that would optimize the recursive query for a large
employeestable.
Output format
- SQL Script – enclosed in a markdown code block with language tag
sql. - Explanation – a separate markdown paragraph titled Explanation.
- Sample Data – markdown code block with
INSERTstatements (languagesql), followed by a markdown table titled Expected Output. - Index Recommendations – markdown code block (language
sql) listing eachCREATE INDEXstatement, preceded by a brief bullet list of why each index is useful.
Deliver exactly these sections in the order listed, with no extra commentary or headings beyond those specified.
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