0% found this document useful (0 votes)
64 views

Labsheet12 Join

This document provides guidance on performing various types of joins in SQL, including natural joins, cross joins, joins using the USING and ON clauses, and joins across three tables. Key concepts covered include joining tables based on equal columns, combining all row combinations between tables, and restricting rows during a join using a WHERE clause. The objectives are to create SELECT statements that implement natural joins, cross joins, joins with USING and ON, and joins across multiple tables.

Uploaded by

deftsoftp
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views

Labsheet12 Join

This document provides guidance on performing various types of joins in SQL, including natural joins, cross joins, joins using the USING and ON clauses, and joins across three tables. Key concepts covered include joining tables based on equal columns, combining all row combinations between tables, and restricting rows during a join using a WHERE clause. The objectives are to create SELECT statements that implement natural joins, cross joins, joins with USING and ON, and joins across multiple tables.

Uploaded by

deftsoftp
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Kingdom of Saudi Arabia

Ministry of Higher Education


King Faisal University
College of Computer Sciences &
Information Technology

IS222 – DATABASE
CONCEPTS AND DESIGN
Lab sheet
Lab 12: JOINS

IS222
Table of Contents
LAB 12: JOINS.....................................................................................................................2
Objectives:.................................................................................................................................2
Tools/Software:.........................................................................................................................2
Concepts & Descriptions:............................................................................................................2
Relational DBMS..........................................................................................................................................2
SELECT Statement with NATURAL JOIN........................................................................................................4
SELECT Statement with CROSS JOIN............................................................................................................4
SELECT Statement with JOIN and USING Clause..........................................................................................4
SELECT Statement with JOIN and ON Clause...............................................................................................5
SELECT Statement to Join 3 Tables..............................................................................................................5
SELECT Statement with LEFT and RIGHT OUTER JOIN..................................................................................5
SELECT Statement with FULL OUTER JOIN...................................................................................................6
SELECT Statement with SELF JOIN................................................................................................................6
SELECT Statement with EQUIJOIN................................................................................................................6
SELECT Statement with Cartesian Product Join...........................................................................................7
SELECT Statement with Nonequijoin...........................................................................................................8
SELECT Statement with Outerjoin................................................................................................................8
Lab Activities:.............................................................................................................................0
Deliverables:..............................................................................................................................3
LAB 12: JOINS

Objectives:
This lesson covers the following objectives:
 create SELECT Statements using NATURAL JOIN
 create SELECT Statements using CROSS JOIN
 create SELECT Statements using JOIN and USING clause
 create SELECT Statements using JOIN and ON clause
 create SELECT Statements using JOIN of 3 tables
 create SELECT Statements using LEFT & RIGHT OUTER JOIN
 create SELECT Statements using FULL OUTER JOIN
 create SELECT Statements using Equijoin
 create SELECT Statements using Cartesian Product Join
 create SELECT Statements using Nonequijoin
 create SELECT Statements using Outer join

Tools/Software:
To accomplish this session, students should have access to APEX.

Concepts & Descriptions:


Relational DBMS

By now, you have learned from lecture that RDBMS applies tables that are related to
each other through a common column/s. In SQL_Schema.sql that you downloaded in Lab 1,
there are 4 table designs: employees/departments, wf_countries, fast foods, and DJs on
demand. They are all available in our APEX so it’s better to understand their relationships.

Let’s set the employees/departments as an example. You may refer to the figure in the
next page.

There are 8 tables and 7 of them are related through common fields or columns. The
lines connecting the tables signifies these relationships. For example, Regions is related to
Countries through their common field Region_ID. Note than Region_ID is the primary key of
Regions and a Foreign Key of Countries.

Up to now, your experience using SQL has been limited to querying and returning
information from one database table at a time. This would not be a problem if all data in the
database were stored in only one table. But you know from data modeling that separating data
into individual tables and being able to associate the tables with one another is the heart of
relational database design.
Fortunately, SQL provides join conditions that enable information to be queried from
separate tables and combined in one report.

A SQL join clause combines fields from 2 (or more) tables in a relational database.
SELECT Statement with 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.

