Unit 7 - Display Data From Multiple Tables Using Joins
Unit 7 - Display Data From Multiple Tables Using Joins
Using JOIN
Agenda
• Types of JOINS and its syntax
• Natural join
• Join with the USING Clause
• Join with the ON Clause
• Self-join
• Nonequijoins
• OUTER join: LEFT OUTER join, RIGHT OUTER join, FULL
OUTER join
• Cartesian product: Cross join
Using JOIN
Types of Joins
• Use table prefixes to qualify column names that are in multiple tables
• Use column aliases to distinguish columns that have identical names, but reside in different tables
.
Types of JOINS
Natural Joins
• The NATURAL JOIN clause is based on all the columns in the two tables
that have the same name
• It selects rows from the two tables that have equal values in all matched
columns
• If the columns having the same names have different data types, an error
is returned
Types of JOINS
Natural Joins examples
• If several columns have the same names but the data types do not match,
use the USING clause to specify the columns for the equijoin
• Use the USING clause to match only one column when more than one
column matches
• The NATURAL JOIN and USING clauses are mutually exclusive
• If the same column is used elsewhere in the SQL statement, do not alias it
• The join condition for the natural join is basically an equijoin of all columns with
the same name
• Use the ON clause to specify arbitrary conditions or specify columns to join
• The join condition is separated from other search conditions
• The ON clause makes code easy to understand
OR
Nonequijoins
SELECT e.last_name, e.salary, j.grade_level
FROM employees e JOIN job_grades j ON e.salary
BETWEEN j.lowest_sal AND j.highest_sal;
OUTER Joins
INNER or OUTER Joins ?
• In SQL:1999, the join of two tables returning only matched rows is called
an INNER join
• A join between two tables that returns the results of the INNER join as well
as the unmatched rows from the left (or right) table is called a left (or right)
OUTER join
• A join between two tables that returns the results of an INNER join as well
as the results of a left and right join is a full OUTER join
OUTER Joins
OUTER Join Examples
SELECT e.last_name, e.department_id, d.department_name
FROM employees e LEFT OUTER JOIN departments d
ON (e.department_id = d.department_id);
a) Nonequijoins
b) Left OUTER join
c) Right OUTER join
d) Full OUTER join
e) Self joins
f) Natural joins
g) Cartesian products
Using JOIN
Practice 5