SlideShare a Scribd company logo
4
Copyright © Oracle Corporation, 2001. All rights reserved.
Displaying Data
from Multiple Tables
4-2 Copyright © Oracle Corporation, 2001. All rights reserved.
Objectives
After completing this lesson, you should be able to
do the following:
• Write SELECT statements to access data from
more than one table using equality and
nonequality joins
• View data that generally does not meet a join
condition by using outer joins
• Join a table to itself by using a self join
4-3 Copyright © Oracle Corporation, 2001. All rights reserved.
Obtaining Data from Multiple Tables
EMPLOYEES DEPARTMENTS
…
…
4-4 Copyright © Oracle Corporation, 2001. All rights reserved.
Cartesian Products
• A Cartesian product is formed when:
– A join condition is omitted
– A join condition is invalid
– All rows in the first table are joined to all rows in
the second table
• To avoid a Cartesian product, always include a
valid join condition in a WHERE clause.
4-5 Copyright © Oracle Corporation, 2001. All rights reserved.
Generating a Cartesian Product
Cartesian
product:
20x8=160 rows
EMPLOYEES (20 rows) DEPARTMENTS (8 rows)
…
…
4-6 Copyright © Oracle Corporation, 2001. All rights reserved.
• Equijoin
• Non-equijoin
• Outer join
• Self join
Types of Joins
• Cross joins
• Natural joins
• Using clause
• Full or two sided outer
joins
• Arbitrary join conditions
for outer joins
SQL: 1999
Compliant Joins:
Oracle Proprietary
Joins (8i and prior):
4-7 Copyright © Oracle Corporation, 2001. All rights reserved.
Joining Tables Using Oracle Syntax
Use a join to query data from more than one table.
• Write the join condition in the WHERE clause.
• Prefix the column name with the table name when
the same column name appears in more than one
table.
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column1 = table2.column2;
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column1 = table2.column2;
4-8 Copyright © Oracle Corporation, 2001. All rights reserved.
What is an Equijoin?
EMPLOYEES DEPARTMENTS
Foreign key Primary key
… …
4-9 Copyright © Oracle Corporation, 2001. All rights reserved.
SELECT employees.employee_id, employees.last_name,
employees.department_id, departments.department_id,
departments.location_id
FROM employees, departments
WHERE employees.department_id = departments.department_id;
Retrieving Records
with Equijoins
…
4-10 Copyright © Oracle Corporation, 2001. All rights reserved.
Additional Search Conditions
Using the AND Operator
EMPLOYEES DEPARTMENTS
… …
4-11 Copyright © Oracle Corporation, 2001. All rights reserved.
Qualifying Ambiguous
Column Names
• Use table prefixes to qualify column names that
are in multiple tables.
• Improve performance by using table prefixes.
• Distinguish columns that have identical names but
reside in different tables by using column aliases.
4-12 Copyright © Oracle Corporation, 2001. All rights reserved.
SELECT e.employee_id, e.last_name, e.department_id,
d.department_id, d.location_id
FROM employees e , departments d
WHERE e.department_id = d.department_id;
Using Table Aliases
• Simplify queries by using table aliases.
• Improve performance by using table prefixes.
4-13 Copyright © Oracle Corporation, 2001. All rights reserved.
Joining More than Two Tables
EMPLOYEES LOCATIONSDEPARTMENTS
To join n tables together, you need a minimum of n-1
join conditions. For example, to join three tables, a
minimum of two joins is required.
…
4-14 Copyright © Oracle Corporation, 2001. All rights reserved.
Non-Equijoins
EMPLOYEES JOB_GRADES
Salary in the EMPLOYEES
table must be between
lowest salary and highest
salary in the JOB_GRADES
table.
…
4-15 Copyright © Oracle Corporation, 2001. All rights reserved.
Retrieving Records
with Non-Equijoins
SELECT e.last_name, e.salary, j.grade_level
FROM employees e, job_grades j
WHERE e.salary
BETWEEN j.lowest_sal AND j.highest_sal;
…
4-16 Copyright © Oracle Corporation, 2001. All rights reserved.
Outer Joins
EMPLOYEESDEPARTMENTS
There are no employees in
department 190.
…
4-17 Copyright © Oracle Corporation, 2001. All rights reserved.
Outer Joins Syntax
• You use an outer join to also see rows that do not
meet the join condition.
• The Outer join operator is the plus sign (+).
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column(+) = table2.column;
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column(+) = table2.column;
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column = table2.column(+);
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column = table2.column(+);
4-18 Copyright © Oracle Corporation, 2001. All rights reserved.
SELECT e.last_name, e.department_id, d.department_name
FROM employees e, departments d
WHERE e.department_id(+) = d.department_id ;
Using Outer Joins
…
4-19 Copyright © Oracle Corporation, 2001. All rights reserved.
Self Joins
EMPLOYEES (WORKER) EMPLOYEES (MANAGER)
MANAGER_ID in the WORKER table is equal to
EMPLOYEE_ID in the MANAGER table.
… …
4-20 Copyright © Oracle Corporation, 2001. All rights reserved.
Joining a Table to Itself
SELECT worker.last_name || ' works for '
|| manager.last_name
FROM employees worker, employees manager
WHERE worker.manager_id = manager.employee_id ;
…
4-21 Copyright © Oracle Corporation, 2001. All rights reserved.
Practice 4, Part One: Overview
This practice covers writing queries to join tables
together using Oracle syntax.
4-22 Copyright © Oracle Corporation, 2001. All rights reserved.
Joining Tables Using SQL: 1999 Syntax
Use a join to query data from more than one table.
SELECT table1.column, table2.column
FROM table1
[CROSS JOIN table2] |
[NATURAL JOIN table2] |
[JOIN table2 USING (column_name)] |
[JOIN table2
ON(table1.column_name = table2.column_name)] |
[LEFT|RIGHT|FULL OUTER JOIN table2
ON (table1.column_name = table2.column_name)];
SELECT table1.column, table2.column
FROM table1
[CROSS JOIN table2] |
[NATURAL JOIN table2] |
[JOIN table2 USING (column_name)] |
[JOIN table2
ON(table1.column_name = table2.column_name)] |
[LEFT|RIGHT|FULL OUTER JOIN table2
ON (table1.column_name = table2.column_name)];
4-23 Copyright © Oracle Corporation, 2001. All rights reserved.
Creating Cross Joins
• The CROSS JOIN clause produces the cross-
product of two tables.
• This is the same as a Cartesian product between
the two tables.
SELECT last_name, department_name
FROM employees
CROSS JOIN departments ;
…
4-24 Copyright © Oracle Corporation, 2001. All rights reserved.
Creating Natural Joins
• The NATURAL JOIN clause is based on all 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.
4-25 Copyright © Oracle Corporation, 2001. All rights reserved.
SELECT department_id, department_name,
location_id, city
FROM departments
NATURAL JOIN locations ;
Retrieving Records with Natural Joins
4-26 Copyright © Oracle Corporation, 2001. All rights reserved.
Creating Joins with the USING Clause
• If several columns have the same names but the
data types do not match, the NATURAL JOIN
clause can be modified with 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.
• Do not use a table name or alias in the referenced
columns.
• The NATURAL JOIN and USING clauses are
mutually exclusive.
4-27 Copyright © Oracle Corporation, 2001. All rights reserved.
SELECT e.employee_id, e.last_name, d.location_id
FROM employees e JOIN departments d
USING (department_id) ;
Retrieving Records with the USING Clause
…
4-28 Copyright © Oracle Corporation, 2001. All rights reserved.
Creating Joins with the ON Clause
• The join condition for the natural join is basically
an equijoin of all columns with the same name.
• To specify arbitrary conditions or specify columns
to join, the ON clause is used.
• The join condition is separated from other search
conditions.
• The ON clause makes code easy to understand.
4-29 Copyright © Oracle Corporation, 2001. All rights reserved.
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);
Retrieving Records with the ON Clause
…
4-30 Copyright © Oracle Corporation, 2001. All rights reserved.
Creating Three-Way Joins with the ON
Clause
SELECT employee_id, city, department_name
FROM employees e
JOIN departments d
ON d.department_id = e.department_id
JOIN locations l
ON d.location_id = l.location_id;
…
4-31 Copyright © Oracle Corporation, 2001. All rights reserved.
INNER Versus OUTER Joins
• In SQL: 1999, the join of two tables returning only
matched rows is an inner join.
• A join between two tables that returns the results
of the inner join as well as unmatched rows left (or
right) tables is 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.
4-32 Copyright © Oracle Corporation, 2001. All rights reserved.
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) ;
LEFT OUTER JOIN
…
4-33 Copyright © Oracle Corporation, 2001. All rights reserved.
SELECT e.last_name, e.department_id, d.department_name
FROM employees e
RIGHT OUTER JOIN departments d
ON (e.department_id = d.department_id) ;
RIGHT OUTER JOIN
…
4-34 Copyright © Oracle Corporation, 2001. All rights reserved.
SELECT e.last_name, e.department_id, d.department_name
FROM employees e
FULL OUTER JOIN departments d
ON (e.department_id = d.department_id) ;
FULL OUTER JOIN
…
4-35 Copyright © Oracle Corporation, 2001. All rights reserved.
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 ;
Additional Conditions
4-36 Copyright © Oracle Corporation, 2001. All rights reserved.
Summary
In this lesson, you should have learned how to use
joins to display data from multiple tables in:
• Oracle proprietary syntax for versions 8i and
earlier
• SQL: 1999 compliant syntax for version 9i
4-37 Copyright © Oracle Corporation, 2001. All rights reserved.
Practice 4, Part Two: Overview
This practice covers the following topics:
• Joining tables using an equijoin
• Performing outer and self joins
• Adding conditions
4-40 Copyright © Oracle Corporation, 2001. All rights reserved.

