Ch 7 - Part 2

Check
page
numbers!!
CHAPTER 7:
ADVANCED SQL
(PART 2 – SUBQUERIES)
Modern Database Management
11th Edition
Jeffrey A. Hoffer, V. Ramesh,
Heikki Topi
Copyright © 2016 Pearson Education, Inc.
1
OBJECTIVES

Define terms
multiple table SQL queries
 Note in SQL Handout 3
Define and use three types of joins – revisit OUTER JOIN
 Self-Join
 Write noncorrelated and correlated
subqueries
 Establish referential integrity in SQL

Write single and

2
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-2
JOIN WITH OTHER OPERATIONS

After the first two tables are joined, the result
set is joined to the next table, and so on
WHERE/
WHERE/
JOIN1
JOIN2
T1
R1
GROUP
HAVING
ORDER BY
BY
R2
R3
R5
R4
T2
T3
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-3
3
4
4
SELF-JOIN EXAMPLE
Note which one is which one!
The same table
is used on both
sides of the join
(remember the
ERD? – and think
about tables);
distinguished
using table
aliases
Self-joins are often used on tables with unary relationships
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-4
FIG 7-5 EXAMPLE OF A SELF-JOIN
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-5
5
SET OPERATION: MINUS
Exclude the designated records
 Example: Find instructors who do not have the
same last name as students
SELECT instructor_name Name
FROM instructor
MINUS
SELECT student_lname Name
From student

Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-6
6
OUTER JOIN REVISIT

Want to list all customers and the orders
placed, including customers who did not place
orders. Which of the following is correct?
1.
2.
3.
4.
cust LEFT JOIN [order]
cust RIGHTT JOIN [order]
[order] LEFT JOIN cust
[order] RIGHTT JOIN cust
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-7
7
OUTER JOIN REVISIT

LEFT JOIN
RIGHT JOIN
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-8
8
MULTIPLE TABLE JOIN REVISIT
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-9
9
MULTIPLE TABLE JOIN REVISIT (COMPLEX)

SELECT

FROM Product_T INNER JOIN (
NOT
recommended
 (Customer_T
INNER JOIN Order_T ON
Customer_T.CustomerID = Order_T.CustomerID)
 INNER JOIN OrderLine_T ON Order_T.OrderID =
OrderLine_T.OrderID)

ON Product_T.ProductID =
OrderLine_T.ProductID;
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-10
10
MULTIPLE TABLE JOIN REVISIT – EASIEST:
Recommended
SELECT
 FROM Customer_T, Order_T, OrderLine_T,
Product_T
 WHERE Customer_T.CustomerID =
Order_T.CustomerID
 AND Order_T.OrderID =OrderLine.OrderID
 AND Product_T.ProductID =
OrderLine_T.ProductID

Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-11
11
SUBQUERIES – 1

Subquery–placing an inner query (SELECT statement)
inside an outer query
1. As a “field” to be output, in the SELECT clause
1.
2.
As a “table” of the FROM clause

