database chapter07
database chapter07
Advanced SQL
Chapter 7 1
Objectives
• Define terms
• Write single and multiple table SQL queries
• Define and use three types of joins
• Write noncorrelated and correlated subqueries
• Understand and use SQL in procedural languages
(e.g. PHP, PL/SQL)
• Understand triggers and stored procedures
2
Chapter 7
Processing Multiple Tables
• Join–a relational operation that causes two or more
tables with a common domain to be combined into a
single table or view
• Equi-join–a join in which the joining condition is
based on equality between values in the common
columns; common columns appear redundantly in the
result table
• Natural join–an equi-join in which one of the
duplicate columns is eliminated in the result table
The common columns in joined tables are usually the primary key
of the dominant table and the foreign key of the dependent table in
1:M relationships.
Chapter 7 3
Processing Multiple Tables
• Outer join–a join in which rows that do not have
matching values in common columns are
nonetheless included in the result table (as opposed
to inner join, in which rows must have matching
values in order to appear in the result table)
Chapter 7 4
Figure 7-2
Visualization of different join types with results returned
in shaded area
AND
OR
Chapter 7 5
The following slides create tables for this
enterprise data model
Chapter 7 6
Relational Database Tables
Chapter 7
For each customer who placed an order, what is
the customer’s name and order number?
Chapter 7 8
Figure 7-1 Pine Valley Furniture Company Customer_T and
Order_T tables with pointers from customers to their orders
Chapter 7 9
9
Equi-Join Example
• For each customer who placed an order, what is the
customer’s name and order number?
Customer ID
appears twice in the
result
Chapter 7 10
Equi-Join Example – alternative syntax
An INNER join will only return rows from each table that have
matching rows in the other.
ON clause performs the equality Note: From Fig. 7-1, you see that only
10 Customers have links with orders.
check for common columns of the
two tables è Only 10 rows will be returned from
this INNER join
Chapter 7 12
Remarks
• Equi-join = Inner Join = Natural Join
• Use Alias
SELECT C.CustomerID, O.CustomerID, CustomerName, OrderID
FROM CUSTOMER C; ORDER O
WHERE C.CustomerID=O.CustomerID
Chapter 7 13
OUTER JOIN EXAMPLE
• List the customer name, ID number, and order number for
all customers. Include customer information even for
customers that do have an order.
Chapter 7 14
Left Outer Join
A B
Chapter 7 15
Outer Join
Results
Unlike
INNER join,
this will
include
customer
rows with no
matching
order rows
Chapter 7 17
Multiple Table Join Example
• Assemble all information necessary to create an invoice for order
number 1006
SELECT C.CustomerID, C.Name, Address, City, State, O.OrderID,
OrderDate, Quantity, Description, Finish, Price, Price*Quantity
FROM Customer C, Order O, Order_Line OL, Product P
WHERE C.CustomerID=O.CustomerID AND O.OrderID=OL.OrderID
AND OL.ProductID=P.ProductID AND O.OrderID=1006
18
Chapter 7
Multiple Table Join Example
• Assemble all information necessary to create an invoice for order
number 1006
Four tables
involved in
this join
Employee
EID EName Addr …. SEID
Employee
Supervise Employee_A
EID EName Addr …. SEID
Employee_A
Chapter 7 22
Processing Multiple Tables
Using Subqueries
• Subquery–placing an inner query (SELECT statement)
inside an outer query
• Options:
– In a condition of the WHERE clause
– As a “table” of the FROM clause
– Within the HAVING clause
• Subqueries can be:
– Noncorrelated–executed once for the entire outer query
– Correlated–executed once for each row returned by the
outer query
Chapter 7 23
Subquery Example
• 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
Join version
Subquery version
Chapter 7 25
Figure 7-6 Graphical depiction of two ways to
answer a query with different types of joins
Chapter 7 26
Figure 7-6 Graphical depiction of two ways to
answer a query with different types of joins
Chapter 7 27
Comparison of Join and Subqueries
M N M N
items items items K
items
items
Chapter 7 28
Correlated vs. Noncorrelated
Subqueries
• Noncorrelated subqueries:
– Do not depend on data from the outer query
– Execute once for the entire 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 29
Figure 7-8a Processing a noncorrelated subquery
Chapter 7 32
Another Subquery Example
• Show all products whose standard price is higher than the
average price
One column of the subquery is an
Subquery forms the derived aggregate function that has an alias
table used in the FROM clause name. That alias can then be
of the outer query
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 33
Union Queries
• Combine the output (union of multiple queries)
together into a single result table
First query
Combine
Second query
Chapter 7 34
Figure 7-9 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 36
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 37
Query Efficiency Considerations
Chapter 7 38
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 39
Guidelines for Better Query Design (cont.)
Chapter 7 40
DBMS without Transactions
Transaction A Transaction B
T1 Balance = 1000 Balance = 1000
T2 Deposit +100
…
T3 Withdraw -200
T4 Balance = 800
…
T5 Deposit +100
T6 Balance = 1200
Chapter 7 41
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
• Marks boundaries of a transaction
– COMMIT
• Makes all updates permanent
– ROLLBACK
• Cancels updates since the last COMMIT
Chapter 7 42
Figure 7-12 An SQL Transaction sequence (in pseudocode)
Chapter 7 43
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
– sys.columns – table and column definitions
– sys.indexes – table index information
– sys.foreign_key_columns – details about columns in foreign
key constraints
Chapter 7 44
SQL:2008 Enhancements/Extensions
Chapter 7 45
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 46
Routines and Triggers
• Routines
– Program modules that execute on demand
• Functions–routines that return values and
take input parameters
• Procedures–routines that do not return values
and can take input or output parameters
• Triggers–routines that execute in response to
a database event (INSERT, UPDATE, or DELETE)
Chapter 7 47
Figure7-13 Triggers contrasted with stored procedures (based on Mullins 1995)
Chapter 7 51
Reasons to Embed SQL in 3GL
Chapter 7 52
Summary
• Subquery–placing an inner query (SELECT
statement) inside an outer query
– Noncorrelated subqueries:
• Do not depend on data from the outer query
– Correlated subqueries:
• Make use of data from the outer query
• Query optimization is important when data
volume increases
Chapter 7 53