More Related Content

What's hot (20)

PPT
07 Using Oracle-Supported Package in Application Development
rehaniltifat
 
PPT
Les01 (retrieving data using the sql select statement)
Achmad Solichin
 
PPT
06 Using More Package Concepts
rehaniltifat
 
PPT
Including Constraints -Oracle Data base
Salman Memon
 
PPTX
SQL UNION
Ritwik Das
 
PPT
Sql oracle
Md.Abu Noman Shuvo
 
PPT
Manipulating Data Oracle Data base
Salman Memon
 
PDF
SQL Functions and Operators
Mohan Kumar.R
 
PPTX
4. plsql
Amrit Kaur
 
PPT
Producing Readable Output with iSQL*Plus - Oracle Data Base
Salman Memon
 
PPT
Creating Views - oracle database
Salman Memon
 
PPTX
SUBQUERIES.pptx
RenugadeviR5
 
PPT
02 Writing Executable Statments
rehaniltifat
 
PDF
SQL BUILT-IN FUNCTION
Arun Sial
 
PPT
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
rehaniltifat
 
PPT
08 Dynamic SQL and Metadata
rehaniltifat
 
DOC
Sql queires
MohitKumar1985
 
PPTX
SQL
Vineeta Garg
 
PDF
SQL Overview
Stewart Rogers
 
PPT
Sql Tutorials
Priyabrat Kar
 
07 Using Oracle-Supported Package in Application Development
rehaniltifat
 
Les01 (retrieving data using the sql select statement)
Achmad Solichin
 
06 Using More Package Concepts
rehaniltifat
 
Including Constraints -Oracle Data base
Salman Memon
 
SQL UNION
Ritwik Das
 
Sql oracle
Md.Abu Noman Shuvo
 
Manipulating Data Oracle Data base
Salman Memon
 
SQL Functions and Operators
Mohan Kumar.R
 
4. plsql
Amrit Kaur
 
Producing Readable Output with iSQL*Plus - Oracle Data Base
Salman Memon
 
Creating Views - oracle database
Salman Memon
 
SUBQUERIES.pptx
RenugadeviR5
 
02 Writing Executable Statments
rehaniltifat
 
SQL BUILT-IN FUNCTION
Arun Sial
 
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
rehaniltifat
 
08 Dynamic SQL and Metadata
rehaniltifat
 
Sql queires
MohitKumar1985
 
SQL Overview
Stewart Rogers
 
Sql Tutorials
Priyabrat Kar
 

Viewers also liked (15)

DOCX
Kathleen Anne Lincourt Resume 1_28_15
Kathleen Lincourt
 
PPTX
1 вступ робоче місце_пит_тести
Andy Levkovich
 
PDF
Recuerdo de 24 horas
torrijosmix1
 
DOCX
Introducción
brandon chicaiza
 
PPTX
1 вступ робоче місце_інфографіка
Andy Levkovich
 
PDF
Get6 infographic
ARIN
 
