Sie sind auf Seite 1von 37

Chapter 8:

Advanced SQL
Modern Database
Management
8th Edition
Jeffrey A. Hoffer, Mary B. Prescott,
Fred R. McFadden
2007 by Prentice Hall

Objectives

Definition of terms
Write multiple table SQL queries
Define and use three types of joins
Write correlated and noncorrelated
subqueries
Establish referential integrity in SQL
Understand triggers and stored procedures
Discuss SQL:1999 standard and its
extension of SQL-92

Chapter 8

2007 by Prentice Hall

Processing Multiple Tables


Joins

Joina relational operation that causes two or more tables


with a common domain to be combined into a single table
or view

Equi-joina 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 joinan equi-join in which one of the duplicate
columns is eliminated in the result table
Outer joina 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)
Union joinincludes all columns from each table in the
join, and an instance for each row of each 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 8
2007 by Prentice Hall
3

The following slides create tables


for this enterprise data model

Chapter 8

2007 by Prentice Hall

Figure 8-1 Pine Valley Furniture Company Customer and Order


tables with pointers from customers to their orders

These tables are used in queries that follow


Chapter 8

2007 by Prentice Hall

Natural Join Example

For each customer who placed an order, what is


the customers name and order number?
Join involves multiple tables in FROM clause
SELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, ORDER_ID
FROM CUSTOMER_T JOIN ORDER_T ON
CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID;

ON clause performs the equality


check for common columns of the
two tables
Chapter 8

2007 by Prentice Hall

Note: from Fig. 1, you


see that only 10
Customers have links
with orders.
Only 10 rows will be
returned from this
INNER join.
6

Outer Join Example


(Microsoft Syntax)

List the customer name, ID number, and order


number for all customers. Include customer
information even for customers that do have an order

SELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, ORDER_ID


FROM CUSTOMER_T LEFT OUTER JOIN ORDER_T
ON CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID;

LEFT OUTER JOIN syntax


with ON causes customer
data to appear even if
there is no corresponding
order data
Chapter 8

2007 by Prentice Hall

Unlike INNER join, this


will include customer
rows with no matching
order rows
7

Results
Unlike
INNER
join, this
will
include
customer
rows with
no
matching
order
rows

Chapter 8

2007 by Prentice Hall

Multiple Table Join


Example
Assemble all information necessary to create an invoice for order
number 1006

Four tables involved


in STATE,
this join
SELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, CUSTOMER_ADDRESS,
CITY,
POSTAL_CODE, ORDER_T.ORDER_ID, ORDER_DATE, QUANTITY, PRODUCT_DESCRIPTION,
STANDARD_PRICE, (QUANTITY * STANDARD_PRICE)
FROM CUSTOMER_T, ORDER_T, ORDER_LINE_T, PRODUCT_T
WHERE CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID AND
ORDER_LINE_T.ORDER_ID
AND ORDER_LINE_T.PRODUCT_ID = PRODUCT_PRODUCT_ID
AND ORDER_T.ORDER_ID = 1006;

Chapter 8

ORDER_T.ORDER_ID =

Each pair of tables requires an equality-check condition in the WHERE clause,


matching primary keys against foreign keys
2007 by Prentice Hall

Figure 8-2 Results from a four-table join

From CUSTOMER_T table

From ORDER_T table


Chapter 8

From PRODUCT_T table

2007 by Prentice Hall

10

Multiple Table Join Example (cont.)


The same multiple join example: assemble all information necessary
to create an invoice for order number 1006. Use MS Access SQL
syntax.
SELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME,
CUSTOMER_ADDRESS, CITY, SATE, POSTAL_CODE, ORDER_T.ORDER_ID,
ORDER_DATE, QUANTITY, PRODUCT_NAME, UNIT_PRICE, (QUANTITY *
UNIT_PRICE)
FROM ((CUSTOMER_T inner join ORDER_T on CUSTOMER_T.CUSTOMER_ID =
ORDER_T.CUSTOMER_ID) inner join ORDER_LINE_T on
ORDER_T.ORDER_ID = ORDER_LINE_T.ORDER_ID) inner join PRODUCT_T
on ORDER_LINE_T.PRODUCT_ID = PRODUCT_T.PRODUCT_ID
WHERE ORDER_T.ORDER_ID = 1006;

Chapter 8

2007 by Prentice Hall

11

Processing Multiple Tables


Using Subqueries

Subqueryplacing 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:

Noncorrelatedexecuted once for the entire outer


query
Correlatedexecuted once for each row returned
by the outer query

Chapter 8

2007 by Prentice Hall

12

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
FROM CUSTOMER_T

SELECT CUSTOMER_NAME
WHERE CUSTOMER_ID IN
(SELECT DISTINCT CUSTOMER_ID FROM ORDER_T);

