w3resource

Using Recursive Queries for Employee Hierarchies in SQL


Using Recursive Queries Across Databases

Write a SQL query to calculate employee hierarchies using recursive queries, comparing syntax between SQL Server and PostgreSQL.

Solution:

-- SQL Server
WITH EmployeeHierarchy AS (
    SELECT EmployeeID, ManagerID, Name, 1 AS Level
    FROM Employees
    WHERE ManagerID IS NULL
    UNION ALL
    SELECT e.EmployeeID, e.ManagerID, e.Name, eh.Level + 1
    FROM Employees e
    JOIN EmployeeHierarchy eh ON e.ManagerID = eh.EmployeeID
)
SELECT * FROM EmployeeHierarchy;

-- PostgreSQL
WITH RECURSIVE EmployeeHierarchy AS (
    SELECT EmployeeID, ManagerID, Name, 1 AS Level
    FROM Employees
    WHERE ManagerID IS NULL
    UNION ALL
    SELECT e.EmployeeID, e.ManagerID, e.Name, eh.Level + 1
    FROM Employees e
    JOIN EmployeeHierarchy eh ON e.ManagerID = eh.EmployeeID
)
SELECT * FROM EmployeeHierarchy;

Explanation:

  • Purpose of the Query :
    • The goal is to demonstrate how recursive queries differ slightly between SQL Server and PostgreSQL.
  • Key Components :
    • WITH RECURSIVE (PostgreSQL): Indicates a recursive query.
    • UNION ALL: Combines base and recursive results.
  • Why Compare Recursive Queries?:
    • Recursive queries model hierarchical data but may have platform-specific syntax.
    • Understanding these differences ensures correct implementation.
  • Real-World Application :
    • In organizational charts, recursive queries model employee hierarchies.

Additional Notes:

  • Use WITH RECURSIVE in PostgreSQL and WITH in SQL Server.
  • Test termination conditions to avoid infinite loops.
  • Important Considerations:
    • Limit recursion depth for performance and safety.

For more Practice: Solve these Related Problems:

  • Write a SQL query to calculate the hierarchy of managers and employees, comparing syntax between SQL Server and PostgreSQL.
  • Write a SQL query to calculate the hierarchy of categories and subcategories, comparing syntax between SQL Server and PostgreSQL.
  • Write a SQL query to calculate the hierarchy of projects and subprojects, comparing syntax between SQL Server and PostgreSQL.
  • Write a SQL query to calculate the hierarchy of organizational units, comparing syntax between SQL Server and PostgreSQL.


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous SQL Exercise:Handling JSON Data in MySQL and PostgreSQL.
Next SQL Exercise: Writing a Query that uses GROUP_CONCAT in MySQL and STRING_AGG in PostgreSQL.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.