Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Database Principles. 2 Chapter3-1 Introduction to SQL uSelect-From-Where Statements uSubqueries uGrouping and Aggregation.

Similar presentations


Presentation on theme: "1 Database Principles. 2 Chapter3-1 Introduction to SQL uSelect-From-Where Statements uSubqueries uGrouping and Aggregation."— Presentation transcript:

1 1 Database Principles

2 2 Chapter3-1 Introduction to SQL uSelect-From-Where Statements uSubqueries uGrouping and Aggregation

3 3 Why SQL? uSQL is a very-high-level language. wSay “what to do” rather than “how to do it.” wAvoid a lot of data-manipulation details needed in procedural languages like C++ or Java. uDatabase management system figures out “best” way to execute query. wCalled “query optimization.”

4 4 Select-From-Where Statements SELECT desired attributes FROM one or more tables WHERE condition about tuples of the tables; SELECT title, length FROM movies WHERE year =1994; For example:

5 5 Our Running Example All our SQL queries will be based on the following database schema: uMovie(title, year, length, inColor, studioName, producerC#) u StarsIn(movieTitle, movieYear, starName) u MovieStar(name, address, gender, birthdate) u MovieExec(name, address, cert#, netWorth) u Studio(name, address, preaC#)

6 6 Example uUsing Movie, what movies were produced by Disney Studios in 1990? SELECT title, length FROM Movie WHERE studioName = ‘Disney’ AND year = 1990; Notice SQL uses single-quotes for strings. SQL is case-insensitive, except inside strings.

7 7 Result of Query titlelength Pretty Women … 119

8 8 Meaning of Single-Relation Query uBegin with the relation in the FROM clause. uApply the selection indicated by the WHERE clause. uApply the extended projection indicated by the SELECT clause.

9 9 Operational Semantics uTo implement this algorithm think of a tuple variable ranging over each tuple of the relation mentioned in FROM. uCheck if the “current” tuple satisfies the WHERE clause. uIf so, compute the attributes or expressions of the SELECT clause using the components of this tuple.

10 10 * In SELECT clauses uWhen there is one relation in the FROM clause, * in the SELECT clause stands for “all attributes of this relation.” uExample using Movie: SELECT * FROM Movie WHERE studioName = ‘Disney’ AND year = 1990;

11 11 Result of Query: titleyearlengthinColorstudioNameprocucerC# Pretty Women … 1990119trueDisney999

12 12 Renaming Attributes uIf you want the result to have different attribute names, use “AS ” to rename an attribute. uExample based on Movie: SELECT title As name, length As duration FROM Movie WHERE studioName = ‘Disney’ AND year = 1990;

13 13 Result of Query: nameDuration Pretty Women … 119

14 14 Expressions in SELECT Clauses uAny expression that makes sense can appear as an element of a SELECT clause. uExample: from Movie: SELECT title As name, length*0.016667 As lengthInHours FROM Movie;

15 15 Constant Expressions uFrom Movie : SELECT title, length*0.016667 AS length, ‘hrs.’ AS inHours FROM Movie WHERE studioName = ‘Disney’ AND year = 1990;

16 16 Result of Query titlelengthinHours Pretty Women … 1.98334hrs.

17 17 Complex Conditions in WHERE Clause uFrom Movie, find all the movies made after 1970 that are in black-and-white: SELECT title FROM Movie WHERE year > 1970 AND NOT inColor;

18 18 Patterns uWHERE clauses can have conditions in which a string is compared with a pattern, to see if it matches. uGeneral form: w LIKE or w NOT LIKE uPattern is a quoted string with % (any string) or _ (any character)

19 19 Example uFrom Movie find all the movies have the title as “Star something”, and we remember that something has four letters.: SELECT title FROM Movie WHERE title LIKE ‘Star _ _ _ _’; A ‘_’ just represent half Chinese characters

20 20 Escape characters in LIKE expressions uIf the pattern we wish to use in a LIKE expression involves the characters % or _. We can follow the pattern by the keyword ESCAPE and choose a escape character. uFor example: a LIKE ‘x%x%’ ESCAPE ‘x’

21 21 Comparing dates and times uA date is represented by the keyword DATE followed by a quoted string of a special form. For example, DATE ‘1948-05-14’ follows the required form. uA time is represented similarly by the keyword TIME and a quoted string. For instance, TIME ‘ 15:00:02.5’ uWe can compare dates or times using the same comparison operators we use for numbers or strings.

22 22 Ordering the output uTo get output in sorted order, we add to the select-from-where statement a clause: ORDER BY uThe order is by default ascending (ASC), but we can get the output highest-first by appending the keyword DESC.

23 23 Example uTo get the movies listed by length, shortest first, and among movies of equal length, alphabetically, we can say: SELECT * FROM Movie WHERE studioName = ‘Disney’ AND year = 1990 ORDER BY length, title;

24 24 练习  图书 ( 书号, 书名, 作者, 出版社, 单价)  查询 “ 数据库 ” 一书的书号和单价  查询所有图书的名称和单价,并按单价从大到小排序  查询单价在 20 至 50 元之间的图书信息  查询北京某出版社出版的图书信息  查询作者是张一,王二,刘三的书的信息  查询所有图书的书号,书名和半价信息  查询缺少出版社信息的图书的书号和书名

25 25 Multirelation Queries uInteresting queries often combine data from more than one relation. uWe can address several relations in one query by listing them all in the FROM clause. uDistinguish attributes of the same name by “. ”

26 26 Example uUsing relations Movie and MovieExec, find the name of the producer of Star War. SELECT name FROM Movie, MovieExec WHERE title = ‘Star War’ AND producerC# = cert#;

27 27 Formal Semantics uAlmost the same as for single-relation queries: 1.Start with the product of all the relations in the FROM clause. 2.Apply the selection condition from the WHERE clause. 3.Project onto the list of attributes and expressions in the SELECT clause.

28 28 Operational Semantics uImagine one tuple-variable for each relation in the FROM clause. wThese tuple-variables visit each combination of tuples, one from each relation. uIf the tuple-variables are pointing to tuples that satisfy the WHERE clause, send these tuples to the SELECT clause.

29 29 Explicit Tuple-Variables uSometimes, a query needs to use two copies of the same relation. uDistinguish copies by following the relation name by the name of a tuple-variable, in the FROM clause. uIt’s always an option to rename relations this way, even when not essential.

30 30 Example uFrom MovieStar, find all pairs of stars who share an address. SELECT Star1.name, Star2.name FROM MovieStar AS Star1, MovieStar AS Star2 WHERE Star1.address = Star2.address AND Star1.name <> Star2.name;

31 31 练习 读者 ( 读者编号,姓名,电话 ) 图书 ( 书号, 书名, 作者, 出版社, 单价) 借阅 ( 书号,读者编号,借阅日期 )  查询借阅过书号为 ‘J0004’ 图书的读者姓名  查询王明所借阅的所有图书的书名和借阅日期

32 32 练习 u 图书馆管理数据库 w 读者 ( 读者编号, 姓名, 单位 ) w 图书 ( 书号, 书名, 作者, 出版社, 单价, 类型 ) w 借阅记录 ( 读者编号, 书号, 借阅日期, 应还日期 ) w 还书记录 ( 读者编号, 书号, 归还日期 ) u 用关系代数描述以下查询要求 w 查询 “ 人民邮电出版社 ” 出版的所有图书的相关信息 w 查询单价在 15 元以上的书名和作者 w 查询 8 号读者 2003 年 3 月 10 日所借图书的相关信息 w 查询超期归还图书的读者姓名和单位 w 查询借阅过《天龙八部》的读者的信息 w 查询借阅过 “ 金庸 ” 所有著作的读者的姓名 w 查询没有借阅过任何图书的读者的姓名

33 33 Subqueries uA parenthesized SELECT-FROM-WHERE statement (subquery ) can be used as a value in a number of places, including FROM and WHERE clauses. uExample: in place of a relation in the FROM clause, we can place another query, and then query its result. wBetter use a tuple-variable to name tuples of the result.

34 34 Subqueries That Return One Tuple uIf a subquery is guaranteed to produce one tuple, then the subquery can be used as a value. wUsually, the tuple has one component. wA run-time error occurs if there is no tuple or more than one tuple.

35 35 Example uFrom Movie, MovieExec, find the name of the producer of Star War. uTwo queries would surely work: 1.Find the certificate number for the producer of Star War. 2.Find the name of the person with this certificate.

36 36 Query + Subquery Solution SELECT name FROM MovieExec WHERE cert# = (SELECT producerC# FROM Movie WHERE title = ‘Star Wars’);

37 37 The IN Operator u IN is true if and only if the tuple is a member of the relation. w NOT IN means the opposite. uIN-expressions can appear in WHERE clauses. uThe is often a subquery.

38 38 Example uFrom Movie, MovieExec and StarsIn, find all the producers of movies in which Harrison Ford stars. SELECT name FROM MovieExec WHERE cert# IN (SELECT producerC# FROM Movie WHERE (title, year) IN (SELECT movieTitle, movieYear FROM StarsIn WHERE starName = ‘Harrison Ford’)); The nested query can be written as a single select-from-where expression?

39 39 The Exists Operator uEXISTS( ) is true if and only if the is not empty. uExample: From Beers(name, manf), find those beers that are the unique beer by their manufacturer.

40 40 Example Query with EXISTS SELECT name FROM Beers b1 WHERE NOT EXISTS( SELECT * FROM Beers WHERE manf = b1.manf ANDname <> b1.name);

41 41 The Operator ANY ux = ANY( ) is a boolean condition true if x equals at least one tuple in the relation. uSimilarly, = can be replaced by any of the comparison operators. uExample: x >= ANY( ) means x is not the smallest tuple in the relation. wNote tuples must have one component only.

42 42 The Operator ALL uSimilarly, x <> ALL( ) is true if and only if for every tuple t in the relation, x is not equal to t. wThat is, x is not a member of the relation. uThe <> can be replaced by any comparison operator. uExample: x >= ALL( ) means there is no tuple larger than x in the relation.

43 43 Example uFrom Movie, find the titles that have been used for two or more movies. SELECT title FROM Movie As old WHERE year < ANY( SELECT year FROM Movie WHERE title = old.title);

44 44 Union, Intersection, and Difference uUnion, intersection, and difference of relations are expressed by the following forms, each involving subqueries: w( subquery ) UNION ( subquery ) w( subquery ) INTERSECT ( subquery ) w( subquery ) EXCEPT ( subquery )

45 45 Example uUsing MovieStar and MovieExec, suppose we wanted the names and addresses of all female movie stars who are also movie executives with a net worth over $10,000,000. (SELECT name, address FROM MovieStar WHERE gender = ‘F’) INTERSECT (SELECT name, address FROM MovieExec WHERE netWorth > 10000000);

46 46 Controlling Duplicate Elimination uForce the result to be a set by SELECT DISTINCT...

47 47 Example: DISTINCT uFrom Movie, MovieExec, StarIn, find all the producers of movies in which Harrison Ford stars : SELECT DISTINCT name FROM Movie, MovieExec, StarsIn WHERE cert# = producerC# AND tile = movieTitle AND year = moiveYear AND starName = ‘Harrison Ford’; uNotice that without DISTINCT, each name would be listed many times.

48 48 Aggregations uSUM, AVG, COUNT, MIN, and MAX can be applied to a column in a SELECT clause to produce that aggregation on the column. uAlso, COUNT(*) counts the number of tuples.

49 49 Example: Aggregation uFrom MovieExec, find the average net worth of all movie executives: SELECT AVG(netWorth) FROM MovieExec;

50 50 Eliminating Duplicates in an Aggregation uUse DISTINCT inside an aggregation. uExample: find the number of different name in MovieExec: SELECT COUNT(DISTINCT name) FROM MovieExec;

51 51 NULL’s Ignored in Aggregation uNULL never contributes to a sum, average, or count, and can never be the minimum or maximum of a column. uBut if there are no non-NULL values in a column, then the result of the aggregation is NULL.

52 52 Example: Effect of NULL’s SELECT count(*) FROM MovieExec; SELECT count(name) FROM MovieExec; The number of tuples in MovieExec. The number of tuples that name is not NULL in MovieExec.

53 53 Grouping uWe may follow a SELECT-FROM- WHERE expression by GROUP BY and a list of attributes. uThe relation that results from the SELECT- FROM-WHERE is grouped according to the values of all those attributes, and any aggregation is applied only within each group.

54 54 Example: Grouping uFrom Movie, the sum of the lengths of all movies for each studio is expressed by: SELECT studioName, SUM(length) FROM Movie GROUP BY studioName;

55 55 Example: Grouping uFrom Movie and MovieExec, find each producer’s total length of film produced. SELECT name, SUM(length) FROM MovieExec, Movie WHERE producerC# = cert# GROUP BY name;

56 56 Restriction on SELECT Lists With Aggregation uIf any aggregation is used, then each element of the SELECT list must be either: 1.Aggregated, or 2.An attribute on the GROUP BY list.

57 57 Illegal Query Example uYou might think you could find the movie that is the longest in length: SELECT title, MAX(length) FROM Movie uBut this query is illegal in SQL.

58 58 HAVING Clauses uHAVING may follow a GROUP BY clause. uIf so, the condition applies to each group, and groups not satisfying the condition are eliminated.

59 59 Example: HAVING uFrom Movie and MovieExec, find the total film length for only those producers who made at least one film prior to 1930. SELECT name, SUM(length) FROM MovieExec, Movie WHERE producerC# = cert# GROUP BY name HAVING MIN(year) < 1930;

60 60 Requirements on HAVING Conditions uThese conditions may refer to any relation or tuple-variable in the FROM clause. uThey may refer to attributes of those relations, as long as the attribute makes sense within a group; i.e., it is either: 1.A grouping attribute, or 2.Aggregated.

61 61 练习 读者 ( 读者编号,姓名,电话 ) 图书 ( 书号, 书名, 作者, 出版社, 单价) 借阅 ( 书号,读者编号,借阅日期 )  查询借阅过图书的读者姓名  查询图书总数  查询每天的图书借阅量(图书借阅记录数)


Download ppt "1 Database Principles. 2 Chapter3-1 Introduction to SQL uSelect-From-Where Statements uSubqueries uGrouping and Aggregation."

Similar presentations


Ads by Google