SQL06
SQL06
SQL06
Displaying Data
from Multiple Tables
Objectives
6-2
Lesson Agenda
6-3
Obtaining Data from Multiple Tables
EMPLOYEES DEPARTMENTS
6-4
Types of Joins
6-5
Joining Tables Using SQL:1999 Syntax
6-6
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-7
Lesson Agenda
6-8
Creating Natural Joins
6-9
Retrieving Records with Natural Joins
6 - 10
Creating Joins with the USING Clause
• If several columns have the same names but the data types
do not match, natural join can be applied using the USING
clause to specify the columns that should be used for an
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.
6 - 11
Joining Column Names
EMPLOYEES DEPARTMENTS
Primary key
Foreign key
6 - 12
Retrieving Records with the USING Clause
6 - 13
Using Table Aliases with the USING Clause
6 - 14
Creating Joins with the ON Clause
6 - 15
Retrieving Records with the ON Clause
6 - 16
Creating Three-Way Joins with
the ON Clause
6 - 17
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 - 18
Lesson Agenda
6 - 19
Joining a Table to Itself
… …
6 - 20
Self-Joins Using the ON Clause
6 - 21
Lesson Agenda
6 - 22
Nonequijoins
EMPLOYEES JOB_GRADES
6 - 23
Retrieving Records
with Nonequijoins
6 - 24
Lesson Agenda
6 - 25
Returning Records with No Direct Match
with Outer Joins
DEPARTMENTS EMPLOYEES
6 - 26
INNER Versus OUTER Joins
6 - 27
LEFT OUTER JOIN
6 - 28
RIGHT OUTER JOIN
6 - 29
FULL OUTER JOIN
6 - 30
Lesson Agenda
6 - 31
Cartesian Products
6 - 32
Generating a Cartesian Product
Cartesian product:
20 x 8 = 160 rows
…
6 - 33
Creating Cross Joins
6 - 34
Summary
6 - 35
Practice 6: Overview
6 - 36