数据库系统课件:ch3 SQL_第1页
数据库系统课件:ch3 SQL_第2页
数据库系统课件:ch3 SQL_第3页
数据库系统课件:ch3 SQL_第4页
数据库系统课件:ch3 SQL_第5页
已阅读5页,还剩58页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、Chapter 3: SQLChapter 3: SQLData DefinitionBasic Query StructureSet OperationsAggregate FunctionsNull ValuesNested SubqueriesComplex Queries ViewsModification of the DatabaseHistoryIBM Sequel language developed as part of System R project at the IBM San Jose Research LaboratoryRenamed Structured Que

2、ry Language (SQL)ANSI and ISO standard SQL:SQL-86SQL-89SQL-92 SQL:1999SQL:2003Commercial systems offer most, if not all, SQL-92 features, plus varying feature sets from later standards and special proprietary features. Not all examples here may work on your particular system.Data Definition Language

3、The schema for each relation.The domain of values associated with each attribute.Integrity constraintsThe set of indices to be maintained for each relations.Security and authorization information for each relation.The physical storage structure of each relation on disk.Allows the specification of no

4、t only a set of relations but also information about each relation, including:Domain Types in SQLchar(n). Fixed length character string, with user-specified length n.varchar(n). Variable length character strings, with user-specified maximum length . Integer (a finite subset of the integers that

5、 is machine-dependent).smallint. Small integer (a machine-dependent subset of the integer domain type).numeric(p,d). Fixed point number, with user-specified precision of p digits, with d digits to the right of decimal point. real, double precision. Floating point and double-precision floating point

