Efficient way to handle below query? in SQLServer or PostgreSql (Self join)


I have an employee table as below

select * from employee

I need to select employee_id, manager_id, result. result should have true or false depends on below conditions.

  1. If the employee is manager for someone then true
  2. If the employee has a manager then true

I came up with a query, but I need to know if there are any other better way to do it. This is my query

with manager  as
select distinct manager_id from employee where manager_id is not null
e.employee_id, e.manager_id , m.manager_id, 
case when e.manager_id is not null then true
     when m.manager_id is not null then true 
     else false
end as Result
from employee e left join manager m  on e.employee_id = m.manager_id 

and the result should come like this

enter image description here

answered question

1 Answer


Maybe something like this:

      ,CASE WHEN EXISTS(SELECT 1 FROM employee M WHERE M.managerID = E.employee_id) THEN true ELSE false END as REsult
FROM employee E

posted this

Have an answer?


Please login first before posting an answer.