Example Explanation
SELECT first_name, last_name, job_id, job_title This join will return columns from the
FROM employees NATURAL JOIN jobs employees table and their related
WHERE department_id > 80; job_title from the jobs table based on the
common column job_id.

SELECT department_name, city The departments and locations table


FROM departments NATURAL JOIN locations; both have a column, location_id, which
is used to join the two tables. Notice that
the natural join column does not have to
appear in the SELECT clause.

SELECT Statement with CROSS JOIN


CROSS JOIN joins each row in one table to every row in the other table. The result
set represents all possible row combinations from the two tables. If you CROSS JOIN a table
with 20 rows with a table with 100 rows, the query will return 2000 rows.

Example Explanation
SELECT last_name, department_name The employees table contains 20 rows
FROM employees CROSS JOIN departments; and the departments table has 8 rows.
Performing a CROSS JOIN will return
160 rows.

SELECT Statement with JOIN and USING Clause


In a natural join, if the tables have columns with the same names but different data
types, the join causes an error. To avoid this situation, the join clause can be modified with a
USING clause. The USING clause specifies the columns that should be used for the join.

Example Explanation
SELECT first_name, last_name, department_id, The columns referenced in the USING
department_name FROM employees JOIN clause should not have a qualifier (table
departments USING (department_id); name or alias) anywhere in the SQL
statement.

SELECT first_name, last_name, department_id, The USING clause allows us to use


department_name WHERE to restrict rows from one or
FROM employees JOIN departments USING both tables.
(department_id)
WHERE last_name = 'Higgins';
SELECT Statement with JOIN and 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.

Example Explanation
SELECT last_name, job_title In this example, the ON clause is used to
FROM employees e JOIN jobs j join the employees table with the jobs
ON (e.job_id = j.job_id); table.

SELECT last_name, job_title Here is the same query with a WHERE


FROM employees e JOIN jobs j clause to restrict the rows selected.
ON (e.job_id = j.job_id)
WHERE last_name LIKE 'H%';

SELECT last_name, salary, grade_level, This is to know the grade_level for each
lowest_sal, highest_sal employees salary. Even if the
FROM employees JOIN job_grades job_grades table does not have a
ON(salary BETWEEN lowest_sal AND common column with the employees
highest_sal); table.

SELECT Statement to Join 3 Tables


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.

Example Explanation
SELECT last_name, department_name AS To produce a report of employees, their
"Department", city department, and the city where the
FROM employees JOIN departments USING department is located, we need to join
(department_id) three tables: employees, departments
JOIN locations USING (location_id); and locations.

SELECT Statement with LEFT and RIGHT OUTER JOIN


A join of two or more tables that returns only the matched rows is called an inner join.
When a join returns the unmatched rows as well as the matched rows, it is called an outer
join.

Example Explanation
SELECT e.last_name, d.department_id, note that the table name listed to the left
d.department_name of the words "left outer join" is referred
FROM employees e to as the "left table."
LEFT OUTER JOIN departments d ON
(e.department_id = d.department_id);
Example Explanation
SELECT e.last_name, d.department_id, This query will return all employee last
d.department_name names, both those that are assigned to a
FROM employees e department and those that are not.
LEFT OUTER JOIN departments d ON
(e.department_id = d.department_id);

SELECT Statement with FULL OUTER JOIN


It is possible to create a join condition to retrieve all matching rows and all unmatched
rows from both tables. Using a full outer join solves this problem. The result set of a full
outer join includes all rows from a left outer join and all rows from a right outer join
combined together without duplication.

Example Explanation
SELECT e.last_name, d.department_id, Employees and departments tables are
d.department_name fully joined on their department_id using
FROM employees e FULL OUTER JOIN.
FULL OUTER JOIN departments d ON
(e.department_id = d.department_id);

SELECT Statement with SELF JOIN


To join a table to itself, the table is given two names or aliases. This will make the
database "think" that there are two tables.