PDF
Campana Siemens LF91BA582
Alsako Electrodomésticos
 
PDF
Bisogno, M. (2015), Goodwill and accounting discreption
University of Salerno
 
DOC
Khurram_Shahzad CV
khurram shahzad
 
DOC
imran cv
imran pasha
 
PDF
Sprawozdanie finansowe za 2015 FRSP bilans
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego
 
PDF
MM Bagali, HR, HRM, HRD, MBA, Research, India, Teaching, Faculty.....Dash board
dr m m bagali, phd in hr
 
PPT
Physiology of hemodynamics & PiCCO parameters in detail
meducationdotnet
 
PPTX
A&m assessment help
greg robertson
 
PDF
CEE_Fund_SPRING_2015
Mitchell Phillips
 
Kathleen Anne Lincourt Resume 1_28_15
Kathleen Lincourt
 
1 вступ робоче місце_пит_тести
Andy Levkovich
 
Recuerdo de 24 horas
torrijosmix1
 
Introducción
brandon chicaiza
 
1 вступ робоче місце_інфографіка
Andy Levkovich
 
Get6 infographic
ARIN
 
Campana Siemens LF91BA582
Alsako Electrodomésticos
 
Bisogno, M. (2015), Goodwill and accounting discreption
University of Salerno
 
Khurram_Shahzad CV
khurram shahzad
 
imran cv
imran pasha
 
Sprawozdanie finansowe za 2015 FRSP bilans
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego
 
MM Bagali, HR, HRM, HRD, MBA, Research, India, Teaching, Faculty.....Dash board
dr m m bagali, phd in hr
 
Physiology of hemodynamics & PiCCO parameters in detail
meducationdotnet
 
A&m assessment help
greg robertson
 
CEE_Fund_SPRING_2015
Mitchell Phillips
 
Ad

Similar to Displaying Data from Multiple Tables - Oracle Data Base (20)

PPT
Les04 Displaying Data from Multiple Tables.ppt
DrZeeshanBhatti
 
PPT
Oracle sql joins
redro
 
PPT
Les05
Akmal Rony
 
PPT
Les04
Vijay Kumar
 
PPT
Sql join
Vikas Gupta
 
PPT
Join sql
Vikas Gupta
 
PPT
Les05
Sudharsan S
 
PPT
Displaying data from multiple tables
Syed Zaid Irshad
 
PPT
Les05 (Displaying Data from Multiple Table)
Achmad Solichin
 
PPT
App C
Sudharsan S
 
PPT
SQL Introduction to displaying data from multiple tables
Vibrant Technologies & Computers
 
PPT
e computer notes - From multiple tables
ecomputernotes
 
PDF
SQL JOINS
Swapnali Pawar
 
PDF
SQL JOINS
PuNeEt KuMaR
 
PPTX
SQL Join's
Muhammad Noman Fazil
 
PDF
Advance database system(part 8)
Abdullah Khosa
 
PPTX
Day-2 SQL Theory_V1.pptx
uzmasulthana3
 
PPTX
Lab4 join - all types listed
Balqees Al.Mubarak
 
PPTX
SQL JOIN
Ritwik Das
 
Les04 Displaying Data from Multiple Tables.ppt
DrZeeshanBhatti
 
Oracle sql joins
redro
 
Les05
Akmal Rony
 
Sql join
Vikas Gupta
 
Join sql
Vikas Gupta
 
Displaying data from multiple tables
Syed Zaid Irshad
 
Les05 (Displaying Data from Multiple Table)
Achmad Solichin
 
SQL Introduction to displaying data from multiple tables
Vibrant Technologies & Computers
 
e computer notes - From multiple tables
ecomputernotes
 
SQL JOINS
Swapnali Pawar
 
SQL JOINS
PuNeEt KuMaR
 
Advance database system(part 8)
Abdullah Khosa
 
Day-2 SQL Theory_V1.pptx
uzmasulthana3
 
Lab4 join - all types listed
Balqees Al.Mubarak
 
SQL JOIN
Ritwik Das
 
Ad

More from Salman Memon (20)

PPTX
PHP Array very Easy Demo
Salman Memon
 
PPTX
Complete Lecture on Css presentation
Salman Memon
 
PPTX
How to Use Dreamweaver cs6
Salman Memon
 
PPTX
what is programming and its clear Concepts to the point
Salman Memon
 
PPTX
Working with variables in PHP
Salman Memon
 
PPT
Web forms and html (lect 5)
Salman Memon
 
PPT
Web forms and html (lect 4)
Salman Memon
 
PPT
Web forms and html (lect 3)
Salman Memon
 
PPT
Web forms and html (lect 2)
Salman Memon
 
PPT
Web forms and html (lect 1)
Salman Memon
 
PPT
Managing in the Future Enterprise
Salman Memon
 
PPT
Overview of Technology Management
Salman Memon
 
PPT
Align Information Technology and Business Strategy
Salman Memon
 
PPTX
WHITE BOX & BLACK BOX TESTING IN DATABASE
Salman Memon
 
PPTX
Email security netwroking
Salman Memon
 
PPTX
Email security - Netwroking
Salman Memon
 
PPTX
Query decomposition in data base
Salman Memon
 
PPTX
Time Management
Salman Memon
 
PPTX
Multimedea device and routes
Salman Memon
 
PPTX
Hash function
Salman Memon
 
PHP Array very Easy Demo
Salman Memon
 
Complete Lecture on Css presentation
Salman Memon
 
How to Use Dreamweaver cs6
Salman Memon
 
what is programming and its clear Concepts to the point
Salman Memon
 
Working with variables in PHP
Salman Memon
 
Web forms and html (lect 5)
Salman Memon
 
Web forms and html (lect 4)
Salman Memon
 
Web forms and html (lect 3)
Salman Memon
 
Web forms and html (lect 2)
Salman Memon
 
Web forms and html (lect 1)
Salman Memon
 
Managing in the Future Enterprise
Salman Memon
 
Overview of Technology Management
Salman Memon
 
Align Information Technology and Business Strategy
Salman Memon
 
WHITE BOX & BLACK BOX TESTING IN DATABASE
Salman Memon
 
Email security netwroking
Salman Memon
 
Email security - Netwroking
Salman Memon
 
Query decomposition in data base
Salman Memon
 
Time Management
Salman Memon
 
Multimedea device and routes
Salman Memon
 
Hash function
Salman Memon
 

Recently uploaded (20)

