-1

I have a table EMP with columns as below:

create table emp(
empno    number(4,0),
ename    varchar2(10),
job      varchar2(9),
mgr_id   number(4,0),
sal      number(7,2),
deptno   number(2,0));

I want to list all employees' names along with their manager names, including those who do not have a manager. For those employees, their manager's name should be displayed as 'BOSS'.

William Robertson
  • 15,273
  • 4
  • 38
  • 44
Gani Ganesh
  • 63
  • 2
  • 10

3 Answers3

2

The following query should work:

select e.ename, (case when m.ename is null then 'BOSS' else m.ename end) as mgrName 
from emp e
left join emp m on m.empno = e.mgr_id
APC
  • 144,005
  • 19
  • 170
  • 281
2

To my mind, the better solution is proposed by Charanjith.

In Oracle, we could even use NVL function instead of "case when" in order to replace null value by something. The result should be the same.

select e.ename empName, NVL(m.ename, 'BOSS') mgrName from emp e
left join emp m on m.empno = e.mgr_id

Moreover, we could see another solution : using inner join to filter on emp when a manager exists. Then union for all employees who don't have any manager.

select e.ename empName, m.ename mgrName from emp e inner join emp m on e.mgr_id = m.empno
union
select e.ename empName, 'BOSS' mgrName from emp e where not exists (select 1 from emp m where e.mgr_id = m.empno)
OlivierTerrien
  • 2,451
  • 1
  • 19
  • 31
0

This work fine in oracle:

SELECT e.ename,
 nvl(m.ename, 'BOSS')mgr
   FROM emp a
LEFT JOIN emp b
ON m.empno = e.mgr_id;
Akanksha
  • 91
  • 7