




版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
1、Chapter 3: Introduction to SQLChapter 3: Introduction to SQLOverview of the SQL Query LanguageData DefinitionBasic Query StructureAdditional Basic OperationsSet OperationsNull ValuesAggregate FunctionsNested SubqueriesModification of the Database HistoryIBM Sequel language developed as part of Syste
2、m R project at the IBM San Jose Research LaboratoryRenamed Structured Query Language (SQL)ANSI and ISO standard SQL:SQL-86, SQL-89, SQL-92 SQL:1999, SQL:2003, SQL:2008Commercial systems offer most, if not all, SQL-92 features, plus varying feature sets from later standards and special proprietary fe
3、atures. Not all examples here may work on your particular system.Data Definition LanguageThe schema for each relation.The domain of values associated with each attribute.Integrity constraintsAnd as we will see later, also other information such as The set of indices to be maintained for each relatio
4、ns.Security and authorization information for each relation.The physical storage structure of each relation on disk.The SQL data-definition language (DDL) allows the specification of information about relations, including:Domain Types in SQLchar(n). Fixed length character string, with user-specified
5、 length n.varchar(n). Variable length character strings, with user-specified maximum length . Integer (a finite subset of the integers that is machine-dependent).smallint. Small integer (a machine-dependent subset of the integer domain type).numeric(p,d). Fixed point number, with user-specified
6、 precision of p digits, with n digits to the right of decimal point. real, double precision. Floating point and double-precision floating point 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.
7、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 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
8、attribute AiExample: create table instructor ( ID char(5), name varchar(20) not null, dept_name varchar(20), salary numeric(8,2)insert into instructor values (10211, Smith, Biology, 66000);insert into instructor values (10211, null, Biology, 66000);Integrity Constraints in Create Tablenot nullprimar
9、y key (A1, ., An )foreign key (Am, ., An ) references rExample: Declare dept_name as the primary key for department.create table instructor ( ID char(5), name varchar(20) not null, dept_name varchar(20), salary numeric(8,2), primary key (ID), foreign key (dept_name) references department)primary key
10、 declaration on an attribute automatically ensures not nullAnd a Few More Relation Definitionscreate table student ( ID varchar(5), name varchar(20) not null, dept_name varchar(20), tot_cred numeric(3,0), primary key (ID), foreign key (dept_name) references department) );create table takes ( ID varc
11、har(5), course_id varchar(8), sec_id varchar(8), semester varchar(6), year numeric(4,0), grade varchar(2), primary key (ID, course_id, sec_id, semester, year), foreign key (ID) references student, foreign key (course_id, sec_id, semester, year) references section );Note: sec_id can be dropped from p
12、rimary key above, to ensure a student cannot be registered for two sections of the same course in the same semesterAnd more stillcreate table course ( course_id varchar(8) primary key, title varchar(50), dept_name varchar(20), credits numeric(2,0), foreign key (dept_name) references department) );Pr
13、imary key declaration can be combined with attribute declaration as shown aboveDrop and Alter Table Constructsdrop table studentDeletes the table and its contentsdelete from studentDeletes all contents of table, but retains tablealter table alter table r add A D where A is the name of the attribute
14、to be added to relation r and D is the domain of A.All tuples in the relation are assigned null as the value for the new attribute. alter table r drop A where A is the name of an attribute of relation rDropping of attributes not supported by many databasesBasic Query Structure The SQL data-manipulat
15、ion language (DML) provides the ability to query information, and insert, delete and update tuplesA typical SQL query has the form:select A1, A2, ., Anfrom r1, r2, ., rmwhere PAi represents an attributeRi represents a relationP is a predicate.The result of an SQL query is a relation.The select Claus
16、eThe 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 instructors:select namefrom instructorNOTE: SQL names are case insensitive (i.e., you may use upper- or lower-case letters.) E.g. Nam
17、e NAME nameSome people use upper case wherever we use bold font.The select Clause (Cont.)SQL allows duplicates in relations as well as in query results.To force the elimination of duplicates, insert the keyword distinct after select.Find the names of all departments with instructor, and remove dupli
18、catesselect distinct dept_namefrom instructorThe keyword all specifies that duplicates not be removed.select all dept_namefrom instructorThe select Clause (Cont.)An asterisk in the select clause denotes “all attributes”select *from instructorThe select clause can contain arithmetic expressions invol
19、ving the operation, +, , , and /, and operating on constants or attributes of tuples.The query: select ID, name, salary/12 from instructorwould return a relation that is the same as the instructor relation, except that the value of the attribute salary is divided by 12.The where ClauseThe where clau
20、se specifies conditions that the result must satisfyCorresponds to the selection predicate of the relational algebra. To find all instructors in Comp. Sci. dept with salary 80000select namefrom instructorwhere dept_name = Comp. Sci. and salary 80000Comparison results can be combined using the logica
21、l connectives and, or, and not. Comparisons can be applied to results of arithmetic expressions.The from ClauseThe from clause lists the relations involved in the queryCorresponds to the Cartesian product operation of the relational algebra.Find the Cartesian product instructor X teachesselect from
22、instructor, teachesgenerates every possible instructor teaches pair, with all attributes from both relationsCartesian product not very useful directly, but useful combined with where-clause condition (selection operation in relational algebra)Cartesian Product: instructor X teachesinstructorteachesJ
23、oinsFor all instructors who have taught some course, find their names and the course ID of the courses they taught. select name, course_id from instructor, teaches where instructor.ID = teaches.IDFind the course ID, semester, year and title of each course offered by the Comp. Sci. departmentselect s
24、ection.course_id, semester, year, title from section, course where section.course_id = course.course_id and dept_name = Comp. Sci. Try Writing Some Queries in SQLSuggest queries to be written.Natural JoinNatural join matches tuples with the same values for all common attributes, and retains only one
25、 copy of each common columnselect *from instructor natural join teaches;Natural Join ExampleList the names of instructors along with the course ID of the courses that they taught. select name, course_idfrom instructor, teacheswhere instructor.ID = teaches.ID;select name, course_idfrom instructor nat
26、ural join teaches;Natural Join (Cont.)Danger in natural join: beware of unrelated attributes with same name which get equated incorrectlyList the names of instructors along with the the titles of courses that they teach Incorrect version (makes course.dept_name = instructor.dept_name)select name, ti
27、tlefrom instructor natural join teaches natural join course;Correct versionselect name, titlefrom instructor natural join teaches, coursewhere teaches.course_id = course.course_id;Another correct versionselect name, titlefrom (instructor natural join teaches) join course using(course_id);The Rename
28、OperationThe SQL allows renaming relations and attributes using the as clause:old-name as new-nameE.g. select ID, name, salary/12 as monthly_salaryfrom instructorFind the names of all instructors who have a higher salary than some instructor in Comp. Sci.select distinct T. namefrom instructor as T,
29、instructor as Swhere T.salary S.salary and S.dept_name = Comp. Sci.Keyword as is optional and may be omitted instructor as T instructor TKeyword as must be omitted in OracleString OperationsSQL includes a string-matching operator for comparisons on character strings. The operator “like” uses pattern
30、s that are described using two special characters:percent (%). The % character matches any substring.underscore (_). The _ character matches any character.Find the names of all instructors whose name includes the substring “dar”. select namefrom instructorwhere name like %dar% Match the string “100
31、%”like 100 % escape String Operations (Cont.)Patters are case sensitive. Pattern matching examples:Intro% matches any string beginning with “Intro”.%Comp% matches any string containing “Comp” as a substring._ _ _ matches any string of exactly three characters._ _ _ % matches any string of at least t
32、hree characters.SQL 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 of all instructors select distinct namefr
33、om instructororder by nameWe may specify desc for descending order or asc for ascending order, for each attribute; ascending order is the default.Example: order by name descCan sort on multiple attributesExample: order by dept_name, nameWhere Clause PredicatesSQL includes a between comparison operat
34、orExample: Find the names of all instructors with salary between $90,000 and $100,000 (that is, $90,000 and $100,000)select name from instructor where salary between 90000 and 100000Tuple comparisonselect name, course_idfrom instructor, teacheswhere (instructor.ID, dept_name) = (teaches.ID, Biology)
35、;DuplicatesIn relations with duplicates, SQL can define how many copies of tuples appear in the result.Multiset versions of some of the relational algebra operators given multiset relations r1 and r2:1. (r1): If there are c1 copies of tuple t1 in r1, and t1 satisfies selections , then there are c1 c
36、opies 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 are 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
37、r1 x r2Duplicates (Cont.)Example: Suppose multiset relations r1 (A, B) and r2 (C) are as follows: r1 = (1, a) (2,a) r2 = (2), (3), (3)Then 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)SQL duplicate semantics: select A1, A2, ., Anfrom r1, r2, ., rmwhere Pi
38、s equivalent to the multiset version of the expression:Set OperationsFind courses that ran in Fall 2009 or in Spring 2010 Find courses that ran in Fall 2009 but not in Spring 2010(select course_id from section where sem = Fall and year = 2009) union(select course_id from section where sem = Spring a
39、nd year = 2010) Find courses that ran in Fall 2009 and in Spring 2010(select course_id from section where sem = Fall and year = 2009) intersect(select course_id from section where sem = Spring and year = 2010)(select course_id from section where sem = Fall and year = 2009) except(select course_id fr
40、om section where sem = Spring and year = 2010)Set OperationsSet operations union, intersect, and except Each of the above operations automatically eliminates duplicatesTo retain all duplicates use the corresponding multiset versions union all, intersect all and except all.Suppose a tuple occurs m ti
41、mes 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 sNull 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 no
42、t exist.The result of any arithmetic expression involving null is nullExample: 5 + null returns nullThe predicate is null can be used to check for null values.Example: Find all instructors whose salary is null.select namefrom instructorwhere salary is nullNull Values and Three Valued LogicAny compar
43、ison 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, (unknown and unknown) = u
44、nknownNOT: (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 unknownAggregate FunctionsThese functions operate on the multiset of values of a column of a relation, and return a valueavg:
45、average valuemin: minimum valuemax: maximum valuesum: sum of valuescount: number of valuesAggregate Functions (Cont.)Find the average salary of instructors in the Computer Science department select avg (salary)from instructorwhere dept_name= Comp. Sci.;Find the total number of instructors who teach
46、a course in the Spring 2010 semesterselect count (distinct ID)from teacheswhere semester = Spring and year = 2010Find the number of tuples in the course relationselect count (*)from course; Aggregate Functions Group ByFind the average salary of instructors in each departmentselect dept_name, avg (sa
47、lary)from instructorgroup by dept_name;Note: departments with no instructor will not appear in resultAggregation (Cont.)Attributes in select clause outside of aggregate functions must appear in group by list/* erroneous query */select dept_name, ID, avg (salary)from instructorgroup by dept_name;Aggr
48、egate Functions Having ClauseFind the names and average salaries of all departments whose average salary is greater than 42000 Note: predicates in the having clause are applied after the formation of groups whereas predicates in the where clause are applied before forming groupsselect dept_name, avg
49、 (salary)from instructorgroup by dept_namehaving avg (salary) 42000;Null Values and AggregatesTotal all salariesselect sum (salary )from instructorAbove statement ignores null amountsResult is null if there is no non-null amountAll aggregate operations except count(*) ignore tuples with null values
50、on the aggregated attributesWhat if collection has only null values?count returns 0all other aggregates return nullNested SubqueriesSQL provides a mechanism for the nesting of subqueries.A subquery is a select-from-where expression that is nested within another query.A common use of subqueries is to
51、 perform tests for set membership, set comparisons, and set cardinality.Example QueryFind courses offered in Fall 2009 and in Spring 2010 Find courses offered in Fall 2009 but not in Spring 2010select distinct course_idfrom sectionwhere semester = Fall and year= 2009 and course_id in (select course_
52、id from section where semester = Spring and year= 2010);select distinct course_idfrom sectionwhere semester = Fall and year= 2009 and course_id not in (select course_id from section where semester = Spring and year= 2010);Example QueryFind the total number of (distinct) studentswho have taken course
53、 sections taught by the instructor with ID 10101 Note: Above query can be written in a much simpler manner. The formulation above is simply to illustrate SQL features.select count (distinct ID)from takeswhere (course_id, sec_id, semester, year) in (select course_id, sec_id, semester, year from teach
54、es where teaches.ID= 10101);Set ComparisonFind names of instructors with salary greater than that of some (at least one) instructor in the Biology department. Same query using some clauseselect namefrom instructorwhere salary some (select salary from instructor where dept_name = Biology);select dist
55、inct T.namefrom instructor as T, instructor as Swhere T.salary S.salary and S.dept_name = Biology;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 salary from instructor
56、 where dept_name = Biology);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 42000;Note that we do not need to use the having clauseAnother way to write above query select dept_name, avg_salaryfrom (select dept_name, avg (salary) from ins
57、tructor group by dept_name) as dept_avg (dept_name, avg_salary) where avg_salary 42000; Subqueries in the From Clause (Cont.)And yet another way to write it: lateral clause select name, salary, avg_salaryfrom instructor I1, lateral (select avg(salary) as avg_salary from instructor I2 where I2.dept_n
58、ame= I1.dept_name);Lateral clause permits later part of the from clause (after the lateral keyword) to access correlation variables from the earlier part.Note: lateral is part of the SQL standard, but is not supported on many database systems; some databases such as SQL Server offer alternative synt
59、axWith 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 departments with the maximum budget with max_budget (value) as (select max(budget) from department) select budget from department, max_bu
60、dget where department.budget = max_budget.value;Complex Queries using With ClauseWith clause is very useful for writing complex queriesSupported by most database systems, with minor syntax variationsFind all departments where the total salary is greater than the average of the total salary at all de
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
- 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 南昌航空大學《旋律寫作基礎(1)》2023-2024學年第二學期期末試卷
- 上海市華二附中2025年高三年級下學期十月份月考英語試題含解析
- 上海海洋大學《普通動物學》2023-2024學年第二學期期末試卷
- 江蘇省南通如皋市2025屆高三二模(4月)英語試題含解析
- 濮陽石油化工職業技術學院《生物醫用材料概論》2023-2024學年第二學期期末試卷
- 麗水學院《ACCASBR戰略商務報告》2023-2024學年第二學期期末試卷
- 共享員工協議書合同書協議書
- 二零二五集體林地承包租賃合同
- 抵押借款合同范例范例
- 二零二五版餐飲出租簡單合同范例
- 2《在馬克思墓前的講話》公開課一等獎創新教學設計(任務式)統編版高中語文必修下冊
- 鐵路物資應急管理制度
- 育兒真經知到課后答案智慧樹章節測試答案2025年春浙江中醫藥大學
- 創三甲病區護理亮點匯報
- 建筑行業勞動保護制度與措施
- (高清版)DB12 445-2011 天津市城市道路交通指引標志設置規范
- 一年級數學口算題1000題
- 初級車工(五級)技能認定理論考試題(附答案)
- 變電檢修工試題庫含參考答案
- 河南省氣象部門招聘真題2024
- 2025年水工維護(高級工)職業技能理論考試題庫(含答案)
評論
0/150
提交評論