《数据库系统原理英文课件:ch3 SQL》由会员分享,可在线阅读,更多相关《数据库系统原理英文课件:ch3 SQL(66页珍藏版)》请在金锄头文库上搜索。
1、Database System Concepts, 5th Ed.Silberschatz, Korth and SudarshanSee www.db- for conditions on re-use Chapter 3: SQLSilberschatz, Korth and Sudarshan3.2Database System Concepts, 5th Edition, Oct 5, 2006Chapter 3: SQLnData DefinitionnBasic Query StructurenSet OperationsnAggregate FunctionsnNull Valu
2、esnNested SubqueriesnComplex Queries nViewsnModification of the DatabasenJoined Relations* Silberschatz, Korth and Sudarshan3.3Database System Concepts, 5th Edition, Oct 5, 2006HistorynIBM Sequel language developed as part of System R project at the IBM San Jose Research LaboratorynRenamed Structure
3、d Query Language (SQL)nANSI and ISO standard SQL:lSQL-86lSQL-89lSQL-92 lSQL:1999 (language name became Y2K compliant!)lSQL:2003nCommercial systems offer most, if not all, SQL-92 features, plus varying feature sets from later standards and special proprietary features. lNot all examples here may work
4、 on your particular system.Silberschatz, Korth and Sudarshan3.4Database System Concepts, 5th Edition, Oct 5, 2006Data Definition LanguagenThe schema for each relation.nThe domain of values associated with each attribute.nIntegrity constraintsnThe set of indices to be maintained for each relations.nS
5、ecurity and authorization information for each relation.nThe physical storage structure of each relation on disk.Allows the specification of not only a set of relations but also information about each relation, including:Silberschatz, Korth and Sudarshan3.5Database System Concepts, 5th Edition, Oct
6、5, 2006Domain Types in SQLnchar(n). Fixed length character string, with user-specified length n.nvarchar(n). Variable length character strings, with user-specified maximum length n.nint. Integer (a finite subset of the integers that is machine-dependent).nsmallint. Small integer (a machine-dependent
7、 subset of the integer domain type).nnumeric(p,d). Fixed point number, with user-specified precision of p digits, with n digits to the right of decimal point. nreal, double precision. Floating point and double-precision floating point numbers, with machine-dependent precision.nfloat(n). Floating poi
8、nt number, with user-specified precision of at least n digits.nMore are covered in Chapter 4.Silberschatz, Korth and Sudarshan3.6Database System Concepts, 5th Edition, Oct 5, 2006Create Table ConstructnAn SQL relation is defined using the create table command:create table r (A1 D1, A2 D2, ., An Dn,(
9、integrity-constraint1),.,(integrity-constraintk)lr is the name of the relationleach Ai is an attribute name in the schema of relation rlDi is the data type of values in the domain of attribute AinExample:create table branch(branch_namechar(15) not null,branch_citychar(30),assetsinteger)Silberschatz,
10、 Korth and Sudarshan3.7Database System Concepts, 5th Edition, Oct 5, 2006Integrity Constraints in Create Tablennot nullnprimary key (A1, ., An )Example: Declare branch_name as the primary key for branch.create table branch (branch_name char(15), branch_citychar(30), assetsinteger, primary key (branc
11、h_name)primary key declaration on an attribute automatically ensures not null in SQL-92 onwards, needs to be explicitly stated in SQL-89Silberschatz, Korth and Sudarshan3.8Database System Concepts, 5th Edition, Oct 5, 2006Drop and Alter Table ConstructsnThe drop table command deletes all information
12、 about the dropped relation from the database.nThe alter table command is used to add attributes to an existing relation: alter table r add A D where A is the name of the attribute to be added to relation r and D is the domain of A.lAll tuples in the relation are assigned null as the value for the n
13、ew attribute. nThe alter table command can also be used to drop attributes of a relation:alter table r drop A where A is the name of an attribute of relation rlDropping of attributes not supported by many databasesSilberschatz, Korth and Sudarshan3.9Database System Concepts, 5th Edition, Oct 5, 2006
14、Basic Query Structure nSQL is based on set and relational operations with certain modifications and enhancementsnA typical SQL query has the form:select A1, A2, ., Anfrom r1, r2, ., rmwhere PlAi represents an attributelri represents a relationlP is a predicate.nThis query is equivalent to the relati
15、onal algebra expression.nThe result of an SQL query is a relation.Silberschatz, Korth and Sudarshan3.10Database System Concepts, 5th Edition, Oct 5, 2006The select ClausenThe select clause list the attributes desired in the result of a querylcorresponds to the projection operation of the relational
16、algebranExample: find the names of all branches in the loan relation:select branch_namefrom loannIn the relational algebra, the query would be: branch_name (loan)nNOTE: SQL names are case insensitive (i.e., you may use upper- or lower-case letters.) lE.g. Branch_Name BRANCH_NAME branch_namelSome peo
17、ple use upper case wherever we use bold font.Silberschatz, Korth and Sudarshan3.11Database System Concepts, 5th Edition, Oct 5, 2006The select Clause (Cont.)nSQL allows duplicates in relations as well as in query results.nTo force the elimination of duplicates, insert the keyword distinct after sele
18、ct.nFind the names of all branches in the loan relations, and remove duplicatesselect distinct branch_namefrom loannThe keyword all specifies that duplicates not be removed.select all branch_namefrom loanSilberschatz, Korth and Sudarshan3.12Database System Concepts, 5th Edition, Oct 5, 2006The selec
19、t Clause (Cont.)nAn asterisk in the select clause denotes “all attributes”select *from loannThe select clause can contain arithmetic expressions involving the operation, +, , , and /, and operating on constants or attributes of tuples.nThe query: select loan_number, branch_name, amount 100 from loan
20、would return a relation that is the same as the loan relation, except that the value of the attribute amount is multiplied by 100.Silberschatz, Korth and Sudarshan3.13Database System Concepts, 5th Edition, Oct 5, 2006The where ClausenThe where clause specifies conditions that the result must satisfy
21、lCorresponds to the selection predicate of the relational algebra. nTo find all loan number for loans made at the Perryridge branch with loan amounts greater than $1200.select loan_numberfrom loanwhere branch_name = Perryridge and amount 1200nComparison results can be combined using the logical conn
22、ectives and, or, and not. nComparisons can be applied to results of arithmetic expressions.Silberschatz, Korth and Sudarshan3.14Database System Concepts, 5th Edition, Oct 5, 2006The where Clause (Cont.)nSQL includes a between comparison operatornExample: Find the loan number of those loans with loan
23、 amounts between $90,000 and $100,000 (that is, $90,000 and $100,000) select loan_numberfrom loanwhere amount between 90000 and 100000Silberschatz, Korth and Sudarshan3.15Database System Concepts, 5th Edition, Oct 5, 2006The from ClausenThe from clause lists the relations involved in the querylCorre
24、sponds to the Cartesian product operation of the relational algebra.nFind the Cartesian product borrower X loanselect from borrower, loann Find the name, loan number and loan amount of all customers having a loan at the Perryridge branch.select customer_name, borrower.loan_number, amount from borrow
25、er, loan where borrower.loan_number = loan.loan_number and branch_name = Perryridge Silberschatz, Korth and Sudarshan3.16Database System Concepts, 5th Edition, Oct 5, 2006The Rename OperationnThe SQL allows renaming relations and attributes using the as clause:old-name as new-namenFind the name, loa
26、n number and loan amount of all customers; rename the column name loan_number as loan_id.select customer_name, borrower.loan_number as loan_id, amountfrom borrower, loanwhere borrower.loan_number = loan.loan_numberSilberschatz, Korth and Sudarshan3.17Database System Concepts, 5th Edition, Oct 5, 200
27、6Tuple VariablesnTuple variables are defined in the from clause via the use of the as clause.nFind the customer names and their loan numbers for all customers having a loan at some branch.n Find the names of all branches that have greater assets than some branch located in Brooklyn. select distinct
28、T.branch_name from branch as T, branch as S where T.assets S.assets and S.branch_city = Brooklyn nKeyword as is optional and may be omitted borrower as T borrower Tselect customer_name, T.loan_number, S.amount from borrower as T, loan as S where T.loan_number = S.loan_numberSilberschatz, Korth and S
29、udarshan3.18Database System Concepts, 5th Edition, Oct 5, 2006String OperationsnSQL includes a string-matching operator for comparisons on character strings. The operator “like” uses patterns that are described using two special characters:lpercent (%). The % character matches any substring.lundersc
30、ore (_). The _ character matches any character.nFind the names of all customers whose street includes the substring “Main”.select customer_namefrom customerwhere customer_street like % Main% nMatch the name “Main%”like Main% escape nSQL supports a variety of string operations such aslconcatenation (
31、using “|”)l converting from upper to lower case (and vice versa)l finding string length, extracting substrings, etc.Silberschatz, Korth and Sudarshan3.19Database System Concepts, 5th Edition, Oct 5, 2006Ordering the Display of TuplesnList in alphabetic order the names of all customers having a loan
32、in Perryridge branchselect distinct customer_namefrom borrower, loanwhere borrower loan_number = loan.loan_number and branch_name = Perryridge order by customer_namenWe may specify desc for descending order or asc for ascending order, for each attribute; ascending order is the default.lExample: orde
33、r by customer_name descSilberschatz, Korth and Sudarshan3.20Database System Concepts, 5th Edition, Oct 5, 2006DuplicatesnIn relations with duplicates, SQL can define how many copies of tuples appear in the result.nMultiset versions of some of the relational algebra operators given multiset relations
34、 r1 and r2:1. (r1): If there are c1 copies of tuple t1 in r1, and t1 satisfies selections , then there are c1 copies of t1 in (r1).2. A (r ): For each copy of tuple t1 in r1, there is a copy of tuple A (t1) in A (r1) where A (t1) denotes the projection of the single tuple t1.3. r1 x r2 : If there ar
35、e c1 copies of tuple t1 in r1 and c2 copies of tuple t2 in r2, there are c1 x c2 copies of the tuple t1. t2 in r1 x r2Silberschatz, Korth and Sudarshan3.21Database System Concepts, 5th Edition, Oct 5, 2006Duplicates (Cont.)nExample: Suppose multiset relations r1 (A, B) and r2 (C) are as follows: r1
36、= (1, a) (2,a) r2 = (2), (3), (3)nThen B(r1) would be (a), (a), while B(r1) x r2 would be(a,2), (a,2), (a,3), (a,3), (a,3), (a,3)nSQL duplicate semantics: select A1, A2, ., Anfrom r1, r2, ., rmwhere Pis equivalent to the multiset version of the expression:Silberschatz, Korth and Sudarshan3.22Databas
37、e System Concepts, 5th Edition, Oct 5, 2006Set OperationsnThe set operations union, intersect, and except operate on relations and correspond to the relational algebra operations nEach of the above operations automatically eliminates duplicates; to retain all duplicates use the corresponding multise
38、t versions union all, intersect all and except all.Suppose a tuple occurs m times in r and n times in s, then, it occurs:lm + n times in r union all slmin(m,n) times in r intersect all slmax(0, m n) times in r except all sSilberschatz, Korth and Sudarshan3.23Database System Concepts, 5th Edition, Oc
39、t 5, 2006Set OperationsnFind all customers who have a loan, an account, or both:(select customer_name from depositor)except(select customer_name from borrower)(select customer_name from depositor)intersect(select customer_name from borrower)n Find all customers who have an account but no loan.(selec
40、t customer_name from depositor)union(select customer_name from borrower)n Find all customers who have both a loan and an account.Silberschatz, Korth and Sudarshan3.24Database System Concepts, 5th Edition, Oct 5, 2006Aggregate FunctionsnThese functions operate on the multiset of values of a column of
41、 a relation, and return a valueavg: average valuemin: minimum valuemax: maximum valuesum: sum of valuescount: number of valuesSilberschatz, Korth and Sudarshan3.25Database System Concepts, 5th Edition, Oct 5, 2006Aggregate Functions (Cont.)nFind the average account balance at the Perryridge branch.n
42、 Find the number of depositors in the bank.n Find the number of tuples in the customer relation.select avg (balance)from accountwhere branch_name = Perryridge select count (*)from customerselect count (distinct customer_name)from depositorSilberschatz, Korth and Sudarshan3.26Database System Concepts
43、, 5th Edition, Oct 5, 2006Aggregate Functions Group BynFind the number of depositors for each branch.Note: Attributes in select clause outside of aggregate functions must appear in group by listselect branch_name, count (distinct customer_name) from depositor, account where depositor.account_number
44、= account.account_number group by branch_nameSilberschatz, Korth and Sudarshan3.27Database System Concepts, 5th Edition, Oct 5, 2006Aggregate Functions Having ClausenFind the names of all branches where the average account balance is more than $1,200. Note: predicates in the having clause are applie
45、d after the formation of groups whereas predicates in the where clause are applied before forming groupsselect branch_name, avg (balance) from account group by branch_name having avg (balance) 1200Silberschatz, Korth and Sudarshan3.28Database System Concepts, 5th Edition, Oct 5, 2006Null ValuesnIt i
46、s possible for tuples to have a null value, denoted by null, for some of their attributesnnull signifies an unknown value or that a value does not exist.nThe predicate is null can be used to check for null values.lExample: Find all loan number which appear in the loan relation with null values for a
47、mount.select loan_numberfrom loanwhere amount is nullnThe result of any arithmetic expression involving null is nulllExample: 5 + null returns nullnHowever, aggregate functions simply ignore nullslMore on next slideSilberschatz, Korth and Sudarshan3.29Database System Concepts, 5th Edition, Oct 5, 20
48、06Null Values and Three Valued LogicnAny comparison with null returns unknownlExample: 5 null or null null or null = nullnThree-valued logic using the truth value unknown:lOR: (unknown or true) = true, (unknown or false) = unknown (unknown or unknown) = unknownlAND: (true and unknown) = unknown, (fa
49、lse and unknown) = false, (unknown and unknown) = unknownlNOT: (not unknown) = unknownl“P is unknown” evaluates to true if predicate P evaluates to unknownnResult of where clause predicate is treated as false if it evaluates to unknownSilberschatz, Korth and Sudarshan3.30Database System Concepts, 5t
50、h Edition, Oct 5, 2006Null Values and AggregatesnTotal all loan amountsselect sum (amount )from loanlAbove statement ignores null amountslResult is null if there is no non-null amountnAll aggregate operations except count(*) ignore tuples with null values on the aggregated attributes.Silberschatz, K
51、orth and Sudarshan3.31Database System Concepts, 5th Edition, Oct 5, 2006Nested SubqueriesnSQL provides a mechanism for the nesting of subqueries.nA subquery is a select-from-where expression that is nested within another query.nA common use of subqueries is to perform tests for set membership, set c
52、omparisons, and set cardinality.Silberschatz, Korth and Sudarshan3.32Database System Concepts, 5th Edition, Oct 5, 2006Example QuerynFind all customers who have both an account and a loan at the bank.n Find all customers who have a loan at the bank but do not have an account at the bankselect distin
53、ct customer_namefrom borrowerwhere customer_name not in (select customer_name from depositor )select distinct customer_namefrom borrowerwhere customer_name in (select customer_name from depositor )Silberschatz, Korth and Sudarshan3.33Database System Concepts, 5th Edition, Oct 5, 2006Example QuerynFi
54、nd all customers who have both an account and a loan at the Perryridge branchn Note: Above query can be written in a much simpler manner. The formulation above is simply to illustrate SQL features.select distinct customer_namefrom borrower, loanwhere borrower.loan_number = loan.loan_number and branc
55、h_name = Perryridge and (branch_name, customer_name ) in(select branch_name, customer_name from depositor, account where depositor.account_number = account.account_number )Silberschatz, Korth and Sudarshan3.34Database System Concepts, 5th Edition, Oct 5, 2006Set ComparisonnFind all branches that hav
56、e greater assets than some branch located in Brooklyn.n Same query using some clauseselect branch_namefrom branchwhere assets some (select assets from branch where branch_city = Brooklyn) select distinct T.branch_namefrom branch as T, branch as Swhere T.assets S.assets and S.branch_city = Brooklyn S
57、ilberschatz, Korth and Sudarshan3.35Database System Concepts, 5th Edition, Oct 5, 2006Definition of Some ClausenF some r t r such that (F t )Where can be: 056(5 some) = true050) = false505(5 some) = true (since 0 5)(read: 5 some tuple in the relation) (5 all(select assetsfrom branchwhere branch_city
58、 = Brooklyn) Silberschatz, Korth and Sudarshan3.37Database System Concepts, 5th Edition, Oct 5, 2006Definition of all ClausenF all r t r (F t)056(5 all) = false6104) = true546(5 all) = true (since 5 4 and 5 6)(5 1200Note that we do not need to use the having clause, since we compute the temporary (v
59、iew) relation branch_avg in the from clause, and the attributes of branch_avg can be used directly in the where clause.Silberschatz, Korth and Sudarshan3.43Database System Concepts, 5th Edition, Oct 5, 2006With ClausenThe with clause provides a way of defining a temporary view whose definition is av
60、ailable only to the query in which the with clause occurs. nFind all accounts with the maximum balance with max_balance (value) as select max (balance) from account select account_number from account, max_balance where account.balance = max_balance.valueSilberschatz, Korth and Sudarshan3.44Database
61、System Concepts, 5th Edition, Oct 5, 2006Complex Queries using With ClausenFind all branches where the total account deposit is greater than the average of the total account deposits at all branches. with branch_total (branch_name, value) as select branch_name, sum (balance) from account group by br
62、anch_name with branch_total_avg (value) as select avg (value) from branch_total select branch_name from branch_total, branch_total_avg where branch_total.value = branch_total_avg.valueSilberschatz, Korth and Sudarshan3.45Database System Concepts, 5th Edition, Oct 5, 2006ViewsnIn some cases, it is no
63、t desirable for all users to see the entire logical model (that is, all the actual relations stored in the database.)nConsider a person who needs to know a customers name, loan number and branch name, but has no need to see the loan amount. This person should see a relation described, in SQL, by (se
64、lect customer_name, borrower.loan_number, branch_name from borrower, loan where borrower.loan_number = loan.loan_number )nA view provides a mechanism to hide certain data from the view of certain users. nAny relation that is not of the conceptual model but is made visible to a user as a “virtual rel
65、ation” is called a view.Silberschatz, Korth and Sudarshan3.46Database System Concepts, 5th Edition, Oct 5, 2006View DefinitionnA view is defined using the create view statement which has the formcreate view v as where is any legal SQL expression. The view name is represented by v.nOnce a view is def
66、ined, the view name can be used to refer to the virtual relation that the view generates.nWhen a view is created, the query expression is stored in the database; the expression is substituted into queries using the view.Silberschatz, Korth and Sudarshan3.47Database System Concepts, 5th Edition, Oct
67、5, 2006Example QueriesnA view consisting of branches and their customersn Find all customers of the Perryridge branchcreate view all_customer as (select branch_name, customer_name from depositor, account where depositor.account_number =account.account_number ) union (select branch_name, customer_nam
68、e from borrower, loan where borrower.loan_number = loan.loan_number )select customer_namefrom all_customerwhere branch_name = Perryridge Silberschatz, Korth and Sudarshan3.48Database System Concepts, 5th Edition, Oct 5, 2006Views Defined Using Other ViewsnOne view may be used in the expression defin
69、ing another view nA view relation v1 is said to depend directly on a view relation v2 if v2 is used in the expression defining v1nA view relation v1 is said to depend on view relation v2 if either v1 depends directly to v2 or there is a path of dependencies from v1 to v2 nA view relation v is said t
70、o be recursive if it depends on itself.Silberschatz, Korth and Sudarshan3.49Database System Concepts, 5th Edition, Oct 5, 2006View ExpansionnA way to define the meaning of views defined in terms of other views.nLet view v1 be defined by an expression e1 that may itself contain uses of view relations
71、.nView expansion of an expression repeats the following replacement step:repeatFind any view relation vi in e1Replace the view relation vi by the expression defining vi until no more view relations are present in e1nAs long as the view definitions are not recursive, this loop will terminateSilbersch
72、atz, Korth and Sudarshan3.50Database System Concepts, 5th Edition, Oct 5, 2006Modification of the Database DeletionnDelete all account tuples at the Perryridge branchdelete from accountwhere branch_name = Perryridge nDelete all accounts at every branch located in the city Needham.delete from account
73、where branch_name in (select branch_name from branch where branch_city = Needham) Silberschatz, Korth and Sudarshan3.51Database System Concepts, 5th Edition, Oct 5, 2006Example QuerynDelete the record of all accounts with balances below the average at the bank. delete from account where balance 1000
74、0update accountset balance = balance 1.05where balance 10000lThe order is importantlCan be done better using the case statement (next slide)Silberschatz, Korth and Sudarshan3.55Database System Concepts, 5th Edition, Oct 5, 2006Case Statement for Conditional UpdatesnSame query as before: Increase all
75、 accounts with balances over $10,000 by 6%, all other accounts receive 5%. update account set balance = case when balance = 10000 then balance *1.05 else balance * 1.06 endSilberschatz, Korth and Sudarshan3.56Database System Concepts, 5th Edition, Oct 5, 2006Update of a ViewnCreate a view of all loa
76、n data in the loan relation, hiding the amount attributecreate view loan_branch asselect loan_number, branch_namefrom loannAdd a new tuple to branch_loaninsert into branch_loanvalues (L-37, Perryridge) This insertion must be represented by the insertion of the tuple(L-37, Perryridge, null )into the
77、loan relationSilberschatz, Korth and Sudarshan3.57Database System Concepts, 5th Edition, Oct 5, 2006Updates Through Views (Cont.)nSome updates through views are impossible to translate into updates on the database relationslcreate view v asselect loan_number, branch_name, amount from loan where bran
78、ch_name = Perryridge insert into v values ( L-99,Downtown, 23) nOthers cannot be translated uniquelylinsert into all_customer values (Perryridge, John) 4Have to choose loan or account, and create a new loan/account number!nMost SQL implementations allow updates only on simple views (without aggregat
79、es) defined on a single relationSilberschatz, Korth and Sudarshan3.58Database System Concepts, 5th Edition, Oct 5, 2006Joined Relations*nJoin operations take two relations and return as a result another relation.nThese additional operations are typically used as subquery expressions in the from clau
80、senJoin condition defines which tuples in the two relations match, and what attributes are present in the result of the join.nJoin type defines how tuples in each relation that do not match any tuple in the other relation (based on the join condition) are treated.Silberschatz, Korth and Sudarshan3.5
81、9Database System Concepts, 5th Edition, Oct 5, 2006Joined Relations Datasets for ExamplesnRelation loannRelation borrowernNote: borrower information missing for L-260 and loan information missing for L-155Silberschatz, Korth and Sudarshan3.60Database System Concepts, 5th Edition, Oct 5, 2006Joined R
82、elations Examples nloan inner join borrower onloan.loan_number = borrower.loan_numbernloan left outer join borrower onloan.loan_number = borrower.loan_numberSilberschatz, Korth and Sudarshan3.61Database System Concepts, 5th Edition, Oct 5, 2006Joined Relations Examplesnloan natural inner join borrow
83、ernloan natural right outer join borrowerSilberschatz, Korth and Sudarshan3.62Database System Concepts, 5th Edition, Oct 5, 2006Joined Relations Examplesnloan full outer join borrower using (loan_number)nFind all customers who have either an account or a loan (but not both) at the bank.select custom
84、er_namefrom (depositor natural full outer join borrower )where account_number is null or loan_number is nullDatabase System Concepts, 5th Ed.Silberschatz, Korth and SudarshanSee www.db- for conditions on re-use End of Chapter 3Silberschatz, Korth and Sudarshan3.64Database System Concepts, 5th Editio
85、n, Oct 5, 2006Figure 3.1: Database Schemabranch (branch_name, branch_city, assets)customer (customer_name, customer_street, customer_city)loan (loan_number, branch_name, amount)borrower (customer_name, loan_number)account (account_number, branch_name, balance)depositor (customer_name, account_number)Silberschatz, Korth and Sudarshan3.65Database System Concepts, 5th Edition, Oct 5, 2006Figure 3.3: Tuples inserted into loan and borrowerSilberschatz, Korth and Sudarshan3.66Database System Concepts, 5th Edition, Oct 5, 2006Figure 3.4:The loan and borrower relations