PPTX
2025 HackRedCon Cyber Career Paths.pptx Scott Stanton
Scott Stanton
 
PPTX
Reimaginando la Ciberdefensa: De Copilots a Redes de Agentes
Cristian Garcia G.
 
PDF
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
PDF
Enhancing Environmental Monitoring with Real-Time Data Integration: Leveragin...
Safe Software
 
PDF
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
PDF
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
PDF
Java 25 and Beyond - A Roadmap of Innovations
Ana-Maria Mihalceanu
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PPTX
The birth and death of Stars - earth and life science
rizellemarieastrolo
 
PDF
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
PDF
Simplify Your FME Flow Setup: Fault-Tolerant Deployment Made Easy with Packer...
Safe Software
 
PDF
My Journey from CAD to BIM: A True Underdog Story
Safe Software
 
PDF
Pipeline Industry IoT - Real Time Data Monitoring
Safe Software
 
PDF
Redefining Work in the Age of AI - What to expect? How to prepare? Why it mat...
Malinda Kapuruge
 
PPTX
Smart Factory Monitoring IIoT in Machine and Production Operations.pptx
Rejig Digital
 
PDF
''Taming Explosive Growth: Building Resilience in a Hyper-Scaled Financial Pl...
Fwdays
 
PPTX
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
PDF
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
PPTX
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
2025 HackRedCon Cyber Career Paths.pptx Scott Stanton
Scott Stanton
 
Reimaginando la Ciberdefensa: De Copilots a Redes de Agentes
Cristian Garcia G.
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
Enhancing Environmental Monitoring with Real-Time Data Integration: Leveragin...
Safe Software
 
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
Java 25 and Beyond - A Roadmap of Innovations
Ana-Maria Mihalceanu
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
The birth and death of Stars - earth and life science
rizellemarieastrolo
 
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
Simplify Your FME Flow Setup: Fault-Tolerant Deployment Made Easy with Packer...
Safe Software
 
My Journey from CAD to BIM: A True Underdog Story
Safe Software
 
Pipeline Industry IoT - Real Time Data Monitoring
Safe Software
 
Redefining Work in the Age of AI - What to expect? How to prepare? Why it mat...
Malinda Kapuruge
 
Smart Factory Monitoring IIoT in Machine and Production Operations.pptx
Rejig Digital
 
''Taming Explosive Growth: Building Resilience in a Hyper-Scaled Financial Pl...
Fwdays
 
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 