Subquery is embedded in
parentheses. In this case it
returns a list that will be used
in the WHERE clause of the
outer query
Chapter 8

2007 by Prentice Hall

13

Subquery Example (cont.)


Using join to accomplish the same result:

SELECT CUSTOMER_NAME
FROM CUSTOMER_T, ORDER_T
WHERE CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID;

Chapter 8

2007 by Prentice Hall

14

Subquery Example (cont.)


Query: Which customers have not placed any orders?
SELECT CUSTOMER_NAME
FROM CUSTOMER_T
WHERE CUSTOMER_ID NOT IN
( SELECT DISTINCT CUSTOMER_ID
FROM ORDER_T);

Chapter 8

2007 by Prentice Hall

15

Subquery Example (cont.)


Query: Which customers have not placed any orders for computer desks?
SELECT CUSTOMER_NAME
FROM CUSTOMER_T
WHERE CUSTOMER_ID NOT IN
( SELECT CUSTOMER_ID
FROM ORDER_T, ORDER_LINE_T, PRODUCT_T
WHERE ORDER_T.ORDER_ID = ORDER_LINE_T.ORDER_ID AND
ORDER_LINE_T.PRODUCT_ID = PRODUCT_T.PRODUCT_ID AND
PRODUCT_NAME = Computer Desk );

Chapter 8

2007 by Prentice Hall

16

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 8

2007 by Prentice Hall

17

Figure 8-3a
Processing a
noncorrelated
subquery

1.

The subquery
executes and
returns the
customer IDs
from the
ORDER_T table

2.

The outer query


on the results of
the subquery

Chapter 8

No reference to data
in outer query, so
subquery executes
once only

These are the only


customers that
have IDs in the
ORDER_T table
2007 by Prentice Hall

18

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
SELECT DISTINCT ORDER_ID FROMinORDER_LINE_T
a non-empty set, otherwise it
WHERE EXISTS
returns a FALSE
(SELECT * FROM PRODUCT_T
WHERE PRODUCT_ID = ORDER_LINE_T.PRODUCT_ID
AND PRODUCT_FINISH = Natural ash);

The subquery is testing for a value


that comes from the outer query
Chapter 8

2007 by Prentice Hall

19

Figure 8-3b Processing a correlated subquery

Subquery refers to outerquery data, so executes once


for each row of outer query

Chapter 8

2007 by Prentice Hall

20

Correlated sub queries (cont.)


Query: List the details about the product with the highest unit price.
SELECT PRODUCT_NAME, PRODUCT_FINISH, UNIT_PRICE
FROM PRODUCT_T PA
WHERE UNIT_PRICE > ALL
( SELECT UNIT_PRICE FROM PRODUCT_T PB
WHERE PB.PRODUCT_ID != PA.PRODUCT_ID);
Alternatively, we can use a non-correlated sub query to get the same result:
SELECT PRODUCT_NAME, PRODUCT_FINISH, UNIT_PRICE
FROM PRODUCT_T
WHERE UNIT_PRICE = (SELECT MAX (UNIT_PRICE) FROM
PRODUCT_T);
PRODUCT_NAME

PRODUCT_FINISH

UNIT_PRICE

Dining Table

Natural Ash

800

Chapter 8

2007 by Prentice Hall

21

Using Derived Tables


Subqueries are not limited to inclusion in the WHERE clause. They may also be
used in the FROM clause, creating a temporary derived table that is used in the
querry.
Query: Which products have a unit price that is higher than the average unit
price?
SELECT Product_Name, Unit_Price, AvgPrice
FROM (SELECT AVG (Unit_Price) AvgPrice FROM Product_T), Product_T
WHERE Unit_Price > AvgPrice;
Result:
Product_Name

Unit_Price

AvgPrice

Entertainment Center

650

440.625

8-Drawer Dresser

750

440.625

Dining Table

800

440.625

Chapter 8

2007 by Prentice Hall

22

UNION Queries
The UNION clause is used to combine the output from multiple
queries together into a single result table.
To use the UNION clause, each query involved must output the
same number of columns, and they must be UNIONcompatible. This means that the output from each query for
each column should be of compatible data types.
The example in the next slide determines the customer(s) who
has purchased the largest quantity of any Pine Valley
product, and the customer(s) who has purchased the smallest
quantity, and returns the results in one table.

Chapter 8

2007 by Prentice Hall

23

Union Queries

Combine the output (union of multiple


queries) together into a single result table

First query
Combine

Second query

Chapter 8

2007 by Prentice Hall

24

An example of combining queries using UNION clause - result:


Customer_ID Customer_Name

Ordered_Quantity Quantity