Example Explanation
SELECT worker.last_name, worker.manager_id, “Manager name” is alias names that
manager.last_name relate to the data's association with that
AS "Manager name" table. Manager_id in the worker table is
FROM employees worker JOIN employees equal to employee_id in the manager
manager table.
ON (worker.manager_id = manager.employee_id);

SELECT Statement with EQUIJOIN


Sometimes called a "simple" or "inner" join, an equijoin is a table join that combines
rows that have the same values for the specified columns.
An equijoin is equivalent to ANSI:
 NATURAL JOIN
 JOIN USING
 JOIN ON (when the join condition uses "=")

SELECT <table1.column>, < table2.column> FROM <table1>,<table2>,


WHERE < table1.column1> = < table2.column2> ;
Example Explanation
SELECT employees.last_name, employees.job_id, Joins 2 tables using their common
jobs.job_title column job_id
FROM employees, jobs
WHERE employees.job_id = jobs.job_id;

SELECT employees.last_name, Joins 2 tables using their common


departments.department_name column department_id
FROM employees, departments
WHERE employees.department_id =
departments.department_id;

Restricting Rows In a Join


SELECT employees.last_name, employees.job_id, As with single-table queries, the
jobs.job_title FROM employees, jobs WHERE WHERE clause can be used to restrict
employees.job_id = jobs.job_id AND the rows considered in one or more
employees.department_id = 80; tables of the join. The query shown uses
the AND operator to restrict the rows
returned.

Aliases
SELECT last_name, e.job_id, job_title FROM Table aliases are used in the query. But
employees e, jobs j WHERE e.job_id = j.job_id when column names are not duplicated
AND department_id = 80; between two tables, you do not need to
add the table name or alias to the
column name.

Join 3 Tables
SELECT last_name, city To produce a report of employees, their
FROM employees e, departments d, locations l department, and the city where the
WHERE e.department_id = d.department_id department is located, we need to join
AND d.location_id = l.location_id three tables: employees, departments
and locations.

SELECT Statement with Cartesian Product Join


 If two tables in a join query have no join condition specified in the WHERE clause or
the join condition is invalid, the Oracle Server returns the Cartesian product of the
two tables.
 This is a combination of each row of one table with each row of the other.
 A Cartesian product is equivalent to an ANSI CROSS JOIN.
 To avoid a Cartesian product, always include a valid join condition in a WHERE
clause.
Example Explanation
SELECT employees.last_name, In this query, the join condition has been
departments.department_name omitted
FROM employees, departments;

SELECT Statement with Nonequijoin


Example Explanation
SELECT last_name, salary, grade_level, To know the grade_level for each
lowest_sal, highest_sal employee's salary, while the job_grades
FROM employees, job_grades table does not have a common column
WHERE (salary BETWEEN lowest_sal AND with the employees table, we can use a
highest_sal); nonequijoin to join the two tables.

SELECT Statement with Outer join


 An outer join is used to see rows that have a corresponding value in another table plus
those rows in one of the tables that have no matching value in the other table.
 To indicate which table may have missing data using Oracle Join Syntax, add a plus
sign (+) after the table's column name in the WHERE clause of the query.

Example Explanation
SELECT e.last_name, d.department_id, This query will return all employee last
d.department_name names, including those that are assigned
FROM employees e, departments d to a department and those that are not.
WHERE e.department_id = The same results could be obtained
d.department_id(+); using an ANSI LEFT OUTER JOIN.

Outer Join and ANSI equivalents


The table below shows ANSI/ISO SQL: 99 joins and their equivalent Oracle outer
joins.
Lab Activities:
1. Write 3 SQL statements to select all columns when countries and regions tables are
joined.
Use Natural Join

SELECT *
FROM countries
NATURAL JOIN regions ;

Use Join and On

SELECT *
FROM countries
JOIN regions ON countries.region_id = regions.region_id;

Use Join and Using

SELECT *
FROM countries
JOIN regions USING (region_id);

2. Write 3 SQL statements to display location ID, state province, and country ID from
locations table, plus country name from countries table.
Use Natural Join
SELECT LOCATION_ID, STATE_PROVINCE,COUNTRY_ID, COUNTRY_NAME
FROM locations
NATURAL JOIN countries ;

