Recursive CTE Employee Hierarchy Query – Manager Sql

Clear professional description of the code solution

C
Christian Geimer
·Oct 4, 2026·
0 0 2
Free
Prompt
499 words

You are an expert SQL developer tasked with writing a production‑ready recursive Common Table Expression (CTE) that extracts an employee hierarchy from a single “Employees” table. Follow the steps and deliverables exactly as described below.

Task Overview Write a recursive CTE query that, given a manager’s employee ID, returns every subordinate in the reporting chain, including the manager themselves, with the following columns for each row:

  1. EmployeeID – the employee’s unique identifier.
  2. EmployeeName – the employee’s full name.
  3. ManagerID – the direct manager’s employee ID (NULL for the top‑level manager).
  4. HierarchyLevel – integer depth where the starting manager is level 1, their direct reports level 2, etc.
  5. Path – a string representing the chain of IDs from the starting manager to the employee, separated by “→” (e.g., 1→4→7).
  6. IsCycle – a Boolean flag indicating whether the row is part of a cycle (should be 0 for normal rows, 1 for rows that would create a cycle).

The query must:

  • Use a parameterizable starting manager ID (e.g., @StartManagerID).
  • Prevent infinite loops by detecting cycles and marking them with IsCycle = 1.
  • Order the final result set first by HierarchyLevel ascending, then by Path alphabetically.
  • Be compatible with SQL Server 2019 (or later) syntax, but also include a brief note on any changes needed for PostgreSQL or MySQL 8+.

Schema (provided for reference)

CREATE TABLE Employees (
    EmployeeID   INT PRIMARY KEY,
    EmployeeName NVARCHAR(100) NOT NULL,
    ManagerID    INT NULL,
    CONSTRAINT FK_Employees_Manager FOREIGN KEY (ManagerID) REFERENCES Employees(EmployeeID)
);

Assume the table is already populated with realistic data, and that occasional data errors may create cycles (e.g., Employee 5 reports to Employee 9, and Employee 9 reports back to Employee 5).

Deliverables

  1. Complete SQL script (enclosed in a markdown code fence with language identifier sql) that:

    • Declares the @StartManagerID variable (use INT type) and sets it to a placeholder value (e.g., /* TODO: set start manager ID */).
    • Implements the recursive CTE meeting all requirements.
    • Includes a final SELECT statement that returns the columns listed above.
  2. Explanation (plain text, numbered list) that:

    • Describes how the CTE works, especially the cycle‑detection logic.
    • Shows how HierarchyLevel and Path are built.
    • Highlights any performance considerations (e.g., indexing recommendations).
  3. Sample output (markdown table) for a hypothetical hierarchy where the starting manager ID is 1. Use at least five rows, including one row that demonstrates a cycle (IsCycle = 1).

  4. Portability notes (brief bullet points) indicating what must be changed for PostgreSQL and MySQL 8+ (e.g., variable declaration, string concatenation operator).

Formatting Requirements

  • The SQL script must be a single, copy‑and‑pasteable block.
  • The explanation must be a numbered list (1., 2., …).
  • The sample output must be a markdown table with headers matching the column names.
  • The portability notes must be a bulleted list.

Please provide the complete response adhering strictly to the structure above. No additional commentary or filler text is needed.

Need help?

Connect with verified experts who can help you succeed.

Related Prompts

More prompts in Coding & Development

View All
Coding & Development
Universal

This Prompt Ads Sequential Function Calling To Models Other Than GPT 0613

This prompt ads sequential function calling to models other than GPT-0613

D
digitalmuse$2.99
39,910 89,588
Coding & Development
Universal

Create a personalized workout routine

Tailor a workout routine specifically designed for individual fitness goals

P
primequery$2.99
23,370 23,405
Coding & Development
Universal

GODMODE CHEATCODE

God Writes You a Letter Today. This is will help you find the perfect Bible Scripture that will guide you through a current problem you're facing.

S
signalcraft$3.99
13,574 13,622
Coding & Development
Universal

Creating a Personal Finance Tracker with [Technology/Tool]

Learn to create a personal finance tracker using [Technology/Tool]. Get code samples and budgeting tips.

F
focusqueryFree
376 385
Coding & Development
ChatGPT

Build an entire application using bubble.io with ChatGPT4

Build an entire app with bubble.io, assisted by chatGPT4, that knows bubble very well and is accurate 95% of the time. This prompt will help you maximize the quality of chatGPT assistance. Having detailed and step-by-step instructions is essential to progress fast with Bubble. This initial prompt will help you get started on a good basis. Follow it because I will make it even better.

P
promptframes$5.99
1,280 1,300
Coding & Development
Universal

Become LawyerGPT

Are you in a legal bind? This prompt can help you gain knowledge about how to handle your legal proceedings. DISCLAIMER: Please meet with a real lawyer to discuss your options.

P
promptbench$2.99
1,063 1,076