Displaying Data from Multiple Tables - Oracle Data Base

  • 1. 4 Copyright © Oracle Corporation, 2001. All rights reserved. Displaying Data from Multiple Tables
  • 2. 4-2 Copyright © Oracle Corporation, 2001. All rights reserved. Objectives After completing this lesson, you should be able to do the following: • Write SELECT statements to access data from more than one table using equality and nonequality joins • View data that generally does not meet a join condition by using outer joins • Join a table to itself by using a self join
  • 3. 4-3 Copyright © Oracle Corporation, 2001. All rights reserved. Obtaining Data from Multiple Tables EMPLOYEES DEPARTMENTS … …
  • 4. 4-4 Copyright © Oracle Corporation, 2001. All rights reserved. Cartesian Products • A Cartesian product is formed when: – A join condition is omitted – A join condition is invalid – All rows in the first table are joined to all rows in the second table • To avoid a Cartesian product, always include a valid join condition in a WHERE clause.
  • 5. 4-5 Copyright © Oracle Corporation, 2001. All rights reserved. Generating a Cartesian Product Cartesian product: 20x8=160 rows EMPLOYEES (20 rows) DEPARTMENTS (8 rows) … …
  • 6. 4-6 Copyright © Oracle Corporation, 2001. All rights reserved. • Equijoin • Non-equijoin • Outer join • Self join Types of Joins • Cross joins • Natural joins • Using clause • Full or two sided outer joins • Arbitrary join conditions for outer joins SQL: 1999 Compliant Joins: Oracle Proprietary Joins (8i and prior):
  • 7. 4-7 Copyright © Oracle Corporation, 2001. All rights reserved. Joining Tables Using Oracle Syntax Use a join to query data from more than one table. • Write the join condition in the WHERE clause. • Prefix the column name with the table name when the same column name appears in more than one table. SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column1 = table2.column2; SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column1 = table2.column2;
  • 8. 4-8 Copyright © Oracle Corporation, 2001. All rights reserved. What is an Equijoin? EMPLOYEES DEPARTMENTS Foreign key Primary key … …
  • 9. 4-9 Copyright © Oracle Corporation, 2001. All rights reserved. SELECT employees.employee_id, employees.last_name, employees.department_id, departments.department_id, departments.location_id FROM employees, departments WHERE employees.department_id = departments.department_id; Retrieving Records with Equijoins …
  • 10. 4-10 Copyright © Oracle Corporation, 2001. All rights reserved. Additional Search Conditions Using the AND Operator EMPLOYEES DEPARTMENTS … …
  • 11. 4-11 Copyright © Oracle Corporation, 2001. All rights reserved. Qualifying Ambiguous Column Names • Use table prefixes to qualify column names that are in multiple tables. • Improve performance by using table prefixes. • Distinguish columns that have identical names but reside in different tables by using column aliases.
  • 12. 4-12 Copyright © Oracle Corporation, 2001. All rights reserved. SELECT e.employee_id, e.last_name, e.department_id, d.department_id, d.location_id FROM employees e , departments d WHERE e.department_id = d.department_id; Using Table Aliases • Simplify queries by using table aliases. • Improve performance by using table prefixes.
  • 13. 4-13 Copyright © Oracle Corporation, 2001. All rights reserved. Joining More than Two Tables EMPLOYEES LOCATIONSDEPARTMENTS To join n tables together, you need a minimum of n-1 join conditions. For example, to join three tables, a minimum of two joins is required. …
  • 14. 4-14 Copyright © Oracle Corporation, 2001. All rights reserved. Non-Equijoins EMPLOYEES JOB_GRADES Salary in the EMPLOYEES table must be between lowest salary and highest salary in the JOB_GRADES table. …
  • 15. 4-15 Copyright © Oracle Corporation, 2001. All rights reserved. Retrieving Records with Non-Equijoins SELECT e.last_name, e.salary, j.grade_level FROM employees e, job_grades j WHERE e.salary BETWEEN j.lowest_sal AND j.highest_sal; …
  • 16. 4-16 Copyright © Oracle Corporation, 2001. All rights reserved. Outer Joins EMPLOYEESDEPARTMENTS There are no employees in department 190. …
  • 17. 4-17 Copyright © Oracle Corporation, 2001. All rights reserved. Outer Joins Syntax • You use an outer join to also see rows that do not meet the join condition. • The Outer join operator is the plus sign (+). SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column(+) = table2.column; SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column(+) = table2.column; SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column = table2.column(+); SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column = table2.column(+);
  • 18. 4-18 Copyright © Oracle Corporation, 2001. All rights reserved. SELECT e.last_name, e.department_id, d.department_name FROM employees e, departments d WHERE e.department_id(+) = d.department_id ; Using Outer Joins …
  • 19. 4-19 Copyright © Oracle Corporation, 2001. All rights reserved. Self Joins EMPLOYEES (WORKER) EMPLOYEES (MANAGER) MANAGER_ID in the WORKER table is equal to EMPLOYEE_ID in the MANAGER table. … …
  • 20. 4-20 Copyright © Oracle Corporation, 2001. All rights reserved. Joining a Table to Itself SELECT worker.last_name || ' works for ' || manager.last_name FROM employees worker, employees manager WHERE worker.manager_id = manager.employee_id ; …
  • 21. 4-21 Copyright © Oracle Corporation, 2001. All rights reserved. Practice 4, Part One: Overview This practice covers writing queries to join tables together using Oracle syntax.
  • 22. 4-22 Copyright © Oracle Corporation, 2001. All rights reserved. Joining Tables Using SQL: 1999 Syntax Use a join to query data from more than one table. SELECT table1.column, table2.column FROM table1 [CROSS JOIN table2] | [NATURAL JOIN table2] | [JOIN table2 USING (column_name)] | [JOIN table2 ON(table1.column_name = table2.column_name)] | [LEFT|RIGHT|FULL OUTER JOIN table2 ON (table1.column_name = table2.column_name)]; SELECT table1.column, table2.column FROM table1 [CROSS JOIN table2] | [NATURAL JOIN table2] | [JOIN table2 USING (column_name)] | [JOIN table2 ON(table1.column_name = table2.column_name)] | [LEFT|RIGHT|FULL OUTER JOIN table2 ON (table1.column_name = table2.column_name)];
  • 23. 4-23 Copyright © Oracle Corporation, 2001. All rights reserved. Creating Cross Joins • The CROSS JOIN clause produces the cross- product of two tables. • This is the same as a Cartesian product between the two tables. SELECT last_name, department_name FROM employees CROSS JOIN departments ; …
  • 24. 4-24 Copyright © Oracle Corporation, 2001. All rights reserved. Creating Natural Joins • The NATURAL JOIN clause is based on all 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.
  • 25. 4-25 Copyright © Oracle Corporation, 2001. All rights reserved. SELECT department_id, department_name, location_id, city FROM departments NATURAL JOIN locations ; Retrieving Records with Natural Joins
  • 26. 4-26 Copyright © Oracle Corporation, 2001. All rights reserved. Creating Joins with the USING Clause • If several columns have the same names but the data types do not match, the NATURAL JOIN clause can be modified with 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. • Do not use a table name or alias in the referenced columns. • The NATURAL JOIN and USING clauses are mutually exclusive.
  • 27. 4-27 Copyright © Oracle Corporation, 2001. All rights reserved. SELECT e.employee_id, e.last_name, d.location_id FROM employees e JOIN departments d USING (department_id) ; Retrieving Records with the USING Clause …
  • 28. 4-28 Copyright © Oracle Corporation, 2001. All rights reserved. Creating Joins with the ON Clause • The join condition for the natural join is basically an equijoin of all columns with the same name. • To specify arbitrary conditions or specify columns to join, the ON clause is used. • The join condition is separated from other search conditions. • The ON clause makes code easy to understand.
  • 29. 4-29 Copyright © Oracle Corporation, 2001. All rights reserved. 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); Retrieving Records with the ON Clause …
  • 30. 4-30 Copyright © Oracle Corporation, 2001. All rights reserved. Creating Three-Way Joins with the ON Clause SELECT employee_id, city, department_name FROM employees e JOIN departments d ON d.department_id = e.department_id JOIN locations l ON d.location_id = l.location_id; …
  • 31. 4-31 Copyright © Oracle Corporation, 2001. All rights reserved. INNER Versus OUTER Joins • In SQL: 1999, the join of two tables returning only matched rows is an inner join. • A join between two tables that returns the results of the inner join as well as unmatched rows left (or right) tables is 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.
  • 32. 4-32 Copyright © Oracle Corporation, 2001. All rights reserved. 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) ; LEFT OUTER JOIN …
  • 33. 4-33 Copyright © Oracle Corporation, 2001. All rights reserved. SELECT e.last_name, e.department_id, d.department_name FROM employees e RIGHT OUTER JOIN departments d ON (e.department_id = d.department_id) ; RIGHT OUTER JOIN …
  • 34. 4-34 Copyright © Oracle Corporation, 2001. All rights reserved. SELECT e.last_name, e.department_id, d.department_name FROM employees e FULL OUTER JOIN departments d ON (e.department_id = d.department_id) ; FULL OUTER JOIN …
  • 35. 4-35 Copyright © Oracle Corporation, 2001. All rights reserved. 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 ; Additional Conditions
  • 36. 4-36 Copyright © Oracle Corporation, 2001. All rights reserved. Summary In this lesson, you should have learned how to use joins to display data from multiple tables in: • Oracle proprietary syntax for versions 8i and earlier • SQL: 1999 compliant syntax for version 9i
  • 37. 4-37 Copyright © Oracle Corporation, 2001. All rights reserved. Practice 4, Part Two: Overview This practice covers the following topics: • Joining tables using an equijoin • Performing outer and self joins • Adding conditions
  • 38. 4-40 Copyright © Oracle Corporation, 2001. All rights reserved.

