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

Chapter4 Session3

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

Chapter4 Session3

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

Database Systems

Chapter 4: Structured Query Language


(SQL)
session 3
SubQuery and Multiple Table joins
Outline

1 SubQuery

2 Multiple Table joins

2
SubQuery
qSubquery is a query inside another query
§A subquery can be nested inside a SELECT, INSERT,
UPDATE or DELETE statement or inside another
subquery.
§A subquery is usually added within the WHERE clause
of another SQL SELECT statement.
qIn a subquery SELECT statement, can not
include:
§the keyword DISTINCT in the SELECT phrase,
§an ORDER BY phrase.

3
Subquery
qSubqueries can be:
§ Noncorrelated subqueries (Self-contained subqueries)
• have no dependency on outer query
• execute once for the entire outer query
§ Correlated subqueries
• depend on values from outer query
• execute once for each row returned by the outer query
• Can use the EXISTS operator

4
Subquery
qA subquery is must be enclosed within parentheses
qSubquery can return:
§ One single value (Scalar Subquery) - One column and one
row
§ A list of values (Multi-Valued Subquery) - One column and
multiple rows
§ A virtual table - Multicolumn, multirow set of values
§ No value - Output of the outer query might result in an
error or a null empty set

5
Subquery
qThe most common type of subquery uses an inner
SELECT subquery on the right side of a WHERE
comparison expression (WHERE subqueries)
qA subquery can be used within a SQL data
manipulation language (DML) statement such
as INSERT, UPDATE, or DELETE

6
WHERE Subqueries
qSyntax
SELECT column_list
FROM table
WHERE expression OPERATOR
(SELECT column_list
FROM table)

qThe subquery (inner query) executes once


before the main query.
qThe result of the subquery is used by the main
query (outer query).

7
The contents of Employees
table

8
The contents of Departments
table

9
Scalar Subquery
qThe Scalar sub query returns one single value to
outer query
§ Uses operators: can be >, <, =, >=, or <=, <>
§ Value generated by the subquery must be of a comparable
data type
qIf the query returns multiple values, the DBMS will
generate an error.
qIf inner query returns an empty set, result is
converted to NULL

10
Scalar Subquery
qSyntax
SELECT ...... θ
FROM ...... can be
=
WHERE ...... θ <>
( SELECT ...... >
FROM ...... >=
WHERE ...... ) <
<=

Must ensure that the subquery returns a SINGLE VALUE,


i.e. a table of one row and one column, or an ERROR results.

11
Scalar Subquery
qExample
SELECT employee_id, first_name, last_name, salary
FROM Employees
WHERE salary >(SELECT AVG(salary) FROM employees)
ORDER BY salary
Inner query
results

12
Multi-Valued Subquery
qMulti-valued subquery returns multiple values to
the outer query
qQuery uses the set comparion operators (IN, ALL,
ANY).
SYMBOL MEANING

IN Equal to any member in a list

ANY Return rows that match any


value on a list
ALL Return rows that match all
values in a list
13
Multi-Valued Subquery
qSyntax:
SELECT ...... θθ
FROM ...... can be
IN
WHERE ...... θθ NOT IN
( SELECT ...... θ ANY
FROM ...... θ ALL
WHERE ...... ) EXISTS
NOT EXISTS

θ is any of =, <>, >, >=, <, <=


The subquery can return MULTIPLE VALUES,
i.e. one column of many rows.
However there is no problem if only one row is returned.
14
Multi-Valued Subquery with IN
qExample
SELECT employee_id, first_name, last_name,
department_id
FROM Employees
WHERE department_id IN (SELECT department_id
FROM departments
Can’t use ‘=’ comparison. WHERE location_id = 1700)
Subquery can return many Inner query
department_id results

15
Multi-Valued Subquery with
ALL
qExample
SELECT employee_id, first_name, last_name, salary, department_id
FROM Employees
WHERE salary > ALL (SELECT salary
FROM employees
WHERE department_id = 10)
AND department_id<>10
If ‘>’ is true for
every value,
ALL returns true,
else false.

