Reputation: 976
I am trying to learn oracle sql and below is my query. I wanted to print everyone's manager and if someone doesn't a manager then it should return "No One".
Problem: I am getting a blank statement instead of "No One". Any help?
SELECT NVL(m.first_name || ' '
|| m.last_name, 'No One') || ' supervises '
|| w.first_name || ' ' || w.last_name
FROM employees w, employees m
WHERE w.manager_id = m.employee_id(+);
NVL(M.FIRST_NAME||''||M.LAST_NAME,'NOONE')||'SUPERVISE
------------------------------------------------------
James Smith supervises Ron Johnson
Ron Johnson supervises Susan Jones
Ron Johnson supervises Fred Hobbs
supervises James Smith
Upvotes: 1
Views: 880
Reputation: 521093
I believe the accepted answer can be simplified by recognizing that when an employee be unsupervised, there will be no matching record for his manager. As a result, both the manager's first and last name will either be NULL
or not NULL
together.
SELECT NVL(m.first_name, 'No One', m.first_name || ' ' || m.last_name)
|| ' supervises ' || w.first_name || ' ' || w.last_name
FROM employees w LEFT JOIN employees m
ON w.manager_id = m.employee_id
Update:
The (+)
operator is Oracle's syntax for a LEFT JOIN
. Have a look at this Stack Overflow article to learn more about Oracle's (+)
operator.
Upvotes: 1
Reputation: 326
This is because of the reason, that when m.first_name and m.last_name will be null for the manager, then m.first_name || ' ' || m.last_name will not result in null, but with ' '. So, it will print space instead of 'No One'. You can achieve your desired results by using nvl2 something like
SELECT NVL2( m.first_name ||m.last_name , m.first_name || ' ' || m.last_name, 'No One' )
|| ' supervises '
|| w.first_name
|| ' '
|| w.last_name FROM employees w, employees m WHERE w.manager_id = m.employee_id(+);
Upvotes: 1