6、numbers, with machine-dependent precision.float(n). Floating point number, with user-specified precision of at least n digits.More are covered in Chapter 4.Database Schemabranch (branch_name, branch_city, assets)customer (customer_name, customer_street, customer_city)loan (loan_number, branch_name,

7、amount)borrower (customer_name, loan_number)account (account_number, branch_name, balance)depositor (customer_name, account_number)Create Table ConstructAn SQL relation is defined using the create table command:create table r (A1 D1, A2 D2, ., An Dn,(integrity-constraint1),.,(integrity-constraintk)r

8、 is the name of the relationeach Ai is an attribute name in the schema of relation rDi is the data type of values in the domain of attribute AiCreate Table ConstructExample:create table branch(branch_namechar(15) not null,branch_citychar(30),assetsinteger)char(15) not nullchar(30) integer Integrity

9、Constraints in Create Tablenot nullprimary key (A1, ., An )Example: Declare branch_name as the primary key for branch.create table branch (branch_namechar(15), branch_citychar(30), assetsinteger, primary key (branch_name)primary key declaration on an attribute automatically ensures not null in SQL-9

10、2 onwards, needs to be explicitly stated in SQL-89primary keyCREATE TABLE ExampleCREATE TABLE Student ( SID smallint(5) unsigned, SN varchar(10) default NULL, SA int(2) default NULL, SD varchar(20) default NULL, SEX varchar(1) DEFAULT M CHECK(SEX=M) OR (SEX=F), PRIMARY KEY (SID)SIDSNSASDSEXStudentDr

11、op and Alter Table ConstructsThe drop table command deletes all information about the dropped relation from the database.The 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

12、 of A.All tuples in the relation are assigned null as the value for the new attribute. The 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 rDropping of attributes not supported by many databasesBasic Query Str

13、ucture SQL is based on set and relational operations with certain modifications and enhancementsA typical SQL query has the form:select A1, A2, ., Anfrom r1, r2, ., rmwhere PAi represents an attributeRi represents a relationP is a predicate.This query is equivalent to the relational algebra expressi

14、on.The result of an SQL query is a relation.The select ClauseThe select clause list the attributes desired in the result of a querycorresponds to the projection operation of the relational algebraExample: find the names of all branches in the loan relation:select branch_namefrom loanIn the relationa

15、l algebra, the query would be: branch_name (loan)The select Clauseselect branch_namefrom loanloanThe select Clause (Cont.)NOTE: SQL names are case insensitive (i.e., you may use upper- or lower-case letters.) E.g. Branch_Name BRANCH_NAME branch_nameSome people use upper case wherever we use bold fon

16、t.SQL allows duplicates in relations as well as in query results.To force the elimination of duplicates, insert the keyword distinct after select.The select Clause (Cont.)Find the names of all branches in the loan relations, and remove duplicatesselect distinct branch_namefrom loanThe keyword all sp

17、ecifies that duplicates not be removed.select all branch_namefrom loanbranch_namePerryridgeMianusPerryridgeDowntownDowntownRedwoodRound HillDowntownbranch_namePerryridgeMianusDowntownRedwoodRound HillDowntownalldistinctThe select Clause (Cont.)An asterisk in the select clause denotes “all attributes

18、”select *from loanloanThe select Clause (Cont.)The select clause can contain arithmetic expressions involving the operation, +, , , and /, and operating on constants or attributes of tuples.The query: select loan_number, branch_name, amount 100 from loanwould return a relation that is the same as th

19、e loan relation, except that the value of the attribute amount is multiplied by 100.loan_numberbranch_nameAmount*100L-11Round Hill90000L-14Downtown150000L-15Perryridge150000L-16Perryridge130000L-17Downtown100000L-23Redwood200000L-93Mianus50000The where ClauseThe where clause specifies conditions tha

20、t the result must satisfyCorresponds to the selection predicate of the relational algebra. To 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 1200loan_numberbranch_nameamountL-11Rou

21、nd Hill900L-14Downtown1500L-15Perryridge1500L-16Perryridge1300L-17Downtown1000L-23Redwood2000L-93Mianus500loan_numberL-15L-16The where Clause (Cont.)Comparison results can be combined using the logical connectives and, or, and not. Comparisons can be applied to results of arithmetic expressions.SQL

22、includes a between comparison operatorExample: Find the loan number of those loans with loan amounts between $900 and $1000 (that is, 900,1000select loan_numberfrom loanwhere amount between 900 and 1000The from ClauseThe from clause lists the relations involved in the queryCorresponds to the Cartesi

23、an product operation of the relational algebra.Find the Cartesian product borrower X loanselect from borrower, loanThe from Clause Find the name, loan number and loan amount of all customers having a loan at the Perryridge branch.select customer_name, borrower.loan_number, amountfrom borrower, loanw

24、here borrower.loan_number = loan.loan_number and branch_name = Perryridge customer_nameborrower.loan_numberamountAdamsL-161300HayersL-151500The Rename OperationThe SQL allows renaming relations and attributes using the as clause:old-name as new-nameFind the name, loan number and loan amount of all c

25、ustomers; 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_numbercustomer_nameloan_idamountTuple VariablesTuple variables are defined in the from clause via the use of the as clause.Fi

26、nd the customer names and their loan numbers for all customers having a loan at some branch. Find the names of all branches that have greater assets than some branch located in Brooklyn. select distinct T.branch_name from branch as T, branch as S where T.assets S.assets and S.branch_city = Brooklyn

27、Keyword as is optional and may be omitted borrower as T borrower Tselect customer_name, T.loan_number, S.amountfrom borrower as T, loan as Swhere T.loan_number = S.loan_numberString OperationsSQL includes a string-matching operator for comparisons on character strings. The operator “like” uses patte

28、rns that are described using two special characters:percent (%). The % character matches any substring.underscore (_). The _ character matches any character.Find the names of all customers whose street includes the substring “Main”.select customer_namefrom customerwhere customer_street like %Main% M

29、atch the name “Main%”like Main% escape String OperationsSQL supports a variety of string operations such asconcatenation (using “|”) converting from upper to lower case (and vice versa) finding string length, extracting substrings, etc.Ordering the Display of TuplesList in alphabetic order the names

30、 of all customers having a loan in Perryridge branchselect distinct customer_namefrom borrower, loanwhere borrower loan_number = loan.loan_number and branch_name = Perryridge order by customer_nameWe may specify desc for descending order or asc for ascending order, for each attribute; ascending orde

31、r is the default.Example: order by customer_name descSet OperationsThe set operations union, intersect, and except operate on relations and correspond to the relational algebra operations Each of the above operations automatically eliminates duplicates; to retain all duplicates use the corresponding

32、 multiset versions union all, intersect all and except all.Suppose a tuple occurs m times in r and n times in s, then, it occurs:m + n times in r union all smin(m,n) times in r intersect all smax(0, m n) times in r except all sSet OperationsFind all customers who have a loan, an account, or both:(se

33、lect customer_name from depositor)except(select customer_name from borrower)(select customer_name from depositor)intersect(select customer_name from borrower) Find all customers who have an account but no loan.(select customer_name from depositor)union(select customer_name from borrower) Find all cu

34、stomers who have both a loan and an account.Aggregate FunctionsThese functions operate on the multiset of values of a column of a relation, and return a valueavg: average valuemin: minimum valuemax: maximum valuesum: sum of valuescount: number of valuesAggregate Functions (Cont.)Find the average acc

35、ount balance at the Perryridge branch. Find the number of depositors in the bank. 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 depositorAggregate Functions Grou

36、p ByFind 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, accountwhere depositor.account_number = account.account_numbergroup by branch_namebalanceXA

37、ggregate Functions Having ClauseFind the names of all branches where the average account balance is more than $120.Note: predicates in the having clause are applied after the formation of groups whereas predicates in the where clause are applied before forming groupsselect branch_name, avg (balance)

38、from accountgroup by branch_namehaving avg (balance) 120Null ValuesIt is possible for tuples to have a null value, denoted by null, for some of their attributesnull signifies an unknown value or that a value does not exist.The predicate is null can be used to check for null values.Example: Find all

39、loan number which appear in the loan relation with null values for amount.select loan_numberfrom loanwhere amount is nullThe result of any arithmetic expression involving null is nullExample: 5 + null returns nullHowever, aggregate functions simply ignore nullsMore on next slideNull Values and Three

40、 Valued LogicAny comparison with null returns unknownExample: 5 null or null null or null = nullThree-valued logic using the truth value unknown:OR: (unknown or true) = true, (unknown or false) = unknown (unknown or unknown) = unknownAND: (true and unknown) = unknown, (false and unknown) = false, (u

41、nknown and unknown) = unknownNOT: (not unknown) = unknown“P is unknown” evaluates to true if predicate P evaluates to unknownResult of where clause predicate is treated as false if it evaluates to unknownNull Values and AggregatesTotal all loan amountsselect sum (amount )from loanAbove statement ign

42、ores null amountsResult is null if there is no non-null amountAll aggregate operations except count(*) ignore tuples with null values on the aggregated attributes.Nested SubqueriesSQL provides a mechanism for the nesting of subqueries.A subquery is a select-from-where expression that is nested withi

43、n another query.A common use of subqueries is to perform tests for set membership, set comparisons, and set cardinality.Example QueryFind all customers who have both an account and a loan at the bank. Find all customers who have a loan at the bank but do not have an account at the bankselect distinc

44、t 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 )Example QueryFind all customers who have both an account and a loan at the Perryridge branch Note: Above

45、 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 branch_name = Perryridge and (branch_name, customer_name) in (select branch_name, customer_name

46、 from account, depositor where account.account_number = depositor.account_number )Set ComparisonFind all branches that have greater assets than some branch located in Brooklyn. Same query using some clauseselect branch_namefrom branchwhere assets some (select assets from branch where branch_city = B

47、rooklyn) select distinct T.branch_namefrom branch as T, branch as Swhere T.assets S.assets and S.branch_city = Brooklyn Definition of Some ClauseF 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

48、assetsfrom branchwhere branch_city = Brooklyn) Definition of all ClauseF 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 (view) relation branch_avg in the from clause, and the a

49、ttributes of branch_avg can be used directly in the where clause.With ClauseThe with clause provides a way of defining a temporary view whose definition is available only to the query in which the with clause occurs. Find all accounts with the maximum balance with max_balance (value) as select max (

50、balance) from account select account_number from account, max_balance where account.balance = max_balance.valueComplex Queries using With ClauseFind 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,

51、 value) as select branch_name, sum (balance) from account group by branch_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.valueModification of the Database DeletionDelete all

52、 account tuples at the Perryridge branchdelete from accountwhere branch_name = Perryridge Delete all accounts at every branch located in the city Needham.delete from accountwhere branch_name in (select branch_name from branch where branch_city = Needham) Example QueryDelete the record of all account

53、s with balances below the average at the bank. delete from account where balance 10000update accountset balance = balance 1.05where balance 10000The order is importantCan be done better using the case statement (next slide)Case Statement for Conditional Updates Same query as before: Increase all acc

54、ounts with balances over $10,000 by 6%, all other accounts receive 5%.update accountset balance = case when balance = 10000 then balance *1.05 else balance * 1.06 endViewsIn some cases, it is not desirable for all users to see the entire logical model (that is, all the actual relations stored in the

55、 database.)Consider 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 (select customer_name, borrower.loan_number, branch_name from borrower, loan where borrower.loan_number = loan.loan_number )A view provides a mechanism to hide certain data from the view of certain users. Any relation that is not of th

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论