16
Multi-Valued Subquery with
ANY
qExample
SELECT employee_id, first_name, last_name, salary, department_id
FROM Employees
WHERE salary > ANY (SELECT salary
FROM employees
WHERE department_id = 10) If ‘>’ is true for
AND department_id<>10 at least one value,
ANY returns true,
else false.

17
EXISTS/NOT EXISTS
qWhen a subquery is used with the keyword EXISTS, it
functions as an existence test
§ True or false only – no rows passed back to outer query
qEXISTS evaluates to TRUE or FALSE
§ If any rows are returned by the subquery, EXISTS returns
TRUE
§ If no rows are returned, EXISTS returns FALSE
qSyntax:
WHERE [NOT] EXISTS (subquery)

18
EXISTS/NOT EXISTS
qThe keyword EXISTS does not follow a column name
or other expression
qThe SELECT list of a subquery introduced by EXISTS
typically only uses an asterisk (*)

19
EXISTS/NOT EXISTS
qExample: Show all the employees information if
there is at least one employee with a salary in excess
of 200,000
SELECT employee_id, first_name, last_name, salary, department_id
FROM Employees
WHERE EXISTS (SELECT * FROM employees WHERE salary > 200000)

The SELECT list typically only


uses an asterisk because no data
will be returned

20
Correlated subqueries
qExample 1: Finds all employees whose salary is
higher than the average salary of the employees in
their departments:
SELECT employee_id, first_name, last_name, salary, department_id
FROM employees e
WHERE salary > (SELECT AVG(salary) FROM employees
WHERE department_id = e.department_id)

21
Correlated subqueries
qExample 2: returns all departments which have
no employees:
SELECT
department_id, department_name
FROM
departments d
WHERE NOT EXISTS( SELECT * FROM employees e
WHERE e.department_id = d.department_id)

22
Correlated subqueries
qExample 3: Which departments have exactly 2
employees working on them ?
SELECT * FROM Departments d
WHERE 2 = (SELECT count(*) FROM employees e
WHERE e.department_id = d.department_id)

23
Subqueries in FROM clause
qExample: Get the maximum of the average
departmental salaries.
SELECT FORMAT(MAX( AvSal ),'C2') AS MaxAvSal
FROM ( SELECT department_id, ROUND(AVG( Salary),2) AS AvSal
FROM employees
GROUP BY department_id ) AS Emp_Averages

This is a useful way of applying


an aggregate function to the result
of an aggregate function.

24
Subqueries in SELECT clause
qExample: Get the additional amount of salary that
each employee receives over and above the
minimum company salary.
SELECT employee_id, first_name, last_name,
( Salary - ( SELECT Min(Salary)
FROM employees ) ) AS Additional
FROM employees

This is a useful way of doing a scalar calculation in each row


that requires the resulting value of an aggregation.

25
Multiple Table joins

26
Multiple Tables Joins
qAbility to combine (join) tables on common
attributes is most important distinction between a
relational database and other databases
qJoin clause is used to combine rows from two or
more tables, based on a related column between
them.
qJoin is generally composed of an equality
comparison between the foreign key and the
primary key of related tables

27
Multiple Tables Joins
qType of joins
§Equijoin or Inner Join
§Self join
§Outer join
§Cross Join

28
The contents of Product table

29
The contents of Vendor table

30
Inner Join
qAlso called as Equijoin
§ This join combines the rows retrieved from two or more
tables, based on a common field between them.
§ This join creates a new result table by combining columns
values of the tables based upon the join condition.
§ To join n tables together, you need a minimum of n-1 join
conditions
qUses an equality operator (=) to join tables.
qINNER JOIN or simply JOIN is used in the query

31
Inner join
qThe INNER JOIN keyword selects all rows from tables
as long as there is a match between the columns
qANSI syntax
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name

qYou can join more than two tables based upon the
join conditions.

32
Inner join
qExample
SELECT Product.P_Descript, Product.P_Price,
Vendor.V_Name, Vendor.V_Contact,Vendor.V_AreaCode,
Vendor.V_Phone
FROM Product INNER JOIN Vendor
ON Product.V_Code = Vendor.V_Code

