© 2007 by prentice hall 1 chapter 8: advanced sql modern database management 8 th edition jeffrey...
TRANSCRIPT
© 2007 by Prentice Hall© 2007 by Prentice Hall 11
Chapter 8:Chapter 8:Advanced SQLAdvanced SQL
Modern Database Modern Database ManagementManagement
88thth Edition EditionJeffrey A. Hoffer, Mary B. Prescott, Jeffrey A. Hoffer, Mary B. Prescott,
Fred R. McFaddenFred R. McFadden
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall 22
ObjectivesObjectives Definition of termsDefinition of terms Write multiple table SQL queriesWrite multiple table SQL queries Define and use three types of joinsDefine and use three types of joins Write correlated and noncorrelated Write correlated and noncorrelated
subqueriessubqueries Establish referential integrity in SQLEstablish referential integrity in SQL Understand triggers and stored proceduresUnderstand triggers and stored procedures Discuss SQL:1999 standard and its Discuss SQL:1999 standard and its
extension of SQL-92extension of SQL-92
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall
Processing Multiple TablesProcessing Multiple Tables The power of The power of RDBMSRDBMS is realized when working with is realized when working with
multiplemultiple tablestables TwoTwo tablestables can be can be joinedjoined when each contains a when each contains a
columncolumn that shares a that shares a commoncommon domain domain The The resultresult of a of a joinjoin operation is a operation is a singlesingle table table SelectedSelected columnscolumns from all tables are included from all tables are included Each Each rowrow returned contains returned contains datadata from rows of input from rows of input
tables where tables where valuesvalues for the for the commoncommon columnscolumns matchmatch RuleRule ofof thumbthumb: there should be : there should be oneone conditioncondition within within
the the WHEREWHERE clause for clause for eacheach pairpair of of tablestables being being joinedjoined
OneOne conditioncondition for joining for joining 22 tablestables, , twotwo conditionsconditions for for joining joining 33 tablestables, and so forth., and so forth.
TwoTwo basic basic approachesapproaches are used for are used for joiningjoining tables: tables: JoinJoin & & SubquerySubquery techniques techniques
33
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall 44
Processing Multiple Tables–Processing Multiple Tables–JoinsJoins
JoinJoin – – a relational operation that causes a relational operation that causes twotwo or more or more tablestables with a with a commoncommon domaindomain to be combined into a to be combined into a singlesingle tabletable or view or view
Equi-joinEqui-join – – a join in which the joining a join in which the joining conditioncondition is based is based on on equalityequality between between valuesvalues in the in the commoncommon columnscolumns; ; common columns appear redundantly in the result common columns appear redundantly in the result tabletable
NaturalNatural joinjoin – – an an equi-joinequi-join in which in which oneone of the of the duplicateduplicate columnscolumns is eliminated in the is eliminated in the resultresult table table
OuterOuter joinjoin – – a join in which a join in which rowsrows that do that do notnot have have matchingmatching valuesvalues in in commoncommon columnscolumns are nonetheless are nonetheless includedincluded in the in the resultresult table (as opposed to table (as opposed to innerinner joinjoin, in , in which rows which rows mustmust have have matchingmatching valuesvalues in order to appear in order to appear in the in the resultresult table) table)
UnionUnion joinjoin – – includes includes allall columnscolumns from from eacheach tabletable in the in the join, and an instance for each row of each tablejoin, 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© 2007 by Prentice Hall 55
The following slides create tables The following slides create tables for this enterprise data modelfor this enterprise data model
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall 66
These tables are used in queries that follow
Figure 8-1 Pine Valley Furniture Company Customer and Order tables with pointers from customers to their orders
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall 77
For each customer who placed an order, what is For each customer who placed an order, what is the customer’s name and order number?the customer’s name and order number?
SELECTSELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, ORDER_ID CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, ORDER_IDFROMFROM CUSTOMER_T CUSTOMER_T NATURALNATURAL JOINJOIN ORDER_T ORDER_T ON ON
CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID;CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID;
Join involves multiple tables in FROM clause
Natural Join ExampleNatural Join ExampleMicrosoft syntaxMicrosoft syntax
ON clause performs the equality check for common columns of the two tables
Note: from Fig. 1, you see that only 10 Customers have links with orders.
Only 10 rows will be returned from this INNER join.
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall
Example Example QueryQuery: what are the names of all customers who : what are the names of all customers who
have placed orders?have placed orders? ORACLEORACLE SQLSQL::
SELECTSELECT Customer_T.customer_ID, Customer_T.customer_ID, customer_name, order_IDcustomer_name, order_ID
FROMFROM Customer_T, Order_T Customer_T, Order_T
WHEREWHERE Customer_T.customer_ID = Customer_T.customer_ID = Order_T.customer_ID; Order_T.customer_ID;
MicrosoftMicrosoft AccessAccess SQLSQL:: SELECTSELECT Customer_T.customer_ID, Customer_T.customer_ID,
Customer_T.customer_Name, Order_T.order_IDCustomer_T.customer_Name, Order_T.order_ID
FROMFROM Customer_T Customer_T INNERINNER JOINJOIN Order_T Order_T ONON
Customer_T.customer_ID = Customer_T.customer_ID = Order_T.customer_ID;Order_T.customer_ID;
88
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall 99
List the customer name, ID number, and order List the customer name, ID number, and order number for all customers. number for all customers. Include customer Include customer information even for customers that do have an information even for customers that do have an orderorder
(Microsoft Syntax)(Microsoft Syntax)SELECTSELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME,
ORDER_IDORDER_IDFROMFROM CUSTOMER_T CUSTOMER_T LEFTLEFT OUTEROUTER JOINJOIN ORDER_T ORDER_TONON CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID; CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID;
Outer Join Example Outer Join Example
LEFT OUTER JOIN syntax with ON 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
(ORACLE Syntax)SELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, ORDER_IDFROM CUSTOMER_T LEFT OUTER JOIN ORDER_TWHERE CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID;
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall 1010
Results
Unlike INNER join, this will include customer rows with no matching order rows
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall 1111
Assemble all information necessary to create an Assemble all information necessary to create an invoiceinvoice for for orderorder number number 10061006
SELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, CUSTOMER_ADDRESS, CITY, SATE, SELECT CUSTOMER_T.CUSTOMER_ID, CUSTOMER_NAME, CUSTOMER_ADDRESS, CITY, SATE, POSTAL_CODE, ORDER_T.ORDER_ID, ORDER_DATE, QUANTITY, PRODUCT_DESCRIPTION, POSTAL_CODE, ORDER_T.ORDER_ID, ORDER_DATE, QUANTITY, PRODUCT_DESCRIPTION, STANDARD_PRICE, (QUANTITY * UNIT_PRICE)STANDARD_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_T.CUSTOMER_ID WHERE CUSTOMER_T.CUSTOMER_ID = ORDER_T.CUSTOMER_ID AND AND ORDER_T.ORDER_ID = ORDER_LINE_T.ORDER_ID ORDER_T.ORDER_ID = ORDER_LINE_T.ORDER_ID
AND ORDER_LINE_T.PRODUCT_ID = PRODUCT_T.PRODUCT_IDAND ORDER_LINE_T.PRODUCT_ID = PRODUCT_T.PRODUCT_IDAND ORDER_T.ORDER_ID = 1006;AND ORDER_T.ORDER_ID = 1006;
Four tables involved in this join
Multiple Table Join ExampleMultiple Table Join Example
Each pair of tables requires an equality-check condition in the WHERE clause, matching primary keys against foreign keys
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall 1212
Figure 8-2 Results from a four-table join
From CUSTOMER_T table
From ORDER_T table From PRODUCT_T table
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall 1313
Processing Multiple Tables Processing Multiple Tables Using SubqueriesUsing Subqueries
SubquerySubquery – placing an – placing an innerinner queryquery (SELECT statement) (SELECT statement) insideinside an an outerouter queryquery
OptionsOptions:: In a In a conditioncondition of the of the WHEREWHERE clause clause As a “As a “tabletable” of the ” of the FROMFROM clause clause WithinWithin the the HAVINGHAVING clause clause
SubqueriesSubqueries can be: can be: NoncorrelatedNoncorrelated – executed – executed onceonce for the for the entireentire
outerouter query query CorrelatedCorrelated – executed – executed onceonce for for eacheach rowrow
returned by the returned by the outerouter query query
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall 1414
Correlated vs. Noncorrelated Correlated vs. Noncorrelated SubqueriesSubqueries
NoncorrelatedNoncorrelated subqueries: subqueries: Do Do notnot dependdepend on on datadata from the from the outerouter
queryquery Execute Execute onceonce for the for the entireentire outerouter query query
CorrelatedCorrelated subqueries: subqueries: Make Make useuse of of datadata from the from the outerouter queryquery Execute Execute onceonce for for eacheach rowrow of the of the outerouter
queryquery Can use the Can use the EXISTSEXISTS operator operator
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall 1515
Show Show allall customerscustomers who have who have placedplaced an an orderorder
SELECTSELECT CUSTOMER_NAME CUSTOMER_NAME FROMFROM CUSTOMER_T CUSTOMER_TWHEREWHERE CUSTOMER_ID CUSTOMER_ID ININ
((SELECTSELECT DISTINCT CUSTOMER_ID DISTINCT CUSTOMER_ID FROMFROM ORDER_T); ORDER_T);
Subquery ExampleSubquery Example Noncorrelated Noncorrelated subqueries subqueries
Subquery is embedded in parentheses. In this case it returns a list that will be used in the WHERE clause of the outer query
The IN operator will test to see if the CUSTOMER_ID value of a row is included in the list returned from the subquery
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall 1616
Figure 8-3a Processing a noncorrelated subquery
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
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 © 2007 by Prentice Hall© 2007 by Prentice Hall 1717
Show Show allall ordersorders that include furniture finished in that include furniture finished in naturalnatural ashash
SELECTSELECT DISTINCTDISTINCT ORDER_ID ORDER_ID FROMFROM ORDER_LINE_T ORDER_LINE_TWHEREWHERE EXISTSEXISTS
((SELECTSELECT * * FROMFROM PRODUCT_T PRODUCT_T WHEREWHERE PRODUCT_ID = ORDER_LINE_T.PRODUCT_ID PRODUCT_ID = ORDER_LINE_T.PRODUCT_ID ANDAND PRODUCT_FINISH = ‘Natural ash’); PRODUCT_FINISH = ‘Natural ash’);
Correlated Subquery ExampleCorrelated Subquery Example
The subquery is testing for a value that comes from the outer query
The EXISTS operator will return a TRUE value if the subquery resulted in a non-empty set, otherwise it returns a FALSE
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall 1818
Figure 8-3b Processing a correlated subquery
Subquery refers to outer-query 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 © 2007 by Prentice Hall© 2007 by Prentice Hall
When When EXISTSEXISTS and and NOTNOT EXISTSEXISTS is used in is used in a subquery, the a subquery, the selectselect listlist of the of the subquery will usually select subquery will usually select allall columns columns ((SelectSelect **))
It does It does notnot mattermatter which which columnscolumns are are returnedreturned
The purpose of the The purpose of the subquerysubquery is to is to testtest if if any any rowsrows fitfit the the conditionsconditions, , notnot to to returnreturn valuesvalues from particular from particular columnscolumns for for comparisoncomparison purposes in the purposes in the outerouter queryquery
The The columnscolumns that will be that will be displayeddisplayed are are determineddetermined strictly by the strictly by the outerouter queryquery
1919
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall 2020
Show Show allall productsproducts whose standard whose standard priceprice is is higherhigher than the than the averageaverage priceprice
SELECTSELECT PRODUCT_DESCRIPTION, STANDARD_PRICE, AVGPRICE PRODUCT_DESCRIPTION, STANDARD_PRICE, AVGPRICEFROMFROM
((SELECTSELECT AVGAVG(STANDARD_PRICE) AVGPRICE (STANDARD_PRICE) AVGPRICE FROMFROM PRODUCT_T), PRODUCT_T),PRODUCT_TPRODUCT_TWHEREWHERE STANDARD_PRICE > AVGPRICE; STANDARD_PRICE > AVGPRICE;
Another Subquery ExampleAnother Subquery Example
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
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
Subquery forms the derived table used in the FROM clause of the outer query
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall 2121
Combining (Union) QueriesCombining (Union) Queries CombineCombine the the outputoutput (union of (union of multiplemultiple
queriesqueries) together into a ) together into a singlesingle resultresult tabletable
First query
Second query
Combine
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall
The expression QUANTITY has been created in The expression QUANTITY has been created in which the strings “Smallest Quantity” and which the strings “Smallest Quantity” and “Largest Quantity” are inserted“Largest Quantity” are inserted
The The resultresult of the of the UnionUnion QueryQuery::
CUSTOMER_idCUSTOMER_id CUSTOMER_Name Ordered_QuantityCUSTOMER_Name Ordered_Quantity QuantityQuantity
11 ContemporaryContemporary 1 1Smallest QtySmallest Qty
22 Value FurnitureValue Furniture 1 1Smallest QtySmallest Qty
11 ContemporaryContemporary 10 10Largest QtyLargest Qty
2222
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall
أرقام البرامج التدريبية التي ساعاتها اإلجمالية أرقام البرامج التدريبية التي ساعاتها اإلجمالية : : 33مثال مثال )أو كالهما(. )أو كالهما(. 1515 ساعة أو التي نفذها المدرب ساعة أو التي نفذها المدرب 6060أكبر أكبر
.. رتب النتائج تنازليا برقم البرنامجرتب النتائج تنازليا برقم البرنامجSELECT CRS#SELECT CRS# FROM COURSEFROM COURSE WHERE C#HRS > 60WHERE C#HRS > 60UNIONUNION SELECT CRS#SELECT CRS# FROM TRAINERFROM TRAINER WHERE EMP# = 15WHERE EMP# = 15 ORDER BY 1 DESC ;ORDER BY 1 DESC ;
GroupingGrouping المجموعـاتالمجموعـاتUNIONUNION دمج نتائج استفسارات متعددةدمج نتائج استفسارات متعددة
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall
: أرقام الدورات التدريبية التي ساعاتها اإلجمالية : أرقام الدورات التدريبية التي ساعاتها اإلجمالية 44مثال مثال )أو كالهما(. )أو كالهما(. 1515 ساعة أو التي نفذها المدرب ساعة أو التي نفذها المدرب 6060أكبر من أكبر من
رتب النتائج تنازليا برقم الدورة مع إظهار الصفوف رتب النتائج تنازليا برقم الدورة مع إظهار الصفوف .. المتكررةالمتكررة
SELECT CRS#SELECT CRS# FROM COURSEFROM COURSE WHERE C#HRS > 60WHERE C#HRS > 60UNION ALLUNION ALL SELECTSELECT CRS#CRS# FROM TRAINERFROM TRAINER WHEREWHERE EMP# = 15EMP# = 15 ORDERORDER BY 1 DESCBY 1 DESC ;;
GroupingGrouping المجموعـاتالمجموعـاتUNIONUNION دمج نتائج استفسارات متعددةدمج نتائج استفسارات متعددة
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall
استرجاع البيانات من أكثر من جدولاسترجاع البيانات من أكثر من جدول عرض قائمة بأسماء كل الدورات التدريبية عرض قائمة بأسماء كل الدورات التدريبية 11مثال مثال
:: وجميع بيانات مخطط تنفيذهاوجميع بيانات مخطط تنفيذها SELECT CTITLE, OFFER.*SELECT CTITLE, OFFER.* FROM COURSE, OFFERFROM COURSE, OFFER WHERE WHERE COURSECOURSE.CRS# = .CRS# = OFFEROFFER.CRS# ;.CRS# ; FROMFROM استخدام مميز مختصر لجداولاستخدام مميز مختصر لجداول
SELECT CTITLE, SELECT CTITLE, OO.*.* FROM COURSE FROM COURSE CC, OFFER , OFFER OO WHERE WHERE C.C.CRS# = CRS# = O.O.CRS# ;CRS# ;
SELECTSELECT تعليمةتعليمةJoining TablesJoining Tables ربـــط الجـــداولربـــط الجـــداول
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall
WHEREWHERE شروط أخرى في عبارةشروط أخرى في عبارة عرض قائمة بأسماء كل البرامج التدريبية عرض قائمة بأسماء كل البرامج التدريبية 22مثال مثال
وجميع بيانات مخطط تنفيذها للدورات المخططة وجميع بيانات مخطط تنفيذها للدورات المخططة ”القاهرة”القاهرةفي في “ “ ::
SELECT CTITLE, SELECT CTITLE, OO.*.* FROM COURSE FROM COURSE CC, OFFER , OFFER OO WHERE WHERE C.C.CRS# = CRS# = O.O.CRS# CRS# AND AND O.O.LOCATION = ‘Cairo' ;LOCATION = ‘Cairo' ;
SELECTSELECT تعليمةتعليمةط الجداولط الجداولتابع ربتابع رب Joining TablesJoining Tables
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall
WHEREWHERE شروط أخرى في عبارةشروط أخرى في عبارة عرض قائمة بأرقام وأسماء كل الدورات عرض قائمة بأرقام وأسماء كل الدورات 33مثال مثال
التدريبية التي لم يحدد لها مكان تنفيذ )الشرط في التدريبية التي لم يحدد لها مكان تنفيذ )الشرط في ((جدول آخرجدول آخر
SELECT SELECT CC.CRS#, CTITLE.CRS#, CTITLE
FROM COURSE FROM COURSE CC, OFFER , OFFER OO
WHERE WHERE CC.CRS# = .CRS# = OO.CRS# .CRS#
AND AND OO.LOCATION IS NULL ;.LOCATION IS NULL ;
SELECTSELECT تعليمةتعليمةط الجداولط الجداولتابع ربتابع رب Joining TablesJoining Tables
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall
ربط أكثر من جدولينربط أكثر من جدولين
المخطط 44مثال مثال التدريبية الدورات بأسماء قائمة المخطط عرض التدريبية الدورات بأسماء قائمة عرضفي في تنفيذها “ تنفيذها “ القاهرة” مدربيها القاهرة” مدربيها وأرقام وأرقام
SELECT DISTINCT CTITLE, T.EMP#, O.LOCATIONSELECT DISTINCT CTITLE, T.EMP#, O.LOCATION
FROMFROM COURSE CCOURSE C, , OFFER OOFFER O, , TRAINER TTRAINER T
WHERE C.CRS# = O.CRS# WHERE C.CRS# = O.CRS#
AND O.CRS# = T.CRS#AND O.CRS# = T.CRS#
AND O.LOCATION = ‘Cairo' ; AND O.LOCATION = ‘Cairo' ;
SELECTSELECT تعليمةتعليمةط الجداولط الجداولتابع ربتابع رب Joining TablesJoining Tables
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall
((االستفسارات المتداخلة )الفرعيةاالستفسارات المتداخلة )الفرعية
SELECT ...SELECT ... FROM ...FROM ... WHERE WHERE (SELECT(SELECT ......
FROM ...FROM ... WHERE ...) ;WHERE ...) ;
SELECTSELECT تعليمةتعليمةSubqueriesSubqueries االستفسارات المتداخلةاالستفسارات المتداخلة
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall
تابع االستفسارات المتداخلة - إرجاع قيمة تابع االستفسارات المتداخلة - إرجاع قيمة واحدةواحدة
: قائمة بالموظفين الذين معدالت أدائهم أكبر : قائمة بالموظفين الذين معدالت أدائهم أكبر 22مثال مثال من المتوسط العام لألداءمن المتوسط العام لألداء
SELECT LNAME, FNAMESELECT LNAME, FNAMEFROM EMPFROM EMPWHERE RAT WHERE RAT >>
(SELECT NUMBER (AVG (RAT), 5, 2)(SELECT NUMBER (AVG (RAT), 5, 2) FROM EMP) ;FROM EMP) ;
SELECTSELECT تعليمةتعليمةSubqueriesSubqueries االستفسارات المتداخلةاالستفسارات المتداخلة
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall
االستفسار الفرعي بعد أي من عوامل المقارنةاالستفسار الفرعي بعد أي من عوامل المقارنة
== >>
WHERE ColumnName < (subquery) ; WHERE ColumnName < (subquery) ; >=>= <=<= <><>
> ANY, > ALL , IN > ANY, > ALL , IN
SELECTSELECT تعليمةتعليمةSubqueriesSubqueries االستفسارات المتداخلةاالستفسارات المتداخلة
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall
تابع االستفسارات المتداخلة - إرجاع قيمة تابع االستفسارات المتداخلة - إرجاع قيمة واحدةواحدة
تزيد : : 33مثال مثال التي ومرتباتهم الموظفين بأسماء تزيد قائمة التي ومرتباتهم الموظفين بأسماء قائمةالمرتبات متوسط المرتبات عن متوسط عن
SELECT LNAME, FNAME, SALARYSELECT LNAME, FNAME, SALARY
FROMFROM EMPEMP
WHERE SALARY WHERE SALARY >>
(SELECT AVG (SALARY) FROM EMP) ;(SELECT AVG (SALARY) FROM EMP) ;
SELECTSELECT تعليمةتعليمةSubqueriesSubqueries االستفسارات المتداخلةاالستفسارات المتداخلة
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall
SELECT تعليمةSubqueries االستفسارات المتداخلة
تابع االستفسارات المتداخلة - إرجاع قيمة تابع االستفسارات المتداخلة - إرجاع قيمة واحدةواحدة
: أرقام الدورات التدريبية التي نفذها المدرب : أرقام الدورات التدريبية التي نفذها المدرب44مثال مثال 'RASHEED ALSALEH''RASHEED ALSALEH'
SELECT DISTINCT CRS#SELECT DISTINCT CRS# FROM FROM TRAINER WHERE TRAINER WHERE EMP# = (SELECT EMP#EMP# = (SELECT EMP#
FROM EMPFROM EMP WHERE LNAME = 'ALSALEH’WHERE LNAME = 'ALSALEH’ AND FNAME = 'RASHEED') ;AND FNAME = 'RASHEED') ;
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall
SELECT تعليمةSubqueries االستفسارات المتداخلة
ربط ربط تابع االستفسارات المتداخلة - إرجاع قيمة واحدة - تابع االستفسارات المتداخلة - إرجاع قيمة واحدة - الفرعية الفرعية االستفسارات AND/ORAND/OR االستفسارات
: أسماء الموظفين الذين لهم أعلى وأقل معدل : أسماء الموظفين الذين لهم أعلى وأقل معدل 66مثال مثال أداءأداء
SELECT LNAME, FNAME, RATSELECT LNAME, FNAME, RAT FROM EMPFROM EMP WHERE RAT =WHERE RAT =
(SELECT MAX (RAT)(SELECT MAX (RAT) FROM EMP)FROM EMP) OR RAT =OR RAT = (SELECT MIN (RAT)(SELECT MIN (RAT)
FROM EMP) ;FROM EMP) ;
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall 3535
Ensuring Transaction IntegrityEnsuring Transaction Integrity TransactionTransaction = A discrete = A discrete unitunit of of workwork that that
must be must be completelycompletely processedprocessed oror notnot processedprocessed at at allall May involve multiple updatesMay involve multiple updates If If anyany updateupdate failsfails, then , then allall other other updatesupdates must must
be be cancelledcancelled SQLSQL commandscommands for for transactionstransactions
BEGINBEGIN TRANSACTION/ENDTRANSACTION/END TRANSACTIONTRANSACTION Marks Marks boundariesboundaries of a transaction of a transaction
COMMITCOMMIT Makes all updates Makes all updates permanentpermanent
ROLLBACKROLLBACK CancelsCancels updates since the last COMMIT updates since the last COMMIT
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall 3636
Figure 8-5 An SQL Transaction sequence (in pseudocode)
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall 3737
Data Dictionary FacilitiesData Dictionary Facilities
System System tablestables that store that store metadatametadata UsersUsers usually can usually can viewview some of these some of these tablestables UsersUsers are are restrictedrestricted from from updatingupdating them them Some Some examplesexamples in in OracleOracle 10g10g
DBA_TABLES – descriptions of tablesDBA_TABLES – descriptions of tables DBA_CONSTRAINTS – description of constraintsDBA_CONSTRAINTS – description of constraints DBA_USERS – information about the users of the systemDBA_USERS – information about the users of the system
Examples in Examples in MicrosoftMicrosoft SQLSQL ServerServer 20002000 SYSCOLUMNS – table and column definitionsSYSCOLUMNS – table and column definitions SYSDEPENDS – object dependencies based on foreign SYSDEPENDS – object dependencies based on foreign
keyskeys SYSPERMISSIONS – access permissions granted to usersSYSPERMISSIONS – access permissions granted to users
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall 3838
SQL:1999 and SQL:2003 SQL:1999 and SQL:2003 Enhancements Enhancements
User-defined data types (User-defined data types (UDTUDT)) Subclasses of standard types or an object typeSubclasses of standard types or an object type
On-Line Analytical Processing (On-Line Analytical Processing (OLAPOLAP)) CEILING, FLOOR, SQRT, RANK, DENSE_RANKCEILING, FLOOR, SQRT, RANK, DENSE_RANK WINDOW–improved numerical analysis WINDOW–improved numerical analysis
capabilitiescapabilities NewNew DataData TypesTypes
BIGINT, MULTISET (collection), XMLBIGINT, MULTISET (collection), XML CREATECREATE TABLETABLE LIKELIKE – create a new table – create a new table
similar to an existing onesimilar to an existing one MERGEMERGE
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall 3939
Persistent Stored Modules (Persistent Stored Modules (SQL/PSMSQL/PSM)) Capability to create and drop Capability to create and drop codecode
modulesmodules storedstored in the in the databasedatabase schema. schema. New statements:New statements:
CASE, IF, LOOP, FOR, WHILE, etc.CASE, IF, LOOP, FOR, WHILE, etc. Makes SQL into a Makes SQL into a proceduralprocedural languagelanguage
OracleOracle has propriety version called has propriety version called PL/SQLPL/SQL, and , and MicrosoftMicrosoft SQL Server has SQL Server has Transact/SQLTransact/SQL
SQL:1999 and SQL:2003 SQL:1999 and SQL:2003 Programming Extensions Programming Extensions
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall 4040
Routines and TriggersRoutines and Triggers RoutinesRoutines
ProgramProgram modulesmodules that that executeexecute onon demanddemand FunctionsFunctions – – routinesroutines that that returnreturn valuesvalues
and take input parametersand take input parameters ProceduresProcedures – – routinesroutines that do not return that do not return
values and can take values and can take inputinput or or outputoutput parametersparameters
TriggersTriggers RoutinesRoutines that that executeexecute in in responseresponse to a to a
databasedatabase eventevent (INSERT, UPDATE, or (INSERT, UPDATE, or DELETE)DELETE)
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall 4141
Figure 8-6
Procedures are called explicitly
Triggers are event-drivenSource: adapted from Mullins, 1995.
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall 4242
Figure 8-7 Simplified trigger syntax, SQL:2003
Figure 8-8 Create routine syntax, SQL:2003
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall
Trigger Example (PL/SQL)Trigger Example (PL/SQL)
CreateCreate triggertrigger Order_ID_BIR Order_ID_BIR
BeforeBefore InsertInsert On Order_T On Order_T
For For EachEach ROWROW
BeginBegin
Select ID_sequence.NextvalSelect ID_sequence.Nextval
Into :New.Order_IDInto :New.Order_ID
From Dual;From Dual;
EndEnd Order_ID_BIR; Order_ID_BIR;
4343
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall
Routine Example (PL/SQL)Routine Example (PL/SQL)
CreateCreate or Replace or Replace ProcedureProcedure Product_Line_SaleProduct_Line_Sale
AS AS BeginBegin
update Product_Tupdate Product_T
set sale_price = 0.9 * standard_priceset sale_price = 0.9 * standard_price
where standard_price >= 400;where standard_price >= 400;
update Product_Tupdate Product_T
set sale_price = 0.85 * standard_priceset sale_price = 0.85 * standard_price
where standard_price < 400;where standard_price < 400;
EndEnd;;
SQL> Exec Product_Line_saleSQL> Exec Product_Line_sale
4444
Chapter 8 © 2007 by Prentice Hall© 2007 by Prentice Hall 4545
Embedded and Dynamic SQLEmbedded and Dynamic SQL
EmbeddedEmbedded SQLSQL Including Including hard-codedhard-coded SQLSQL statementsstatements in in
a a programprogram written in another written in another languagelanguage such as such as CC or or JavaJava
DynamicDynamic SQLSQL Ability for an Ability for an applicationapplication programprogram to to
generategenerate SQLSQL codecode on the on the flyfly, as the , as the application is application is runningrunning