1 / 50

SQL: Structured Query Language (‘Sequel’)

SQL: Structured Query Language (‘Sequel’). Chapter 5. SQL. Query Language Constraints Triggers. SQL Overview. Data Manipulation Language (DML) Queries, insert, delete, modify Data Definition Language (DDL) Creation, deletion, modification tables and views

hasana
Télécharger la présentation

SQL: Structured Query Language (‘Sequel’)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. SQL: Structured Query Language(‘Sequel’) Chapter 5

  2. SQL Query Language Constraints Triggers

  3. SQL Overview • Data Manipulation Language (DML) • Queries, insert, delete, modify • Data Definition Language (DDL) • Creation, deletion, modification tables and views • Creating and deleting index (commercial DB) • Triggers and Advanced Integrity Constraints • Embedded and Dynamic SQL • Calling SQL code using host language (C, etc. ) (Chapter 6) • Client-Server Execution and Remote Database Access • (chapter 7) • Transaction Management (chapter 21) • Security • Advanced features • OO, recursive queries, data mining, spatial data, text and XML

  4. Running Example R1 • Instances of the Sailors and Reserves relations in our examples. S1 S2

  5. Basic SQL Query SELECT [DISTINCT] target-list FROMrelation-list WHERE qualification • relation-list A list of relation names • target-list A list of attributes of relations in relation-list • qualification • Comparisons (Attr op const or Attr1 op Attr2, where op is one of ) combined using AND, OR and NOT. • DISTINCT is optional keyword indicating that answer should not contain duplicates. Default is that duplicates are not eliminated!

  6. Example Query SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid=R.sid AND R.bid=103

  7. Comparisons in Oracle

  8. Example Query SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid=R.sid AND R.bid=103

  9. Conceptual Evaluation Strategy • Semantics of SQL query defined in terms of following conceptual evaluation strategy: • Compute cross-product of relation-list. • Discard resulting tuples if they fail qualifications. • Delete attributes that are not in target-list. • If DISTINCT is specified, eliminate duplicate rows. • Probably the least efficient way! • Optimizer will find more efficient strategies to compute the same answers.

  10. R S SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid=R.sid AND R.bid=103

  11. A Note on Range Variables • Needed only if same relation appears twice in FROM clause. • The previous query can also be written as: SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid=R.sid AND bid=103 OR SELECT sname FROM Sailors, Reserves WHERE Sailors.sid=Reserves.sid AND bid=103 It is good style, however, to use range variables always!

  12. Find sailors who’ve reserved at least one boat SELECT S.sid FROM Sailors S, Reserves R WHERE S.sid=R.sid • Questions: • What is the exact output of this query ? • Would adding DISTINCT to this query make a difference? • What is the effect of replacing S.sid by S.sname in SELECT clause? • Would adding DISTINCT to this variant of the query make a difference?

  13. Expressions and Strings SELECT S.age, age1=S.age-5, 2*S.age AS age2 FROM Sailors S WHERE S.sname LIKE‘B_%B’ • ASand = are two ways to name fields in result. • LIKE is used for string matching. `_’ stands for any one character and `%’ stands for 0 or more arbitrary characters. • Find triples (of ages of sailors and two fields defined by expressions) for sailors whose names begin and end with B and contain at least three characters.

  14. Find sid’s of sailors who’ve reserved a redor a green boat SELECT S.sid FROM Sailors S, Reserves R, Boats B WHERE S.sid=R.sid AND R.bid=B.bid AND (B.color=‘red’ OR B.color=‘green’) • UNIONcompute union of any two union-compatible sets of tuples SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ UNION SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘green’

  15. Find sid’s of sailors who’ve reserved a redor a green boat SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND (B.color=‘red’ OR B.color=‘green’) • If we replace ORby ANDin the first version, what do we get? SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ UNION SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘green’

  16. Key field! Find sid’s of sailors who’ve reserved a red and a green boat • INTERSECT: Can be used to compute the intersection of any two union-compatible sets of tuples. • What happens if change S.sid as S.sname??? • SQL/92 standard, but some systems don’t support INTERSECT ? SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ INTERSECT SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘green’

  17. Find sid’s of sailors who’ve reserved a red and a green boat Key field! SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ INTERSECT SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘green’ • What would query look like without INTERSECT? SELECT S.sid FROM Sailors S, Boats B1, Reserves R1, Boats B2, Reserves R2 WHERE S.sid=R1.sid AND R1.bid=B1.bid AND S.sid=R2.sid AND R2.bid=B2.bid AND (B1.color=‘red’ AND B2.color=‘green’)

  18. Find sid’s of sailors who’ve reserved a red and not a green boat SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ EXCEPT SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘green’ • What if we want to compute the DIFFERENCE, called EXCEPT in SQL? • SQL/92 standard, but some systems don’t support EXCEPT. SELECT S.sid FROM Sailors S, Boats B1, Reserves R1, Boats B2, Reserves R2 WHERE S.sid=R1.sid AND R1.bid=B1.bid AND S.sid=R2.sid AND R2.bid=B2.bid AND (B1.color='red' AND NOT(B2.color = 'green'))

  19. About duplication • Default: Eliminate duplicate • Unless Use # of copies of a row in result UNION ALL (m+n) INTERSECT ALL min(m,n) EXCEPT ALL m-n

  20. Nested Queries Find names of sailors who’ve reserved boat #103: SELECT S.sname FROM Sailors S WHERE S.sid IN (SELECT R.sid FROM Reserves R WHERE R.bid=103) • WHERE, FROM, HAVING clauses can itself contain an SQL query!  powerful feature of SQL. • nested loops evaluation: For each Sailors tuple, check the qualification by re-computing the subquery.

  21. Nested Queries Evaluation Find names of sailors who’ve reserved boat #103: SELECT S.sname FROM Sailors S WHERE S.sid IN (SELECT R.sid FROM Reserves R WHERE R.bid=103) • Nested loops evaluation: • For each Sailors tuple, check qualification by re-computing subquery.

  22. Nested Queries Find names of sailors who’ve reserved boat #103: SELECT S.sname FROM Sailors S WHERE S.sid IN (SELECT R.sid FROM Reserves R WHERE R.bid=103) • Change query to find sailors who’ve not reserved #103: SELECT S.sname FROM Sailors S WHERE S.sid NOT IN (SELECT R.sid FROM Reserves R WHERE R.bid=103)

  23. Nested Queries Find names of sailors who’ve reserved boat #103: SELECT S.sname FROM Sailors S WHERE S.sid IN (SELECT R.sid FROM Reserves R WHERE R.bid=103) • Could this query be rewritten without nesting?

  24. Nested Queries with Correlation Find names of sailors who’ve reserved boat #103: SELECT S.sname FROMSailors S WHERE EXISTS (SELECT * FROM Reserves R WHERE R.bid=103 ANDS.sid=R.sid) • EXISTSis another set comparison operator, like IN.

  25. Nested Queries with Correlation Find names of sailors who’ve reserved boat #103: SELECT S.sname FROMSailors S WHERE EXISTS (SELECT * FROM Reserves R WHERE R.bid=103 ANDS.sid=R.sid) • Why, in general, this subquery must be re-computed for each Sailors tuple ?

  26. Nested Queries with Correlation Find names of sailors who’ve reserved boat #103: SELECT S.sname FROMSailors S WHERE EXISTS (SELECT * FROM Reserves R WHERE R.bid=103 ANDS.sid=R.sid) • Question: Finds sailors with at most one reservation for boat #103. • UNIQUEis used instead of EXISTS • * is replaced by R.bid. (Why?)

  27. More on Set-Comparison Operators • opANY, opALL, op IN • Op = { } • e.g. Find sailors whose rating is greater than that of some sailor called Horatio: • IN is equal to =ANY • NOT IN is equal to <>ANY SELECT * FROM Sailors S WHERE S.rating > ANY(SELECT S2.rating FROM Sailors S2 WHERE S2.sname=‘Horatio’)

  28. Rewriting INTERSECT Queries Using IN Find sid’s of sailors who’ve reserved both a red and a green boat: SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ AND S.sid IN (SELECT S2.sid FROM Sailors S2, Boats B2, Reserves R2 WHERE S2.sid=R2.sid AND R2.bid=B2.bid AND B2.color=‘green’)

  29. Rewriting INTERSECT Queries Using IN Find sid’s of sailors who’ve reserved both a red and a green boat: SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ AND S.sid IN (SELECT S2.sid FROM Sailors S2, Boats B2, Reserves R2 WHERE S2.sid=R2.sid AND R2.bid=B2.bid AND B2.color=‘green’) • Similarly, EXCEPT queries re-written using NOT IN. To find names (not sid’s) of Sailors who’ve reserved both red and green boats

  30. Division in SQL Find sailors who’ve reserved all boats. SELECT S.sname FROM Sailors S WHERE NOT EXISTS ((SELECT B.bid FROM Boats B) EXCEPT (SELECT R.bid FROM Reserves R WHERE R.sid=S.sid))

  31. (1) SELECT S.sname FROM Sailors S WHERE NOT EXISTS ((SELECT B.bid FROM Boats B) EXCEPT (SELECT R.bid FROM Reserves R WHERE R.sid=S.sid)) Division in SQL Find sailors who’ve reserved all boats. • Let’s do it without EXCEPT: (2) SELECT S.sname FROM Sailors S WHERE NOT EXISTS (SELECT B.bid FROM Boats B WHERE NOT EXISTS (SELECT R.bid FROM Reserves R WHERE R.bid=B.bid AND R.sid=S.sid)) Sailors S such that ... there is no boat B without ... a Reserves tuple showing S reserved B

  32. COUNT (*) COUNT ( [DISTINCT] A) SUM ( [DISTINCT] A) AVG ( [DISTINCT] A) MAX (A) MIN (A) Aggregate Operators • Significant extension of relational algebra. SELECT COUNT (*) FROM Sailors S Why no Distinct? SELECT AVG (S.age) FROM Sailors S WHERE S.rating=10 SELECT COUNT (DISTINCT S.rating) FROM Sailors S WHERE S.sname=‘Bob’

  33. Aggregate Operators • Significant extension of relational algebra. SELECT S.sname FROM Sailors S WHERE S.rating= (SELECT MAX(S2.rating) FROM Sailors S2) SELECT AVG ( DISTINCT S.age) FROM Sailors S WHERE S.rating=10

  34. Find name and age of the oldest sailor(s) SELECT S.sname, MAX (S.age) FROM Sailors S • Is this first query legal? • No! Why not ? SELECT S.sname, S.age FROM Sailors S WHERE S.age = (SELECT MAX (S2.age) FROM Sailors S2) Is this second query legal?

  35. Motivation for Grouping • So far, aggregate operators to all (qualifying) tuples. • Question? apply aggregate to each group of tuples. • Consider:Find the age of the youngest sailor for each rating level. • Suppose rating values {1,2,…,10}, 10 queries: • Question? • we don’t know how many rating levels exist ? • what the rating values for these levels are! SELECT MIN (S.age) FROM Sailors S WHERE S.rating = i For i = 1, 2, ... , 10:

  36. Queries With GROUP BY and HAVING SELECT [DISTINCT] target-list FROMrelation-list WHERE qualification GROUP BYgrouping-list HAVING group-qualification • Thetarget-listcontains :(i) attribute names(ii) aggregate-op (column-name) (e.g., MIN (S.age)). • A group is a set of tuples that have the same value for all attributes in grouping-list. • REQUIREMENT: - The target-list (i)  grouping-list. - Why? each answer tuple of a group must have a single value.

  37. Find age of the youngest sailor with age 18, for each rating with at least 2 such sailors SELECT S.rating, MIN (S.age) AS min-age FROM Sailors S WHERE S.age >= 18 GROUP BY S.rating HAVINGCOUNT (*) > 1

  38. GroupBy --- Conceptual Evaluation • Compute the cross-product of relation-list • Discard tuples that fail qualification • Delete `unnecessary’ fields • Partition the remaining tuples into groups by the value of attributes in grouping-list. (GroupBy) • Eliminate groups using the group-qualification (Having) • We will have a single value per group! That is, one answer tuple is generated per qualifying group.

  39. Find age of the youngest sailor with age 18, for each rating with at least 2 such sailors Sailors instance: SELECT S.rating, MIN (S.age) AS min-age FROM Sailors S WHERE S.age >= 18 GROUP BY S.rating HAVINGCOUNT (*) > 1 Answer relation: Q: Why not rating =9 ?

  40. Find age of the youngest sailor with age 18, for each rating with at least 2 such sailors.

  41. Find age of the youngest sailor with age 18, for each rating with at least 2 such sailors and with every sailor under 60. Find age of the youngest sailor with age 18, for each rating with at least 2 such sailors SELECT S.rating, MIN (S.age) AS min-age FROM Sailors S WHERE S.age >= 18 GROUP BY S.rating HAVINGCOUNT (*) > 1 HAVING COUNT (*) > 1 AND EVERY (S.age <=60)

  42. Find age of the youngest sailor with age 18, for each rating with at least 2 such sailors and with every sailor under 60. HAVING COUNT (*) > 1 AND EVERY (S.age <=60) What is the result of changing EVERY to ANY?

  43. Find age of the youngest sailor with age 18, for each rating with at least 2 sailors between 18 and 60. Sailors instance: SELECT S.rating, MIN (S.age) AS min-age FROM Sailors S WHERE S.age >= 18 AND S.age <= 60 GROUP BY S.rating HAVINGCOUNT (*) > 1 Answer relation:

  44. For each red boat, find the number of reservations for this boat SELECT B.bid, COUNT (*) AS scount FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ GROUP BY B.bid • Grouping over a Join of three relations. • Q: What do we get if we remove B.color=‘red’ from the WHERE clause and add a HAVING clause with this condition? • No difference. Illegal. • Only column in GroupBy can appear in Having, unless in aggregate operator of Having • Q: What if we drop Sailors and the condition involving S.sid?

  45. Find age of the youngest sailor with age > 18, for each rating with at least 2 sailors (of any age) • HAVING clause can also contain a subquery. SELECT S.rating, MIN (S.age) FROM Sailors S WHERE S.age > 18 GROUP BY S.rating HAVING 1 < (SELECT COUNT (*) FROM Sailors S2 WHERE S.rating=S2.rating) • Q: find only ratings with 2 sailors over 18 ? • What if HAVING clause is replaced by: (two such sailors) • HAVING COUNT(*) >1

  46. Find those ratings for which the average age is the minimum over all ratings • WRONG : Aggregate operations cannot be nested! SELECT S.rating FROM Sailors S WHERE S.age = (SELECT MIN (AVG (S2.age)) FROM Sailors S2) • Correct solution (in SQL/92): SELECT Temp.rating, Temp.avgage FROM (SELECT S.rating, AVG (S.age) AS avgage FROM Sailors S GROUP BY S.rating) AS Temp WHERE Temp.avgage = (SELECT MIN (Temp.avgage) FROM Temp)

  47. Null Values • Field values in a tuple are sometimes : • unknown(e.g., a rating has not been assigned) or • inapplicable(e.g., no spouse’s name). • SQL provides a special value null for such situations. • The presence of nullcomplicates many issues. • rating>8 ?? If rating = null? What about AND, OR and NOT connectives?

  48. Null Values • SQL provides a special value null • The presence of nullcomplicates many issues. • rating>8 ?? If rating = null? What about AND, OR and NOT connectives? • We need a 3-valued logic(true, false and unknown). • Special operatorsIS NULL to check if value is/is not null. Disallow NULL value : NOT NULL • e.g., WHERE clause eliminates rows that don’t evaluate to true.Duplicates??? (treated as true implicitly)  problem! • New operators (outer Joins).

  49. Outer Joins • Left Outer Join • Right Outer Join • Full Outer Join SELECT S.sid, R.bid FROM Sailors S LEFT OUTER JOIN Reserves R WHERE S.sid = R.sid Q: Right Outer Join? Full Outer Join? SELECT S.sid, R.bid FROM Sailors S NATURAL LEFT OUTER JOIN Reserves R

  50. Summary • SQL was an important factor in the early acceptance of the relational model; more natural than earlier procedural query languages. • Relationally complete; in fact, significantly more expressive power than relational algebra. • Even queries that can be expressed in RA can often be expressed more naturally in SQL. • Many alternative ways to write a query; optimizer should look for most efficient evaluation plan. • In practice, users need to be aware of how queries are optimized and evaluated for best results.

More Related