3.
In this case a view is created in the subquery and the
view is then used in the main query
In a condition of the WHERE clause
1.
4.
“Treat” the “no row value and set value can be
together” problem
When part of the condition is not a ready value (that
needs to be found from a query
3 and 4 logically
In a condition of HAVING clause
1.
Chapter 7
the same
Similar to “3” except that it’s now for a group
Copyright © 2016 Pearson Education, Inc.
7-12
SUBQUERIES - 2
 Subquery/inner
query and main/outer
query are “in two worlds”:
1.
2.
3.
Can use different tables
The same table can have different table aliases
Fields selected in subquery are never for display
in the main/outer query  makes no sense to
use alias for FIELDS inside the subquery

“What happens here stays here”

Re “2” above: what if we do need to relate A
SPECIFIC value in main query w subquery? 
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-13
SUBQUERIES - 3
 Subqueries
can be:
 Noncorrelated–executed
outer query
once for the entire
 The
inner query does not rely on the outer query – as if
they are two totally independent queries
 The outer query uses the resulted data passed from the
inner query only ONCE
 Correlated–executed
once for each row
returned by the outer query
 The
inner query needs data/parameter passed INTO it
from the outer query
 The inner query often executed multiple times, whenever
the outer query passes in a different data/parameter
Chapter 7value
Copyright © 2016 Pearson Education, Inc.
7-14
SUBQUERY EXAMPLE

What are the name and address of the
customer who placed order #1008?
SELECT CUSTOMER_NAME, CUSTOMER_ADDRESS
FROM CUSTOMER_T
WHERE CUSTOMER_T.CUSTOMER_ID =
(SELECT CUSTOMER_ID FROM ORDER_T
WHERE ORDER_ID = 1008);


Note: the value for ORDER_ID does NOT appear in the query
result; it is used as the selection criterion in the inner query
Data
from a WHERE-subquery cannot
be included in the final results
They are only used as ______
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-15
SUBQUERY EXAMPLE (CONT) – JOIN
TABLES VS SUBQUERY
16
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-16
JOIN VS. SUBQUERY

Some queries could be accomplished by either a join
or a subquery [Examine the query on last slide]
Join version
Subquery version
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-17
17
SUBQUERY EXAMPLE (CONT) – JOIN
TABLES VS SUBQUERY
18
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-18
SUBQUERY – “IN”

In this case, the subquery
returns MANY values,
not just one.
Show all customers who have placed an order
The IN operator will test to see if
the CUSTOMER_ID value of a
row is included in the list returned
from the subquery
SELECT CUSTOMER_NAME FROM CUSTOMER_T
WHERE CUSTOMER_ID IN
(SELECT DISTINCT CUSTOMER_ID FROM ORDER_T);
NOT/ANY/ALL may
be used in front of IN;
logical operators =,<, >
can be used
Chapter 7
Subquery is embedded in
parentheses. In this case it
returns a list that will be used
in the WHERE clause of the
outer query
Copyright © 2016 Pearson Education, Inc.
7-19
FIG 7-7 SUBQUERY – “NOT IN”
Chapter 7
Copyright © 2016 Pearson Education, Inc.
20
7-20
CORRELATED VS. NON-CORRELATED
SUBQUERIES
21

Noncorrelated subqueries:
 Do
not depend on data from the outer query
 Execute once for the entire outer query
 i.e. the subquery “first runs by itself”, “then
pass the result to outer query”

Correlated subqueries:
 Make
use of data from the outer query
 Execute once for each row of the outer query
 Can use the EXISTS operator
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-21
ABOUT INNER QUERY AND OUTER QUERY

In the non-correlated subqueries, the inner
query
 only
provides its output(s) as the Input(s) for the
outer query;
 The field names/alias are unrelated with those in
the outer query;
 The tables used can be (and often are) totally
different from those in the outer query;
 In short: they, are, in, two, different, worlds!  “Las
Vegas: ‘What happens here stays here’ ”
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-22
22
23
Figure 7-8a Processing a noncorrelated subquery
A Chapter
noncorrelated
subquery
processes
completely
beforeInc.
the outer query begins
7
Copyright
© 2016
Pearson Education,
7-23
24
SUBQUERY – “EXISTS”

EXISTS
 take

a value of true if the subquery returns an
intermediate results table that contains one or
more rows (a nonempty set),
 false if no rows are returned (empty set)
Query: What are the order IDs for all orders that have
included furniture finished in natural ash?
SELECT DISTINCT ORDER_ID FROM ORDER_LINE_T
WHERE EXISTS
(SELECT * FROM PRODUCT_T
WHERE PRODUCT_ID = ORDER_LINE_T.PRODUCT_ID
AND PRODUCT_FINISH = ‘Natural Ash’);
Note “select *”…
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-24
25
CORRELATED SUBQUERY EXAMPLE

Show all orders that include furniture finished in natural
ash
The EXISTS operator will return a
TRUE value if the subquery resulted in
a non-empty set, otherwise it returns a
FALSE
SELECT DISTINCT OrderID FROM OrderLine_T
WHERE EXISTS
(SELECT * FROM Product_T
WHERE ProductID = OrderLine_T.ProductID
AND Productfinish = ‘Natural ash’);
The subquery is testing for a value
that comes from the outer query
 A correlated subquery always refers to an attribute from a table
referenced
query 
passing
Chapter 7 in the outerCopyright
© 2016
Pearsonarguments
Education, Inc.from outter query7-25
Figure 7-8b
Processing a
correlated
subquery
Subquery refers to outerquery data, so executes once
for each row of outer query
Note: Only the
orders that
involve products
with Natural
Ash will be
included in the
final results.
Chapter
Chapter 77
© 2013 Pearson
Education,
Inc. Publishing
as Prentice Hall
Copyright
© 2016 Pearson
Education, Inc.
7-26
26
26
(SUMMARY) PLACES FOR A SUBQUERY
Clause
Use
subQ
Remark
SELECT
Yes SubQ generate column
FROM
Yes SubQ generate a “dynaset”
WHERE
Yes SubQ participate in condition
GROUP BY
No
HAVING
Yes Same/similar with in WHERE
ORDER
Chapter 7 BY
GROUP BY works w field only
ORDER BY works with field
No?
Copyright © 2016 Pearson Education, Inc.
Subquery produces
value(s); they are
7-27
NOT fields
27
(SUMMARY) SUBQ IN …
1.
2.
3.
4.
SELECT: Break the “ban” of “no row values with set
values”
 You want to list the individual restaurants’ sales as well
as the average sales, for a comparison
FROM: Provide a “temp table”
 Restaurants whose cities are not the same as the
cities of their franchisees
WHERE: Provide conditions that involve parts that are too
complex for one single query
 Restaurants whose sales greater than AVG
Accommodate the passing of arguments into the
subquery >>> More complex; to demo this case
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-28
28
SUBQUERY SUMMARY – 1: SIMPLE SUBQ
Evaluate once and result is compared w EACH row of the
parent query.
SELECT field_list
FROM table_list (w possible joins)
Will the
WHERE field {=,<,>,IN} (Subquery)
subquery
With GROUP BY:
SELECT field_list
FROM table_list (w possible joins)
GROUP BY field_list
HAVING field {=,<,>,IN} (Subquery)

Chapter 7
Copyright © 2016 Pearson Education, Inc.
results be
displayed?
7-29
29
SUBQUERY SUMMARY – 1: SIMPLE SUBQ
Typical scenarios:
1. Rows/Groups with a field value > average of {whole
table; a specific group}
2. Groups having a field value >= AVG/COUNT…
of{whole table; a specific group}
3. Rows/groups whose certain field value is among a
list of valid values (use IN)
 Note: in most cases (especially bullet #3), the values
from the right-hand-side of the Boolean operators are
NOT from the same table of the parent/main query –
“reach different table thru SubQ”
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-30
30
SUBQ SUMMARY – 2: CREATE SUBSET FOR FROM
SELECT field_list
FROM (Subquery) WHERE …
Will the subquery
results be
displayed?
Example: display the names and home city of
franchisees who currently owns restaurants in
California
 Example: display the names and home city of
franchisees who currently owns restaurants in
California, whose credit rating is A or AA

Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-31
31
ANOTHER SUBQUERY EXAMPLE (DERIVED
32

TABLE)
Show all products whose standard price is higher than
the average price
Subquery forms the derived
table [view] used in the FROM
clause of the outer query
One column of the subquery is an
aggregate function that has an alias
name. That alias can then be
referred to in the outer query
The WHERE clause normally cannot include aggregate functions, but because
the aggregate is performed in the subquery its result can be used in the outer
query’s WHERE clause
Chapter 7
Copyright
© 2016name
Pearson Education,
Inc.
7-32
Differentiate:
column
(header)
vs variable
(EXAMPLE) SUBQ IN FROM - DYNASET
If I want to see the average sales of the top-sale
restaurants from each city, the “top-sale
restaurants from each city” must be obtained
in a subquery:
SELECT AVG(AnnualSales) FROM
(SELECT MAX(AnnualSales)
FROM Restaurant GROUP BY City);

Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-33
33
SUBQ SUMMARY – 3: CREATE SUBSET FOR SELECT
SELECT field_list, (Subquery)
FROM table_list WHERE …

Example:
Chapter 7
Copyright © 2016 Pearson Education, Inc.
Will the
subquery
results be
displayed?
7-34
34
SUBQ SUMMARY – 4: CORRELATED SUBQUERY
Pass argument from the main Q INTO subQ
Will the
Special case: WHERE EXIST…
subquery
i.e.: “*if* there’s a corresponding results be
displayed
row”
In addition to the book’s example,

?

Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-35
35
SUBQ IN WHERE – PASSING ARGUMENTS INTO
SUBQUERY
If I want to see the restaurants whose sales are
above average in its own city Passing argument in
 SELECT RestaurantID, AnnualSales, City
 FROM Restaurants R
 WHERE AnnualSales >
 (SELECT AVG(AnnualSales) FROM Restaurants
WHERE City = R.City
GROUP BY City);

Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-36
36
UNION QUERIES

37
Combine the output (union of multiple queries)
together into a single result table
First query
Combine
Second query
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-37
STRATEGY FOR WRITING SUBQ
1. Lay out the “big-picture” logic;
2. Then figure out the “complex” part of logic
that may need a subQ
3. Write the main query
4. Write the subquery
5. Assemble the two
6. Watch out: “border penetration” of



Arguments
Tables
Query results
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-38
38
39
Figure 7-8 Combining queries using UNION
Note: with
UNION queries,
the quantity and
data types of the
attributes in the
SELECT clauses
of both queries
must be identical
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-39
CONDITIONAL EXPRESSIONS USING CASE
SYNTAX
This is available with
newer versions of SQL,
previously not part of
the standard
Figure 7-9
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-40
40
41
TIPS FOR DEVELOPING QUERIES









Be familiar with the data model (entities and
relationships)
Understand the desired results
Know the attributes desired in result
Identify the entities that contain desired
attributes
Review ERD
Construct a WHERE equality for each link
Fine tune with GROUP BY and HAVING clauses if
needed
Consider the effect on unusual data
“Integrity” of logic – do NOT “translate”
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-41
EXAMPLE OF QUERY USING A VIEW
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-42
TIPS FOR DEVELOPING QUERIES








Be familiar with the data model (entities and
relationships)
Understand the desired results
Know the attributes desired in results
Identify the entities that contain desired
attributes
Review ERD
Construct a WHERE equality for each link
Fine tune with GROUP BY and HAVING clauses
if needed
Consider the effect on unusual data
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-43
44
QUERY EFFICIENCY CONSIDERATIONS
Instead of SELECT *, identify the specific
attributes in the SELECT clause; this helps
reduce network traffic of result set
 Limit the number of subqueries; try to make
everything done in a single query if possible
 If data is to be used many times, make a
separate query and store its results rather
than performing the query repeatedly

Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-44
GUIDELINES FOR BETTER QUERY
DESIGN







Understand how indexes are used in query
processing
Keep optimizer statistics up-to-date
Use compatible data types for fields and literals
Write simple queries
Break complex queries into multiple simple parts
Don’t nest one query inside another query
Don’t combine a query with itself (if possible avoid
self-joins)
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-45
46
GUIDELINES FOR BETTER QUERY DESIGN
(CONT.)






Create temporary tables for groups of queries
Combine update operations
Retrieve only the data you need
Don’t have the DBMS sort without an index
Learn!
Consider the total query processing time for ad hoc
queries
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-46
47
ENSURING TRANSACTION INTEGRITY

Transaction = A discrete unit of work that must
be completely processed or not processed at all



May involve multiple updates
If any update fails, then all other updates must be
cancelled
SQL commands for transactions

BEGIN TRANSACTION/END TRANSACTION


COMMIT


Makes all updates permanent
ROLLBACK

Chapter 7
Marks boundaries of a transaction
Cancels updates since the last COMMIT
Copyright © 2016 Pearson Education, Inc.
7-47
48
Figure 7-12 An SQL Transaction sequence (in pseudocode)
Chapter 7
Copyright
© 2016
Pearson Education,
Inc.
Our
lecture
may end
7-48
with this slide
49
DATA DICTIONARY FACILITIES




System tables that store metadata
Users usually can view some of these tables
Users are restricted from updating them
Some examples in Oracle 11g




DBA_TABLES – descriptions of tables
DBA_CONSTRAINTS – description of constraints
DBA_USERS – information about the users of the system
Examples in Microsoft SQL Server 2008



Chapter 7
sys.columns – table and column definitions
sys.indexes – table index information
sys.foreign_key_columns – details about columns in foreign
key constraints
Copyright © 2016 Pearson Education, Inc.
7-49
SQL:2008
ENHANCEMENTS/EXTENSIONS

User-defined data types (UDT)


Analytical functions (for OLAP)




CEILING, FLOOR, SQRT, RANK, DENSE_RANK, ROLLUP, CUBE,
SAMPLE,
WINDOW–improved numerical analysis capabilities
New Data Types


Subclasses of standard types or an object type
BIGINT, MULTISET (collection), XML
CREATE TABLE LIKE–create a new table similar to an
existing one
MERGE
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-50
50
SQL:2008 ENHANCEMENTS
(CONT)
Programming extensions
 Persistent Stored Modules (SQL/PSM)

 Capability
to create and drop code modules
 New statements:
 CASE,
IF, LOOP, FOR, WHILE, etc.
 Makes SQL into a procedural language

Oracle has propriety version called
PL/SQL, and Microsoft SQL Server has
Transact/SQL
Chapter 7
Copyright © 2016 Pearson Education, Inc.
7-51
51