qOr use EquiJoin based on equality V_Code (old-style


join)
SELECT Product.P_Descript,Product.P_Price,Vendor.V_Name,
Vendor.V_Contact,Vendor.V_AreaCode, Vendor.V_Phone
FROM Product, Vendor
WHERE Product.V_Code = Vendor.V_Code
33
Inner join
qResult

34
Inner join
qJoining Tables With a Alias
§ An alias may be used to identify the source table from
which the data is taken
SELECT P.P_Descript,P.P_Price,V.V_Name,
V.V_Contact,V.V_AreaCode, V.V_Phone
FROM Product P INNER JOIN Vendor V
ON P.V_Code = V.V_Code

35
Self Join
qA Self join or Recursive Join is a type of SQL join
which is used to join a table to itself.
qThe table has a Foreign key that references its
own Primary key.
qAn alias is especially useful when a table must be
joined to itself in a recursive query to avoid column
ambiguity.

36
Self Join
qExample: list of all employees with their managers
names by joining the EMP table to itself.
SELECT E.EMP_Num, E.EMP_LName, E.EMP_MGR, M.EMP_LName
FROM EMP E
INNER JOIN EMP M
ON E.EMP_MGR = M.EMP_Num
ORDER BY E.EMP_MGR

37
The content of Emp table

38
Self Join
qResult

39
The content of Product table

40
The content of Vendor table

41
Outer join
qOuter join is a join in which rows that do not have
matching values in common columns are also included
in the result table .
qNull values appear in columns where there is not a
match between tables
qOuter join
§ Left outer join
§ Right outer join
§ Full outer join

42
Left Outer Join
qIn Left outer join (or Left Join)
§ Returns all rows from the left table (table1) and the
matching rows from the right table (table2)
§ If no records match from the left table, it shows those
records with NULL values
qSyntax:
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name

43
Left Outer Join
qExample: Show V_Code, V_Name for all vendors listed
in the Vendor table. Include P_Code, P_Descript even if
there is no product for that vendor.

SELECT V.V_Code, V_Name, P.P_Code, P.P_Descript


FROM VENDOR V LEFT JOIN PRODUCT P
ON V.V_Code = P.V_Code

44
Left Outer Join
qResult

45
Right Outer Join
qIn Right outer join (or Right Join)
§ Returns all rows from the right table (table2) and the
matching rows from the left table (table1)
§ If no records match from the right table, it shows those
records with NULL values
qSyntax
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name

46
Right Outer Join
qExample: Show P_Code, P_Descript for all products
listed in the Product table. Include V_Code, V_Name
even if there is no Vendor for that product.
SELECT P.P_Code, P.P_Descript, P.V_Code, V_Name
FROM VENDOR V RIGHTJOIN PRODUCT P
ON V.V_Code = P.V_Code

47
Right Outer Join
qResult

48
Full Outer Join
qFull Outer Join or Full Join
§ returns all records when there is a match in left (table1)
or right (table2) table records.
qSyntax

SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition

49
Full Outer Join
qExample: List P_Code, P_Descript, V_Code and
V_Name of all products and vendors, regardless of
whether or not the products have vendor or the
vendors supply the products.
SELECT P.P_Code, P.P_Descript, V.V_Code, V_Name
FROM VENDOR V FULL JOIN PRODUCT P
ON V.V_Code = P.V_Code

50
Full Outer Join
qResult

51
Cross Join
qA cross join performs a relational product (also
known as the Cartesian product) of two
tables
SELECT column_name(s)
FROM table1
CROSS JOIN table2

52
Cross Join
q Example
SELECT P.P_Code, P.P_Descript, V.V_Code, V_Name
FROM VENDOR V CROSSJOIN PRODUCT P

qOr using other syntax (all DBMSs use this style)


SELECT P.P_Code, P.P_Descript, V.V_Code, V_Name
FROM VENDOR V, PRODUCT P

53
Cross Join
qThe command performs a cross join of the VENDOR
and PRODUCT tables that generates 176 rows. (There
are 11 vendor rows and 16 product rows, yielding 11 ×
16 = 176 rows.)
qSome rows of the
result

54

You might also like