Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query to get name of all employees under a manager recursively

Tags:

I am looking for a query to get name of all employees under a particular manager recursively.

EMP_TABLE

EMP_ID     EMP_NAME     MANAGER_ID
1          A            3
2          B            3
3          C            4
4          D            5
5          E            NULL

Query:

SELECT EMP_ID, EMP_NAME, MANAGER_ID FROM EMP_TABLE WHERE MANAGER_ID=4;

Output of this query:

EMP_ID     EMP_NAME     MANAGER_ID
3          C            4

Expected output:

EMP_ID     EMP_NAME     MANAGER_ID
1          A            3
2          B            3
3          C            4
like image 679
Shailesh Vikram Singh Avatar asked Dec 30 '21 10:12

Shailesh Vikram Singh


2 Answers

You need to use CONNECT BY to process hierarchical data in the table:

https://docs.snowflake.com/en/sql-reference/constructs/connect-by.html

SELECT EMP_ID, EMP_NAME, MANAGER_ID FROM EMP_TABLE 
START WITH MANAGER_ID=4
CONNECT BY MANAGER_ID = prior EMP_ID
ORDER BY EMP_ID;

+--------+----------+------------+
| EMP_ID | EMP_NAME | MANAGER_ID |
+--------+----------+------------+
|      1 | A        |          3 |
|      2 | B        |          3 |
|      3 | C        |          4 |
+--------+----------+------------+
like image 107
Gokhan Atil Avatar answered Oct 05 '22 23:10

Gokhan Atil


The CONNECT BY solution is very clear.

Here you have a recursive solution:

WITH rec AS (
    SELECT EMP_ID, EMP_NAME, MANAGER_ID 
      FROM EMP_TABLE 
     WHERE MANAGER_ID=4
     UNION ALL
    SELECT tb.EMP_ID, tb.EMP_NAME, tb.MANAGER_ID 
      FROM rec AS ta
      JOIN EMP_TABLE AS tb ON ta.EMP_ID = tb.MANAGER_ID
)
SELECT EMP_ID, EMP_NAME, MANAGER_ID 
  FROM rec
 ORDER BY 1;
like image 39
Michael Golos Avatar answered Oct 06 '22 01:10

Michael Golos