Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced...

33
Chapter Chapter 8: Chapter Chapter 8: Advanced SQL Advanced SQL Modern Database Management Modern Database Management 9 th th Edition Edition 9 Edition Edition Jeffrey A. Jeffrey A. Hoffer Hoffer, Mary B. Prescott, , Mary B. Prescott, Heikki Heikki Topi Topi © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice Hall Publishing as Prentice Hall 1

Transcript of Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced...

Page 1: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

ChapterChapter 88::Chapter Chapter 88::Advanced SQLAdvanced SQLQQ

Modern Database ManagementModern Database Management99thth EditionEdition99 EditionEdition

Jeffrey A. Jeffrey A. HofferHoffer, Mary B. Prescott, , Mary B. Prescott, HeikkiHeikki TopiTopi

© © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 11

Page 2: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

ObjectivesObjectivesObjectivesObjectivesDefinition of termsDefinition of termsWrite single and multiple table SQL queriesWrite single and multiple table SQL queriesg p Q qg p Q qDefine and use three types of joinsDefine and use three types of joinsWrite noncorrelated and correlated subqueriesWrite noncorrelated and correlated subqueriesWrite noncorrelated and correlated subqueriesWrite noncorrelated and correlated subqueriesEstablish referential integrity in SQLEstablish referential integrity in SQLUnderstand triggers and stored proceduresUnderstand triggers and stored proceduresDiscuss SQL:Discuss SQL:200200n standard and its extension of n standard and its extension of SQLSQL--9292Understand SQL use for OLTP and OLAPUnderstand SQL use for OLTP and OLAP

Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 22

Understand SQL use for OLTP and OLAP Understand SQL use for OLTP and OLAP

Page 3: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

Processing Multiple TablesProcessing Multiple Tables––JoinsJoinsg pg pJoinJoin––a relational operation that causes two or more tables with a a relational operation that causes two or more tables with a common domain to be combined into a single table or viewcommon domain to be combined into a single table or viewcommon domain to be combined into a single table or viewcommon domain to be combined into a single table or view

EquiEqui--joinjoin––a join in which the joining condition is based on a join in which the joining condition is based on equality between values in the common columns; common columns equality between values in the common columns; common columns

d d tl i th lt t bld d tl i th lt t blappear redundantly in the result tableappear redundantly in the result table

Natural joinNatural join––an equian equi--join in which one of the duplicate columns join in which one of the duplicate columns is eliminated in the result tableis eliminated in the result table

