Sec 6-7 Join Clauses
Sec 6-7 Join Clauses
NATURAL JOIN
• A natural join is based on all columns in two
tables that have the same name and selects
rows from the two tables that have equal
values in all matched columns.
• when using a natural join, it is possible to join
the tables without having to explicitly specify
the columns in the corresponding table.
• the names and data types of both columns must be the
same.
SELECT first_name, last_name, job_id, job_title
FROM employees NATURAL JOIN jobs WHERE
department_id > 80;
Using Where
SELECT first_name, last_name, department_id,
department_name
FROM employees JOIN departments USING
(department_id)
WHERE last_name = 'Higgins';
ON Clause
• What if the columns to be joined have different
names, or if the join uses non-equality comparison
operators such as <, >, or BETWEEN ?
• We can't use USING, so instead we use an ON clause.
• This allows a greater variety of join conditions to be
specified.
• The ON clause also allows us to use WHERE to restrict
rows from one or both tables.
• A join ON clause is required when the
common columns have different names in the
two tables.
SELECT last_name, job_title
FROM employees e JOIN jobs j
ON (e.job_id = j.job_id);
Left
SELECT e.last_name, d.department_id, d.department_name
FROM employees e
RIGHT OUTER JOIN departments d ON (e.department_id =
d.department_id);
• It is not possible to have the equivalent of a FULL OUTER JOIN by adding a (+) sign
to both columns in the join condition.
SELECT e.last_name, d.department_id, d.department_name
FROM employees e, departments d
WHERE e.department_id(+) = d.department_id(+);