Sub topic 2
Reading and writing the (+) operator
This chapter assumes you know basic SELECT, WHERE, table aliases, primary keys, and foreign keys. It also assumes you know that an inner join drops rows that have no match.
Oracle's older join syntax lists tables separated by commas and places the join condition in WHERE. The (+) marker is written after a column. It tells Oracle which side may lack matching rows. Put the marker on the side that can be empty, and the query keeps every row from the other side.
Reading a (+) query
SELECT d.department_name, e.last_name
FROM departments d, employees e
WHERE d.department_id = e.department_id(+);The marker sits on employees, so every department appears in the result. A department with no employees shows NULL for last_name. This query is equivalent to a LEFT OUTER JOIN from departments to employees.
Writing a (+) query with a filter
A condition on the optional table also needs the marker:
SELECT d.department_name, e.last_name
FROM departments d, employees e
WHERE d.department_id = e.department_id(+)
AND e.salary(+) > 10000;If you omit (+) from the salary condition, Oracle treats it as a filter on the whole result. Rows padded with NULL fail the test, so the query returns only matched rows.
Converting (+) queries to ANSI joins
Move the join condition into ON. Move any filter on the optional table into ON as well:
SELECT d.department_name, e.last_name
FROM departments d
LEFT OUTER JOIN employees e
ON e.department_id = d.department_id
AND e.salary > 10000;If the (+) marker sits on the left table, use RIGHT OUTER JOIN and keep the tables in the same order.
> Note: the (+) operator cannot be used with OR or IN, and it cannot mark both sides of one condition. It also cannot express FULL OUTER JOIN. Write new queries in ANSI syntax.
Joining three or more tables
Each JOIN adds one more table to the tables already joined:
SELECT e.last_name, d.department_name, l.city
FROM employees e
JOIN departments d ON e.department_id = d.department_id
JOIN locations l ON d.location_id = l.location_id;If some departments have no employees and you still want them listed, make the first step a LEFT OUTER JOIN. Rows whose location_id is NULL still drop out at the last step, so check that column when you need every department.
Exercise
Rewrite this legacy query as an ANSI join: SELECT e.lastname, d.departmentname FROM employees e, departments d WHERE e.departmentid = d.departmentid(+);
Show answer
SELECT e.lastname, d.departmentname FROM employees e LEFT OUTER JOIN departments d ON e.departmentid = d.departmentid; The marker is on departments, so employees is the table that must keep every row.