Outer joinOuter join––a join in which rows that do not have matching a join in which rows that do not have matching values in common columns are nonetheless included in the result values in common columns are nonetheless included in the result table (as opposed totable (as opposed to innerinner join, in which rows must have matchingjoin, in which rows must have matchingtable (as opposed to table (as opposed to innerinner join, in which rows must have matching join, in which rows must have matching values in order to appear in the result table)values in order to appear in the result table)

Union joinUnion join––includes all columns from each table in the join, and includes all columns from each table in the join, and an instance for each row of each tablean instance for each row of each tablean instance for each row of each tablean instance for each row of each table

The common columns in joined tables are usually the primary key of the

Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 33

dominant table and the foreign key of the dependent table in 1:M relationships

Page 4: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

Figure Figure 88--22Visualization of different join types with resultsVisualization of different join types with resultsVisualization of different join types with results Visualization of different join types with results

returned in shaded areareturned in shaded area

Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 44

Page 5: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

The following slides create tables for The following slides create tables for this enterprise data modelthis enterprise data model

Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 55

Page 6: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

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 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 66

Page 7: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

Natural Join ExampleNatural Join ExampleFor each customer who placed an order, what is the For each customer who placed an order, what is the

ppp ,p ,

customer’s name and order number?customer’s name and order number?

Join involves multiple tables in FROM clause

SELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, ORDER_IDSELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, ORDER_ID

Join involves multiple tables in FROM clause

FROM CUSTOMER_T NATURAL JOIN ORDER_T ON FROM CUSTOMER_T NATURAL JOIN ORDER_T ON

CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID;CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID;

ON clause performs the equality Note: from Fig. 1, you see that only 10 Customers have links with orders

p q ycheck for common columns of the two tables

have links with orders

Only 10 rows will be returned from this INNER

Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 77

returned from this INNER join

Page 8: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

Outer Join Example Outer Join Example (Microsoft Syntax)(Microsoft Syntax)

List the customer name, ID number, and order List the customer name, ID number, and order

(Microsoft Syntax)(Microsoft Syntax), ,, ,

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

SELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, ORDER_IDSELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, ORDER_IDFROM CUSTOMER_T, LEFT OUTER JOIN ORDER_TFROM CUSTOMER_T, LEFT OUTER JOIN ORDER_TON CUSTOMER T CUSTOMER ID = ORDER T CUSTOMER ID;ON CUSTOMER T CUSTOMER ID = ORDER T CUSTOMER ID;ON CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID;ON CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID;

LEFT OUTER JOIN syntax with ON causes customer data toON causes customer data to appear even if there is no corresponding order data

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

Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 88

no matching order rows

Page 9: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

Results

Unlike INNER j i thijoin, this will include customer rows withrows with no matching order rowsorder rows

Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 99

Page 10: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

Multiple Table Join ExampleMultiple Table Join ExampleAssemble all information necessary to create an Assemble all information necessary to create an invoice for order numberinvoice for order number 10061006

p pp p

invoice for order number invoice for order number 10061006

SELECT CUSTOMER T.CUSTOMER ID, CUSTOMER NAME, SELECT CUSTOMER T.CUSTOMER ID, CUSTOMER NAME,

Four tables involved in this join

_ _ , _ ,_ _ , _ ,CUSTOMER_ADDRESS, CITY, SATE, POSTAL_CODE, CUSTOMER_ADDRESS, CITY, SATE, POSTAL_CODE, ORDER_T.ORDER_ID, ORDER_DATE, QUANTITY, ORDER_T.ORDER_ID, ORDER_DATE, QUANTITY, PRODUCT_DESCRIPTION, STANDARD_PRICE, PRODUCT_DESCRIPTION, STANDARD_PRICE, (QUANTITY * UNIT_PRICE)(QUANTITY * UNIT_PRICE)

FROM CUSTOMER_T, ORDER_T, ORDER_LINE_T, PRODUCT_TFROM CUSTOMER_T, ORDER_T, ORDER_LINE_T, PRODUCT_T

WHERE CUSTOMER_T.CUSTOMER_ID = ORDER_LINE.CUSTOMER_ID WHERE CUSTOMER_T.CUSTOMER_ID = ORDER_LINE.CUSTOMER_ID AND ORDER_T.ORDER_ID = ORDER_LINE_T.ORDER_ID AND ORDER_T.ORDER_ID = ORDER_LINE_T.ORDER_ID

AND ORDER LINE T PRODUCT ID PRODUCT PRODUCT IDAND ORDER LINE T PRODUCT ID PRODUCT PRODUCT IDAND ORDER_LINE_T.PRODUCT_ID = PRODUCT_PRODUCT_IDAND ORDER_LINE_T.PRODUCT_ID = PRODUCT_PRODUCT_IDAND ORDER_T.ORDER_ID = AND ORDER_T.ORDER_ID = 10061006;;

E h i f bl i li h k di i i h WHERE l

Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 1010

Each pair of tables requires an equality-check condition in the WHERE clause, matching primary keys against foreign keys

Page 11: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

Figure 8-4 Results from a four-table join

F CUSTOMER T blFrom CUSTOMER_T table

From ORDER_T table From PRODUCT_T table

Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 1111

Page 12: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

Processing Multiple Tables Processing Multiple Tables g pg pUsing SubqueriesUsing Subqueries

SubquerySubquery––placing an inner query (SELECT placing an inner query (SELECT statement) inside an outer querystatement) inside an outer queryOptions:Options:

In a condition of the WHERE clauseIn a condition of the WHERE clauseAs a “table” of the FROM clauseAs a “table” of the FROM clauseWithin the HAVING clauseWithin the HAVING clause

Subqueries can be:Subqueries can be:NoncorrelatedNoncorrelated––executed once for the entire outer executed once for the entire outer queryqueryqueryqueryCorrelatedCorrelated––executed once for each row returned executed once for each row returned by the outer queryby the outer query

Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 1212

by the outer queryby the outer query

Page 13: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

Subquery ExampleSubquery ExampleShow all customers who have placed an orderShow all customers who have placed an order

q y pq y ppp

The IN operator will test to see if the CUSTOMER_ID value of a row is

SELECT CUSTOMER NAME FROM CUSTOMER TSELECT CUSTOMER NAME FROM CUSTOMER T

included in the list returned from the subquery

SELECT CUSTOMER_NAME FROM CUSTOMER_TSELECT CUSTOMER_NAME FROM CUSTOMER_TWHERE CUSTOMER_ID INWHERE CUSTOMER_ID IN

(SELECT DISTINCT CUSTOMER_ID FROM ORDER_T);(SELECT DISTINCT CUSTOMER_ID FROM ORDER_T);

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

Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 1313

outer query

Page 14: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

Correlated vs. Noncorrelated Correlated vs. Noncorrelated SubqueriesSubqueries

Noncorrelated subqueries:Noncorrelated subqueries:Do not depend on data from the outerDo not depend on data from the outerDo not depend on data from the outer Do not depend on data from the outer queryqueryExecute once for the entire outer queryExecute once for the entire outer queryExecute once for the entire outer queryExecute once for the entire outer query

Correlated subqueries:Correlated subqueries:M k f d t f th tM k f d t f th tMake use of data from the outer queryMake use of data from the outer queryExecute once for each row of the outer Execute once for each row of the outer queryqueryCan use the EXISTS operatorCan use the EXISTS operator

Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 1414

Page 15: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

Figure 8-6aFigure 8 6a Processing a noncorrelated subquery

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

1. The subquery executes and

t threturns the customer IDs from the ORDER_T table

These are the only customers that have

2. The outer query on the results of the subquery customers that have

IDs in the ORDER_T table

subquery

Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 1515

Page 16: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

Correlated Subquery ExampleCorrelated Subquery ExampleShow all orders that include furniture finished in Show all orders that include furniture finished in

q y pq y p

natural ashnatural ash

The EXISTS operator will return aThe EXISTS operator will return a TRUE value if the subquery resulted in a non-empty set, otherwise it returns a FALSE

SELECT DISTINCT ORDER_ID FROM ORDER_LINE_TSELECT DISTINCT ORDER_ID FROM ORDER_LINE_TWHERE EXISTSWHERE EXISTS

(SELECT * FROM PRODUCT T(SELECT * FROM PRODUCT T

returns a FALSE

(SELECT * FROM PRODUCT_T (SELECT * FROM PRODUCT_T WHERE PRODUCT_ID = ORDER_LINE_T.PRODUCT_ID WHERE PRODUCT_ID = ORDER_LINE_T.PRODUCT_ID AND PRODUCT_FINISH = ‘Natural ash’);AND PRODUCT_FINISH = ‘Natural ash’);

The subquery is testing for a value that comes from the outer query

Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 1616

q y

Page 17: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

Figure 8-6bFigure 8 6b Processing a correlated Subquery refers to outer-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 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 1717

Page 18: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

Another Subquery ExampleAnother Subquery ExampleShow all products whose standard price is higher than Show all products whose standard price is higher than the average pricethe average priceg pg p

One column of the subquery is an aggregate function that has an aliasSubquery forms the derived table used aggregate function that has an alias name. That alias can then be referred to in the outer query

Subquery forms the derived table used in the FROM clause of the outer query

SELECT PRODUCT_DESCRIPTION, STANDARD_PRICE, AVGPRICESELECT PRODUCT_DESCRIPTION, STANDARD_PRICE, AVGPRICEFROMFROM

(SELECT AVG(STANDARD_PRICE) AVGPRICE FROM PRODUCT_T),(SELECT AVG(STANDARD_PRICE) AVGPRICE FROM PRODUCT_T),PRODUCT_TPRODUCT_TWHERE STANDARD PRICE > AVG PRICE;WHERE STANDARD PRICE > AVG PRICE;_ _ ;_ _ ;

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 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 1818

Page 19: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

Union QueriesUnion QueriesUnion QueriesUnion QueriesCombine the output (union of multiple queries) Combine the output (union of multiple queries) together into a single result tabletogether into a single result tabletogether into a single result tabletogether into a single result table

First query

Combine

Second query

Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 1919

Page 20: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

Figure 8-7 Combining queries using UNION

Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 2020

Page 21: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

Conditional Expressions Using CaseConditional Expressions Using CaseConditional Expressions Using Case Conditional Expressions Using Case SyntaxSyntax

This is available with This is available with i fi fnewer versions of newer versions of

SQL, previously not SQL, previously not t f th t d dt f th t d dpart of the standardpart of the standard

Figure Figure 88--88

Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 2121

Page 22: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

Tips for Developing QueriesTips for Developing Queriesp p g Qp p g QBe familiar with the data model (entities and Be familiar with the data model (entities and

l ti hi )l ti hi )relationships)relationships)Understand the desired resultsUnderstand the desired resultsKnow the attributes desired in resultKnow the attributes desired in resultIdentify the entities that contain desired Identify the entities that contain desired yyattributesattributesReview ERDReview ERDConstruct a WHERE for each linkConstruct a WHERE for each linkFine tune with GROUP BY and HAING clausesFine tune with GROUP BY and HAING clausesFine tune with GROUP BY and HAING clauses Fine tune with GROUP BY and HAING clauses if neededif neededConsider the effect on unusual dataConsider the effect on unusual data

Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 2222

Consider the effect on unusual dataConsider the effect on unusual data

Page 23: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

Ensuring Transaction IntegrityEnsuring Transaction Integrityg g yg g yTransaction = A discrete unit of work that Transaction = A discrete unit of work that

t b l t l d tt b l t l d tmust be completely processed or not must be completely processed or not processed at allprocessed at all

M i l lti l d tM i l lti l d tMay involve multiple updatesMay involve multiple updatesIf any update fails, then all other updates must be If any update fails, then all other updates must be cancelledcancelledcancelledcancelled

SQL commands for transactionsSQL commands for transactionsBEGIN TRANSACTION/END TRANSACTIONBEGIN TRANSACTION/END TRANSACTIONBEGIN TRANSACTION/END TRANSACTIONBEGIN TRANSACTION/END TRANSACTION

Marks boundaries of a transactionMarks boundaries of a transactionCOMMITCOMMIT

Makes all updates permanentMakes all updates permanentROLLBACKROLLBACK

C l d i h l COMMITC l d i h l COMMITChapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 2323

Cancels updates since the last COMMITCancels updates since the last COMMIT

Page 24: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

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

Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 2424

Page 25: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

Data Dictionary FacilitiesData Dictionary Facilitiesyy

System tables that store metadataSystem tables that store metadatayyUsers usually can view some of these tablesUsers usually can view some of these tablesUsers are restricted from updating themUsers are restricted from updating themSome examples in Oracle Some examples in Oracle 1010gg

DBA_TABLESDBA_TABLES––descriptions of tablesdescriptions of tablesCO S SCO S S d fd fDBA_CONSTRAINTSDBA_CONSTRAINTS––description of constraintsdescription of constraints

DBA_USERSDBA_USERS––information about the users of the systeminformation about the users of the systemExamples in Microsoft SQL ServerExamples in Microsoft SQL Server 20002000Examples in Microsoft SQL Server Examples in Microsoft SQL Server 20002000

SYSCOLUMNSSYSCOLUMNS––table and column definitionstable and column definitionsSYSDEPENDSSYSDEPENDS––object dependencies based on foreign keysobject dependencies based on foreign keysS S SS S S object depe de c es based o o e g eysobject depe de c es based o o e g eysSYSPERMISSIONSSYSPERMISSIONS––access permissions granted to usersaccess permissions granted to users

Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 2525

Page 26: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

SQL:SQL:1999 1999 and SQL:and SQL:200200NN

Enhancements/ExtensionsEnhancements/ExtensionsUserUser defined data types (UDT)defined data types (UDT)UserUser--defined data types (UDT)defined data types (UDT)

Subclasses of standard types or an object typeSubclasses of standard types or an object typeAnalytical functions (for OLAP)Analytical functions (for OLAP)Analytical functions (for OLAP)Analytical functions (for OLAP)

CEILING, FLOOR, SQRT, RANK, DENSE_RANKCEILING, FLOOR, SQRT, RANK, DENSE_RANKWINDOWWINDOW improved numerical analysis capabilitiesimproved numerical analysis capabilitiesWINDOWWINDOW––improved numerical analysis capabilitiesimproved numerical analysis capabilities

New Data TypesNew Data TypesBIGINT MULTISET (collection) XMLBIGINT MULTISET (collection) XMLBIGINT, MULTISET (collection), XMLBIGINT, MULTISET (collection), XML

CREATE TABLE LIKECREATE TABLE LIKE––create a new table create a new table similar to an existing onesimilar to an existing onesimilar to an existing onesimilar to an existing oneMERGEMERGE

Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 2626

Page 27: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

SQL:SQL:1999 1999 and SQL:and SQL:200200NNQQ QQEnhancements/Extensions (cont.)Enhancements/Extensions (cont.)

Persistent Stored Modules (SQL/PSM)Persistent Stored Modules (SQL/PSM)C bilit t t d d d d lC bilit t t d d d d lCapability to create and drop code modulesCapability to create and drop code modulesNew statements:New statements:

CASE, IF, LOOP, FOR, WHILE, etc.CASE, IF, LOOP, FOR, WHILE, etc.Makes SQL into a procedural languageMakes SQL into a procedural language

Oracle has propriety version called Oracle has propriety version called PL/SQL and Microsoft SQL Server hasPL/SQL and Microsoft SQL Server hasPL/SQL, and Microsoft SQL Server has PL/SQL, and Microsoft SQL Server has Transact/SQLTransact/SQL

Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 2727

Page 28: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

Routines and TriggersRoutines and TriggersRoutines and TriggersRoutines and Triggers

RoutinesRoutinesRoutinesRoutinesProgram modules that execute on demandProgram modules that execute on demandFunctionsFunctions routines that return values androutines that return values andFunctionsFunctions––routines that return values and routines that return values and take input parameterstake input parametersProceduresProcedures routines that do not returnroutines that do not returnProceduresProcedures––routines that do not return routines that do not return values and can take input or output values and can take input or output parametersparametersparametersparameters

TriggersTriggersR ti th t t i tR ti th t t i tRoutines that execute in response to a Routines that execute in response to a database event (INSERT, UPDATE, or database event (INSERT, UPDATE, or DELETE)DELETE)

Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 2828

DELETE)DELETE)