Editor's Notes

  • #2: Schedule:TimingTopic 55 minutesLecture 55 minutesPractice 110 minutesTotal
  • #3: Lesson Aim This lesson covers how to obtain data from more than one table.
  • #4: Data from Multiple Tables Sometimes you need to use data from more than one table. In the slide example, the report displays data from two separate tables. Employee IDs exist in the EMPLOYEES table. Department IDs exist in both the EMPLOYEES and DEPARTMENTS tables. Location IDs exist in the DEPARTMENTS table. To produce the report, you need to link the EMPLOYEES and DEPARTMENTS tables and access data from both of them.
  • #5: Cartesian Products When a join condition is invalid or omitted completely, the result is a Cartesian product, in which all combinations of rows are displayed. All rows in the first table are joined to all rows in the second table. A Cartesian product tends to generate a large number of rows, and the result is rarely useful. You should always include a valid join condition in a WHERE clause, unless you have a specific need to combine all rows from all tables. Cartesian products are useful for some tests when you need to generate a large number of rows to simulate a reasonable amount of data.
  • #6: Cartesian Products (continued) A Cartesian product is generated if a join condition is omitted. The example on the slide displays employee last name and department name from the EMPLOYEES and DEPARTMENTS tables. Because no WHERE clause has been specified, all rows (20 rows) from the EMPLOYEES table are joined with all rows (8 rows) in the DEPARTMENTS table, thereby generating 160 rows in the output. SELECT last_name, department_name dept_name FROM employees, departments; Instructor Note Demo: 4_cart.sql Purpose: To illustrate executing a Cartesian product
  • #7: Types of Joins The Oracle9i database offers join syntax that is SQL: 1999 compliant. Prior to the 9i release, the join syntax was different from the ANSI standards. The new SQL: 1999 compliant join syntax does not offer any performance benefits over the Oracle proprietary join syntax that existed in prior releases. Instructor Note Do not get into details of all the types of joins now. Explain each join one by one, as is done in the following slides.
  • #8: Defining Joins When data from more than one table in the database is required, a join condition is used. Rows in one table can be joined to rows in another table according to common values existing in corresponding columns, that is, usually primary and foreign key columns. To display data from two or more related tables, write a simple join condition in the WHERE clause. In the syntax: table1.columndenotes the table and column from which data is retrieved table1.column1 =is the condition that joins (or relates) the tables togethertable2.column2 Guidelines When writing a SELECT statement that joins tables, precede the column name with the table name for clarity and to enhance database access. If the same column name appears in more than one table, the column name must be prefixed with the table name. To join n tables together, you need a minimum of n-1 join conditions. For example, to join four tables, a minimum of three joins is required. This rule may not apply if your table has a concatenated primary key, in which case more than one column is required to uniquely identify each row. For more information, see Oracle9i SQL Reference, “SELECT.”
  • #9: Equijoins To determine an employee’s department name, you compare the value in the DEPARTMENT_ID column in the EMPLOYEES table with the DEPARTMENT_ID values in the DEPARTMENTS table. The relationship between the EMPLOYEES and DEPARTMENTS tables is an equijoin—that is, values in the DEPARTMENT_ID column on both tables must be equal. Frequently, this type of join involves primary and foreign key complements. Note: Equijoins are also called simple joins or inner joins. Instructor Note Explain the use of a decision matrix for simplifying writing joins. For example, if you want to display the name and department number of all the employees who are in the same department as Goyal, you can start by making the following decision tree: Columns to DisplayOriginating TableCondition last_nameemployeeslast_name='Goyal' department_namedepartmentsemployees.department_id = departments.department_id Now the SQL statement can be easily formulated by looking at the decision matrix. The first column gives the column list in the SELECT statement, the second column gives the tables for the FROM clause, and the third column gives the condition for the WHERE clause.
  • #10: Retrieving Records with Equijoins In the slide example: The SELECT clause specifies the column names to retrieve: employee last name, employee number, and department number, which are columns in the EMPLOYEES table department number, department name, and location ID, which are columns in the DEPARTMENTS table The FROM clause specifies the two tables that the database must access: EMPLOYEES table DEPARTMENTS table The WHERE clause specifies how the tables are to be joined: EMPLOYEES.DEPARTMENT_ID = DEPARTMENTS.DEPARTMENT_ID Because the DEPARTMENT_ID column is common to both tables, it must be prefixed by the table name to avoid ambiguity.
  • #11: Additional Search Conditions In addition to the join, you may have criteria for your WHERE clause to restrict the rows under consideration for one or more tables in the join. For example, to display employee Matos' department number and department name, you need an additional condition in the WHERE clause. SELECT last_name, employees.department_id, department_name FROM employees, departments WHERE employees.department_id = departments.department_id AND last_name = 'Matos';
  • #12: Qualifying Ambiguous Column Names You need to qualify the names of the columns in the WHERE clause with the table name to avoid ambiguity. Without the table prefixes, the DEPARTMENT_ID column could be from either the DEPARTMENTS table or the EMPLOYEES table. It is necessary to add the table prefix to execute your query. If there are no common column names between the two tables, there is no need to qualify the columns. However, using the table prefix improves performance, because you tell the Oracle Server exactly where to find the columns. The requirement to qualify ambiguous column names is also applicable to columns that may be ambiguous in other clauses, such as the SELECT clause or the ORDER BY clause. Instructor Note Demo: 4_loc.sql Purpose: To illustrate a SELECT clause with no aliases.
  • #13: Table Aliases Qualifying column names with table names can be very time consuming, particularly if table names are lengthy. You can use table aliases instead of table names. Just as a column alias gives a column another name, a table alias gives a table another name. Table aliases help to keep SQL code smaller, therefore using less memory. Notice how table aliases are identified in the FROM clause in the example. The table name is specified in full, followed by a space and then the table alias. The EMPLOYEES table has been given an alias of e, and the DEPARTMENTS table has an alias of d. Guidelines Table aliases can be up to 30 characters in length, but shorter is better. If a table alias is used for a particular table name in the FROM clause, then that table alias must be substituted for the table name throughout the SELECT statement. Table aliases should be meaningful. The table alias is valid only for the current SELECT statement.
  • #14: Additional Search Conditions Sometimes you may need to join more than two tables. For example, to display the last name, the department name, and the city for each employee, you have to join the EMPLOYEES, DEPARTMENTS, and LOCATIONS tables. SELECT e.last_name, d.department_name, l.city FROM employees e, departments d, locations l WHERE e.department_id = d.department_id AND d.location_id = l.location_id;
  • #15: Non-Equijoins A non-equijoin is a join condition containing something other than an equality operator. The relationship between the EMPLOYEES table and the JOB_GRADES table has an example of a non-equijoin. A relationship between the two tables is that the SALARY column in the EMPLOYEES table must be between the values in the LOWEST_SALARY and HIGHEST_SALARY columns of the JOB_GRADES table. The relationship is obtained using an operator other than equals (=).
  • #16: Non-Equijoins (continued) The slide example creates a non-equijoin to evaluate an employee’s salary grade. The salary must be between any pair of the low and high salary ranges. It is important to note that all employees appear exactly once when this query is executed. No employee is repeated in the list. There are two reasons for this: None of the rows in the job grade table contain grades that overlap. That is, the salary value for an employee can lie only between the low salary and high salary values of one of the rows in the salary grade table. All of the employees’ salaries lie within the limits provided by the job grade table. That is, no employee earns less than the lowest value contained in the LOWEST_SAL column or more than the highest value contained in the HIGHEST_SAL column. Note: Other conditions, such as <= and >= can be used, but BETWEEN is the simplest. Remember to specify the low value first and the high value last when using BETWEEN. Table aliases have been specified in the slide example for performance reasons, not because of possible ambiguity. Instructor Note Explain that BETWEEN … AND … is actually translated by the Oracle server to a pair of AND conditions (a >= lower limit) and (a <= higher limit) and IN ( … ) is translated by the Oracle server to a set of OR conditions (a = value1 OR a = value2 OR a = value3 ). So using BETWEEN … AND … , IN(…) has no performance benefits; the benefit is logical simplicity.
  • #17: Returning Records with No Direct Match with Outer Joins If a row does not satisfy a join condition, the row will not appear in the query result. For example, in the equijoin condition of EMPLOYEES and DEPARTMENTS tables, employee Grant does not appear because there is no department ID recorded for her in the EMPLOYEES table. Instead of seeing 20 employees in the result set, you see 19 records. SELECT e.last_name, e.department_id, d.department_name FROM employees e, departments d WHERE e.department_id = d.department_id;
  • #18: Using Outer Joins to Return Records with No Direct Match The missing rows can be returned if an outer join operator is used in the join condition. The operator is a plus sign enclosed in parentheses (+), and it is placed on the “side” of the join that is deficient in information. This operator has the effect of creating one or more null rows, to which one or more rows from the nondeficient table can be joined. In the syntax: table1.column =is the condition that joins (or relates) the tables together. table2.column (+)is the outer join symbol, which can be placed on either side of theWHERE clause condition, but not on both sides. (Place the outerjoin symbol following the name of the column in the table without the matching rows.) Instructor Note Demo: 4_ejoin.sql Purpose: To illustrate an equijoin leading to an outer join.
  • #19: Using Outer Joins to Return Records with No Direct Match (continued) The slide example displays employee last names, department ID’s and department names. The Contracting department does not have any employees. The empty value is shown in the output shown. Outer Join Restrictions The outer join operator can appear on only one side of the expression—the side that has information missing. It returns those rows from one table that have no direct match in the other table. A condition involving an outer join cannot use the IN operator or be linked to another condition by the OR operator. Instructor Note The UNION operator works around the issue of being able to use an outer join operator on one side of the expression. The ANSI full outer join also allows you to have an outer join on both sides of the expression. It is discussed later in this lesson. Demo: 4_ojoin.sql Purpose: To illustrate an outer join.
  • #20: Joining a Table to Itself Sometimes you need to join a table to itself. To find the name of each employee’s manager, you need to join the EMPLOYEES table to itself, or perform a self join. For example, to find the name of Whalen’s manager, you need to: Find Whalen in the EMPLOYEES table by looking at the LAST_NAME column. Find the manager number for Whalen by looking at the MANAGER_ID column. Whalen’s manager number is 101. Find the name of the manager with EMPLOYEE_ID 101 by looking at the LAST_NAME column. Kochhar’s employee number is 101, so Kochhar is Whalen’s manager. In this process, you look in the table twice. The first time you look in the table to find Whalen in the LAST_NAME column and MANAGER_ID value of 101. The second time you look in the EMPLOYEE_ID column to find 101 and the LAST_NAME column to find Kochhar. Instructor Note Show the data from the EMPLOYEES table and point out how each manager is also an employee.
  • #21: Joining a Table to Itself (continued) The slide example joins the EMPLOYEES table to itself. To simulate two tables in the FROM clause, there are two aliases, namely w and m, for the same table, EMPLOYEES. In this example, the WHERE clause contains the join that means “where a worker’s manager number matches the employee number for the manager.” Instructor Note Point out the following to the students: The column heading in the result of the query on the slide seems meaningless. A meaningful column alias should have been used instead. There are only 19 rows in the output, but there are 20 rows in the EMPLOYEES table. This occurs because employee King, who is the president, does not have a manager.
  • #22: Practice 4, Part One: Overview This practice is designed to give you a variety of exercises that join tables together using the Oracle syntax shown in the lesson so far. Complete practice questions 1- 4 at the end of this lesson.
  • #23: Defining Joins Using the SQL: 1999 syntax, you can obtain the same results as were shown in the prior pages. In the syntax: table1.columnDenotes the table and column from which data is retrieved CROSS JOINReturns a Cartesian product from the two tables NATURAL JOINJoins two tables based on the same column name JOIN table USING column_namePerforms an equijoin based on the column name JOIN table ON table1.column_name Performs an equijoin based on the condition in the ON clause = table2.column_name LEFT/RIGHT/FULL OUTER For more information, see Oracle9i SQL Reference, “SELECT.”
  • #24: Creating Cross Joins The example on the slide gives the same results as the following: SELECT last_name, department_name FROM employees, departments;
  • #25: Creating Natural Joins It was not possible to do a join without explicitly specifying the columns in the corresponding tables in prior releases of Oracle. In Oracle9i it is possible to let the join be completed automatically based on columns in the two tables which have matching data types and names, using the keywords NATURAL JOIN keywords. Note: The join can happen only on columns having the same names and data types in both the tables. If the columns have the same name, but different data types, then the NATURAL JOIN syntax causes an error.
  • #26: Retrieving Records with Natural Joins In the example on the slide, the LOCATIONS table is joined to the DEPARTMENT table by the LOCATION_ID column, which is the only column of the same name in both tables. If other common columns were present, the join would have used them all. Equijoins The natural join can also be written as an equijoin: SELECT department_id, department_name, departments.location_id, city FROM departments, locations WHERE departments.location_id = locations.location_id; Natural Joins with a WHERE Clause Additional restrictions on a natural join are implemented by using a WHERE clause. The example below limits the rows of output to those with a department ID equal to 20 or 50. SELECT department_id, department_name, location_id, city FROM departments NATURAL JOIN locations WHERE department_id IN (20, 50);
  • #27: The USING Clause Natural joins use all columns with matching names and data types to join the tables. The USING clause can be used to specify only those columns that should be used for an equijoin. The columns referenced in the USING clause should not have a qualifier (table name or alias) anywhere in the SQL statement. For example, this statement is valid: SELECT l.city, d.department_name FROM locations l JOIN departments d USING (location_id) WHERE location_id = 1400; This statement is invalid because the LOCATION_ID is qualified in the WHERE clause: SELECT l.city, d.department_name FROM locations l JOIN departments d USING (location_id) WHERE d.location_id = 1400; ORA-25154: column part of USING clause cannot have qualifier The same restriction applies to NATURAL joins also. Therefore columns that have the same name in both tables have to be used without any qualifiers.
  • #28: The USING Clause (continued) The example shown joins the DEPARTMENT_ID column in the EMPLOYEES and DEPARTMENTS tables, and thus shows the location where an employee works. This can also be written as an equijoin: SELECT employee_id, last_name, employees.department_id, location_id FROM employees, departments WHERE employees.department_id = departments.department_id;
  • #29: The ON Condition Use the ON clause to specify a join condition. This lets you specify join conditions separate from any search or filter conditions in the WHERE clause.
  • #30: Creating Joins with the ON Clause The ON clause can also be used as follows to join columns that have different names: SELECT e.last_name emp, m.last_name mgr FROM employees e JOIN employees m ON (e.manager_id = m.employee_id); The preceding example is a selfjoin of the EMPLOYEE table to itself, based on the EMPLOYEE_ID and MANAGER_ID columns.
  • #31: Three-Way Joins A three-way join is a join of three tables. In SQL: 1999 compliant syntax, joins are performed from left to right so the first join to be performed is EMPLOYEES JOIN DEPARTMENTS. The first join condition can reference columns in EMPLOYEES and DEPARTMENTS but cannot reference columns in LOCATIONS. The second join condition can reference columns from all three tables. This can also be written as a three-way equijoin: SELECT employee_id, city, department_name FROM employees, departments, locations WHERE employees.department_id = departments.department_id AND departments.location_id = locations.location_id; Instructor Note The example shown can also be accomplished with the USING clause: SELECT e.employee_id, l.city, d.department_name FROM employees e JOIN departments d USING (department_id) JOIN locations l USING (location_id);
  • #32: Joins - Comparing SQL: 1999 to Oracle Syntax
  • #33: Example of LEFT OUTER JOIN This query retrieves all rows in the EMPLOYEES table, which is the left table even if there is no match in the DEPARTMENTS table. This query was completed in earlier releases as follows: SELECT e.last_name, e.department_id, d.department_name FROM employees e, departments d WHERE d.department_id (+) = e.department_id;
  • #34: Example of RIGHT OUTER JOIN This query retrieves all rows in the DEPARTMENTS table, which is the right table even if there is no match in the EMPLOYEES table. This query was completed in earlier releases as follows: SELECT e.last_name, e.department_id, d.department_name FROM employees e, departments d WHERE d.department_id = e.department_id (+);
  • #35: Example of FULL OUTER JOIN This query retrieves all rows in the EMPLOYEES table, even if there is no match in the DEPARTMENTS table. It also retrieves all rows in the DEPARTMENTS table, even if there is no match in the EMPLOYEES table. Instructor Note It was not possible to complete this in earlier releases using outer joins. However, you could accomplish the same results using the UNION operator. SELECT e.last_name, e.department_id, d.department_name FROM employees e, departments d WHERE e.department_id (+) = d.department_id UNION SELECT e.last_name, e.department_id, d.department_name FROM employees e, departments d WHERE e.department_id = d.department_id (+);
  • #36: Applying Additional Conditions You can apply additional conditions in the WHERE clause. The example shown performs a join on the EMPLOYEES and DEPARTMENTS tables, and, in addition, displays only employees with a manager ID equal to 149.
  • #37: Summary There are multiple ways to join tables. Types of Joins Equijoins Non-equijoins Outer joins Self joins Cross joins Natural joins Full or outer joins Cartesian Products A Cartesian product results in all combinations of rows displayed. This is done by either omitting the WHERE clause or specifying the CROSS JOIN clause. Table Aliases Table aliases speed up database access. Table aliases can help to keep SQL code smaller, by conserving memory.
  • #38: Practice 4, Part Two: Overview This practice is intended to give you practical experience in extracting data from more than one table. Try using both the Oracle proprietary syntax and the SQL: 1999 compliant syntax. In Part Two, questions 5-8, try writing the join statements using ANSI syntax. In Part Two, questions 9-11, try writing the join statements using both the Oracle syntax and the ANSI syntax.
  • #39: Practice 4 - Part One 1. Write a query to display the last name, department number, and department name forall employees. 2.Create a unique listing of all jobs that are in department 80. Include the location of the department in the output. 3. Write a query to display the employee last name, department name, location ID, and city of all employees who earn a commission.
  • #40: Practice 4 - Part One (continued) 4.Display the employee last name and department name for all employees who have an a (lowercase) in their last names. Place your SQL statement in a text file named lab4_4.sql.
  • #41: Practice 4 - Part Two 5.Write a query to display the last name, job, department number, and department name for allemployees who work in Toronto. 6.Display the employee last name and employee number along with their manager’s last name and manager number. Label the columns Employee, Emp#, Manager, and Mgr#, respectively.Place your SQL statement in a text file named lab4_6.sql.
  • #42: Practice 4 - Part Two (continued) 7.Modify lab4_6.sql to display all employees including King, who has no manager. Order the results by the employee number.Place your SQL statement in a text file named lab4_7.sql. Run the query in lab4_7.sql. If you have time, complete the following exercises: 8.Create a query that displays employee last names, department numbers, and all theemployees who work in the same department as a given employee. Give each column an appropriate label.
  • #43: Practice 4 - Part Two (continued) 9.Show the structure of the JOB_GRADES table. Create a query that displays the name, job,department name, salary, and grade for all employees. If you want an extra challenge, complete the following exercises: 10.Create a query to display the name and hire date of any employee hired after employee Davies.
  • #44: Practice 4 - Part Two (continued) 11.Display the names and hire dates for all employees who were hired before their managers, along with their manager’s names and hire dates. Label the columns Employee, EmpHired, Manager, and Mgr Hired, respectively.