Use Join and On

SELECT LOCATION_ID, STATE_PROVINCE, l.COUNTRY_ID, COUNTRY_NAME


FROM locations l
JOIN countries co ON l.country_id = co.country_id;

Use Join and Using

SELECT LOCATION_ID, STATE_PROVINCE, COUNTRY_ID, COUNTRY_NAME


FROM locations
JOIN countries USING (COUNTRY_ID);
3. Write 2 SQL statements to display employee ID, first name, and job ID from
employees table as well as job ID and start date from job_history table.
What JOIN types can you use for this? Why?
INNER JOIN is used to combine the rows from the "employees" and "job_history" tables
based on the employee_id column, which exists in both tables. This will retrieve only the
matching records from both tables.

LEFT JOIN is used to retrieve all the rows from the "employees" table, regardless of
whether they have a matching record in the "job_history" table. . If there is no match, the
columns from the "job_history" table will be NULL.

SQL Statement No. 1

SELECT e.employee_id, e.first_name, e.job_id, jh.job_id, jh.start_date


FROM employees e
JOIN job_history jh ON e.employee_id = jh.employee_id;

SQL Statement No. 2

SELECT e.employee_id, e.first_name, e.job_id, jh.job_id, jh.start_date


FROM employees e
LEFT JOIN job_history jh ON e.employee_id = jh.employee_id;

4. Use EQUIJOIN to write a SQL statement to display employee ID, first name, manager
ID, and manager’s name from employees table.

SELECT emp.EMPLOYEE_ID, emp.FIRST_NAME, emp.MANAGER_ID,


mgr.first_name || ' '|| mgr.last_name AS manager_name
FROM employees emp
JOIN employees mgr ON emp.manager_id = mgr.employee_id;

5. Use EQUIJOIN to write a SQL statement to display the employee ID, first name,
department ID, job ID from employees table, as well department name from
departments table and job title from jobs table.

SELECT emp.employee_id, emp.first_name, emp.department_id, emp.job_id,


dep.department_name, job.job_title
FROM employees emp
JOIN departments dep ON emp.department_id = dep.department_id
JOIN jobs job ON emp.job_id = job.job_id;
6. Use EQUIJOIN to write a SQL statement to select all columns when employees and
departments tables are joined using department ID.

SELECT *
FROM employees emp
JOIN departments dep ON emp.department_id = dep.department_id;

7. Use EQUIJOIN to write a SQL statement to display an employee’s employee ID, first
name, last name, department ID, department name, job ID, and job title by joining
employees, departments, and jobs tables.

SELECT emp.employee_id, emp.first_name, emp.last_name, emp.department_id,


dep.department_name, emp.job_id, job.job_title
FROM employees emp,departments dep,jobs job
where emp.department_id=dep.department_id and emp.job_id = job.job_id;

8. Use EQUIJOIN to write a SQL statement to display employee ID, first name, job ID,
and job title from employees and jobs tables, as well as start date, job ID, and job titl
from job_history and jobs tables.

SELECT emp.employee_id, emp.first_name, emp.job_id, job.job_title, jh.job_id,


jobh.job_title, jh.start_date
FROM employees emp
JOIN jobs job ON emp.job_id = job.job_id
JOIN job_history jh ON emp.employee_id = jh.employee_id
JOIN jobs jobh ON jh.job_id =jobh.job_id;

9. Create a query of the Oracle database that shows employee last names , department
IDs, and department names. Include all employees even if they are not assigned to a
department.

SELECT emp.LAST_NAME, emp.DEPARTMENT_ID, dep.DEPARTMENT_NAME


FROM employees emp
LEFT JOIN departments dep ON emp.DEPARTMENT_ID = dep.DEPARTMENT_ID;
10. Modify the query in problem above to return all the department IDs even if no
employees are assigned to them.

SELECT emp.last_name, dep.department_id, dep.department_name


FROM departments dep
LEFT JOIN employees emp ON emp.department_id = dep.department_id;

Deliverables:
At the end of this session, students are expected to have written all the SQL statements in
the activity with correct output list.

You might also like