Page 29: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

Figure 8-10 Triggers contrasted with stored procedures

Procedures are called explicitly

Triggers are event-driven

Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 2929

Triggers are event drivenSource: adapted from Mullins, 1995.

Page 30: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

Figure 8-11 Simplified trigger syntax, SQL:200n

Figure 8-12 Create routine syntax, SQL:200n

Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 3030

Page 31: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

Embedded and Dynamic SQLEmbedded and Dynamic SQL

Embedded SQLEmbedded SQLIncluding hardIncluding hard--coded SQL statements in a coded SQL statements in a program written in another language such as program written in another language such as p g g gp g g gC or JavaC or Java

Dynamic SQLDynamic SQLDynamic SQLDynamic SQLAbility for an application program to generate Ability for an application program to generate SQL code on the fly as the application isSQL code on the fly as the application isSQL code on the fly, as the application is SQL code on the fly, as the application is runningrunning

Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 3131

Page 32: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

OLAP SQLOLAP SQLOLAP SQLOLAP SQLOnline Transaction Processing (OLTP)Online Transaction Processing (OLTP)g ( )g ( )

RealReal--time processing of SQL transactions, time processing of SQL transactions, characterized by fast data entry and retrieval in multicharacterized by fast data entry and retrieval in multi--y yy yuser environmentsuser environmentsSmaller size, less data sources, many users, simpler Smaller size, less data sources, many users, simpler queries, more normalized, standard SQLqueries, more normalized, standard SQL

Online Analytical Processing (OLAP)Online Analytical Processing (OLAP)Use of graphical tools providing users with Use of graphical tools providing users with multidimensional views of data for analysis purposesmultidimensional views of data for analysis purposesLarger size, more data sources, fewer users, complex Larger size, more data sources, fewer users, complex queries, less normalized, OLAP SQL and statistical queries, less normalized, OLAP SQL and statistical

k (SPSS/SAS)k (SPSS/SAS)Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 3232

packages (SPSS/SAS)packages (SPSS/SAS)

Page 33: Chapter 8: Advanced SQL - is.cba.edu.kwis.cba.edu.kw/433/Handouts/ch08.pdf · Chapter 8: Advanced SQL Modern Database Management 9thEdition Jeffrey A. Jeffrey A. HofferHoffer, Mary

All rights reserved. No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means electronicretrieval system, or transmitted, in any form or by any means, electronic,

mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher. Printed in the United States of America.

Copyright © Copyright © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall

Chapter 8 © © 2009 2009 Pearson Education, Inc. Pearson Education, Inc. Publishing as Prentice HallPublishing as Prentice Hall 3333