Lab 06
Lab 06
Multiple Tables
Lesson Agenda
6-2
Obtaining Data from Multiple Tables
EMPLOYEES DEPARTMENTS
6-3
Types of Joins
6-4
Joining Tables Using SQL Syntax
6-5
Qualifying Ambiguous
Column Names
• Use table prefixes to qualify column names that are in
multiple tables.
• Use table prefixes to improve performance.
• Instead of full table name prefixes, use table aliases.
• Table alias gives a table a shorter name:
– Keeps SQL code smaller, uses less memory
• Use column aliases to distinguish columns that have
identical names, but reside in different tables.
6-6
Lesson Agenda
6-7
Creating Natural Joins
6-8
Retrieving Records with Natural Joins
6-9
Creating Joins with the USING
Clause
• 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.
6 - 10
Joining Column Names
EMPLOYEES DEPARTMENTS
Primary key
Foreign key
6 - 11
Retrieving Records with the USING
Clause
6 - 12
Using Table Aliases with the USING
Clause
• Do not qualify a column that is used in the USING
clause.
• If the same column is used elsewhere in the SQL
statement,
SELECT do not
l.city, alias it.
d.department_name
FROM locations l JOIN departments
d USING (location_id)
WHERE d.location_id = 1400;
6 - 13
Creating Joins with the ON
Clause
• The join condition for the natural join is basically an
equijoin of all columns with the same name.
• Use the ON clause to specify conditions or specify columns
to join.
• The join condition is separated from other search
conditions.
• The ON clause makes code easy to understand.
6 - 14
Retrieving Records with the ON
Clause
6 - 15
Creating Three-Way Joins with
the ON Clause
6 - 16
Applying Additional Conditions
to a Join
Use the AND clause or the WHERE clause to apply
additional conditions:
SELECT e.employee_id, e.last_name, e.department_id,
d.department_id, d.location_id
FROM employees e JOIN departments d
ON (e.department_id =
d.department_id)
AND e.manager_id = 149 ;
Or
SELECT e.employee_id, e.last_name, e.department_id,
d.department_id, d.location_id
FROM employees e JOIN departments d
ON (e.department_id =
d.department_id)
WHERE e.manager_id = 149 ;
6 - 17
Lesson Agenda
6 - 18
Joining a Table to Itself
… …
6 - 20
Lesson Agenda
6 - 21
Nonequijoins
EMPLOYEES JOBS
6 - 22
Retrieving Records
with Nonequijoins
6 - 23
Lesson Agenda
6 - 25
INNER Versus OUTER
Joins
• In SQL, 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.
6 - 26
LEFT OUTER
JOIN
6 - 27
RIGHT OUTER
JOIN
6 - 28
FULL OUTER
JOIN
6 - 29
Lesson Agenda
6 - 30
Cartesian Products
6 - 31
Generating a Cartesian Product
Cartesian product:
20 x 8 = 160
rows
6 - 32
Creating Cross Joins
6 - 33
Thank You