Contemporary Casuals

Smallest Quantity

Value Furniture

Smallest Quantity

Contemporary Casuals

10

Largest Quantity

Chapter 8

2007 by Prentice Hall

25

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

Marks boundaries of a transaction


Makes all updates permanent

ROLLBACK

Chapter 8

Cancels updates since the last COMMIT


2007 by Prentice Hall

26

Figure 8-5 An SQL Transaction sequence (in pseudocode)

Chapter 8

2007 by Prentice Hall

27

Triggers and Routines

Triggers

Routines that execute in response to a


database event (INSERT, UPDATE, or DELETE)

Routines

Program modules that execute on demand


Functionsroutines that return values and
take input parameters
Proceduresroutines that do not return
values and can take input or output
parameters

Chapter 8

2007 by Prentice Hall

28

Triggers and Routines (cont.)


Trigger a named set of SQL statements that are considered
(triggered) when a data modification (INSERT, UPDATE,
DELETE) occurs. If a condition stated within the trigger is met,
then a prescribed action is taken.
Since triggers are stored and executed in the database, they
execute against all applications that access the database.
Trigger can also cascade, causing other triggers to fire. Thus, a
single request from a client can result in a series of integrity or
logic checks being performed on the server without causing
extensive network traffic between client and server.
Triggers can be used to ensure referential integrity, enforce
business rules, create audit trails, or activate a procedure.
Chapter 8

2007 by Prentice Hall

29

Figure 8-7 Simplified trigger syntax, SQL:2003

Figure 8-8 Create routine syntax, SQL:2003

Chapter 8

2007 by Prentice Hall

30

Triggers and Routines (cont.)


Triggers have three parts, the event, the condition, and the action.

Simplified Oracle PL/SQL trigger syntax:


CREATE [OR REPLACE] TRIGGER trigger_name
{BEFORE|AFTER}{INSERT|DELETE|UPDATE} ON
table_name
[FOR EACH ROW [WHEN (trigger_condition)]]
Trigger_body_here;

Chapter 8

2007 by Prentice Hall

31

Triggers and Routines (cont.)


A simple example of a trigger written in PL/SQL:
CREATE OR REPLACE TRIGGER Order_ID_BIR
BEFORE INSERT ON Order_t
FOR EACH ROW
BEGIN
SELECT ID_Sequence.NextVal
INTO :New.Order_ID
FROM DUAL;
END Order_ID_BIR;
Chapter 8

2007 by Prentice Hall

32

Triggers and Routines (cont.)


Routine is a stored block of code that have to be called in order
to operate. It is like a trigger, except that it does not run
automatically. SQL-invoked routines can be procedures or
functions. A function returns one value and has only input
parameters. A procedure may have input parameters, output
parameters, and parameters that are both input and output
parameters.
Triggers and routines are very useful database objects because
they are stored in the database and controlled by the DBMS.
Thus, the code required to create them is stored in only one
location and is administered centrally. This promotes stronger
data integrity and consistency of use within the database.
Chapter 8

2007 by Prentice Hall

33

Triggers and Routines (cont.)


In order to build a simple procedure that will set a sale price, the
existing PRODUCT_T table is altered by adding a new column,
Sale_Price, that will hold the sale price for the product:
ALTER TABLE PRODUCT_T
ADD (SALE_PRICE DECIMAL (6, 2));
The following simple procedure will execute two SQL statements.
Products with a Unit_Price of $400 or higher are discounted 10
percent, and products with a Unit_Price of less than $400 are
discounted 15 percent. The Oracle code module that will create
and store the procedure named PRODUCT_LINE_SALE is as
follows (see next slide):
Chapter 8

2007 by Prentice Hall

34

Triggers and Routines (cont.)


CREATE OR REPLACE PROCEDURE Product_Line_Sale
AS BEGIN
UPDATE PRODUCT_T
SET Sale_Price = 0.90 * Unit_Price
WHERE Unit_Price >= 400;
UPDATE PRODUCT_T
SET Sale_Price = 0.85 * Unit_Price
WHERE Unit_Price < 400;
END;
To run the procedure in Oracle, use this command:
SQL> EXEC Product_Line_Sale
Chapter 8

2007 by Prentice Hall

35

Figure 8-6 Triggers contrasted with stored procedures


Procedures are called explicitly

Triggers are event-driven


Source: adapted from Mullins, 1995.

Chapter 8

2007 by Prentice Hall

36

Embedded and Dynamic


SQL

Embedded SQL

Including hard-coded SQL statements in


a program written in another language
such as C or Java

Dynamic SQL

Ability for an application program to


generate SQL code on the fly, as the
application is running

Chapter 8

2007 by Prentice Hall

37

Das könnte Ihnen auch gefallen