Recursive CTE Employee Hierarchy Query – Employeeid Sql

Clear professional description of the code solution

C
Christian Geimer
·Oct 11, 2026·
2 0 7
Free
Prompt
517 words

Task: Write a complete, production‑ready solution for retrieving an employee hierarchy using a recursive Common Table Expression (CTE) in SQL Server (or PostgreSQL compatible syntax). The solution must include the SQL query, a brief explanation of how it works, sample data insertion statements, an example of the expected result set, and performance considerations (including index recommendations and cycle detection).

Requirements:

  1. Schema Definition

    • Table name: Employees
    • Columns:
      • EmployeeID (INT, primary key)
      • EmployeeName (NVARCHAR(100), NOT NULL)
      • ManagerID (INT, NULL, foreign key referencing Employees.EmployeeID)
      • Title (NVARCHAR(100), NOT NULL)
      • HireDate (DATE, NOT NULL)
    • Provide a CREATE TABLE statement that includes primary key and foreign‑key constraints.
  2. Sample Data

    • Insert at least 10 rows that form a multi‑level hierarchy (e.g., CEO → VP → Director → Manager → Staff).
    • Include at least one case where ManagerID is NULL (top‑level) and one case that would create a cycle if not handled (e.g., Employee 9 reports to Employee 5, and Employee 5 reports to Employee 9). Show how the cycle is prevented.
  3. Recursive CTE Query

    • The query must accept a parameter @RootEmployeeID (or $root_id for PostgreSQL) to start the hierarchy at any employee.
    • Output columns:
      1. EmployeeID
      2. EmployeeName
      3. Title
      4. HireDate
      5. ManagerID
      6. HierarchyLevel (1 for the root, 2 for direct reports, etc.)
      7. Path – a string showing the chain of EmployeeIDs from the root to the current row, separated by > (e.g., 1>4>7).
    • Include a safeguard against infinite recursion (e.g., OPTION (MAXRECURSION 1000) for SQL Server or MAXRECURSION equivalent).
    • Order the final result set by Path.
  4. Explanation

    • Provide a concise (≤150 words) description of how the recursive CTE builds the hierarchy, how HierarchyLevel and Path are calculated, and how the cycle‑prevention logic works.
  5. Performance & Indexing

    • Recommend at least one index (or index combination) that optimizes the recursive query.
    • Explain why the index helps and any trade‑offs.
    • Mention any additional settings (e.g., SET ANSI_NULLS ON) that are advisable for production.
  6. Output Format

    • All SQL code must be enclosed in triple backticks with the appropriate language tag (sql).
    • The explanation and performance notes should be plain text sections with clear headings.
    • Example result set should be presented as a markdown table.

Expected Output Example:

-- 1. Table creation
CREATE TABLE Employees ( ... );

-- 2. Sample data
INSERT INTO Employees ...;

-- 3. Recursive CTE query
DECLARE @RootEmployeeID INT = 1;
WITH EmployeeHierarchy AS ( ... )
SELECT ...;
OPTION (MAXRECURSION 1000);

Explanation: Your brief description here.

Performance & Indexing: Your recommendations here.

Sample Result Set

EmployeeIDEmployeeNameTitleHireDateManagerIDHierarchyLevelPath
1Alice SmithCEO2005-03-01NULL11
2Bob JonesVP Marketing2008-07-15121>2
…………………

Deliver the entire response exactly as described, with no additional commentary.

Need help?

Connect with verified experts who can help you succeed.

Related Prompts

More prompts in Data & Analytics

View All