Presentation is loading. Please wait.

Presentation is loading. Please wait.

Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Basic SQL Queries.

Similar presentations


Presentation on theme: "Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Basic SQL Queries."— Presentation transcript:

1 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Basic SQL Queries

2 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke2 Why documenting your assignment solution is good practice

3 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke3 Introduction  Introduce SQL, the standard query language for relational DBS.  Like relational algebra, an SQL query takes one or two input tables and returns one output table.  Any RA query can also be formulated in SQL.  In addition, SQL contains certain features that go beyond the expressiveness of RA, e.g. sorting and aggregation functions.

4 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke4 Introduction  Introduce SQL, the standard query language for relational DBS.  An SQL query takes one or two input tables and returns one output table.

5 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke5 Example Instances Reserves Sailors bidcolour 101green 103red Boats

6 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke6 Overview  Basic SQL syntax  Set Operations  Joins  Advanced Queries  nested queries  comparing sets, strings.

7 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke7 Basic SQL Queries

8 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke8 Basic SQL Syntax  relation-list A list of relation names (possibly with a range-variable after each name).  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 an optional keyword indicating that the answer should not contain duplicates. Default is that duplicates are not eliminated! SELECT [DISTINCT] target-list FROM relation-list WHERE qualification

9 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke9 Conceptual Evaluation  Semantics of an SQL query defined in terms of the following conceptual evaluation strategy:  Compute the 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.  More generally, the FROM clause must contain an expression that evaluates to a relation.

10 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke10 Example of Conceptual Evaluation SELECT * FROM Sailors S, Reserves R WHERE S.sid=R.sid AND R.bid=103

11 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke11 Range Variables  Really needed only if the same relation appears twice in the FROM clause. The previous query can also be written as: SELECT * FROM Sailors S, Reserves R WHERE S.sid=R.sid AND bid=103 SELECT * FROM Sailors, Reserves WHERE Sailors.sid=Reserves.sid AND bid=103 OR

12 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke12 BASIC OPERATORS IN SQL Relational Algebra Ops

13 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke13 SELECT (columns, values) SELECT S.sname FROM Sailors S

14 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke14 WHERE  The WHERE clause selects/filters rows. SELECT * FROM Sailors S WHERE S.sid = 58

15 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke15 Union  Find sid’s of sailors who are 45 years old or have rating 10.  UNION : Can be used to compute the union of any two union-compatible sets of tuples (which are themselves the result of SQL queries).  If we replace OR by AND in the first version, what do we get? SELECT S.sid FROM Sailors S WHERE S.age = 45.0 OR S.rating = 10 SELECT S.sid FROM Sailors S WHERE S.age = 45.0 UNION SELECT S.sid FROM Sailors S WHERE S.rating = 10

16 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke16 Intersections  Find sid’s of sailors who are 45 years old and have rating 10.  INTERSECT: Can be used to compute the intersection of any two union-compatible sets of tuples.  Not supported in? SELECT S.sid FROM Sailors S WHERE S.age = 45.0 INTERSECT SELECT S.sid FROM Sailors S WHERE S.rating = 10

17 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke17 Set Difference  Find sid’s of sailors who are 45 years old and do not have rating 10.  EXCEPT: Can be used to compute the set difference of any two union- compatible sets of tuples.  Not supported in MySQL. SELECT S.sid FROM Sailors S WHERE S.age = 45.0 EXCEPT SELECT S.sid FROM Sailors S WHERE S.rating = 10

18 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke18 Cross Product and Table Joins  FROM List is interpreted as cross product. SELECT * FROM Sailors, Reserves SELECT * FROM Sailors CROSS JOIN Reserves  With JOIN keyword

19 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke19 Joining Two Tables SELECT * FROM Sailors S, Reserves R WHERE S.sid=R.sid AND R.bid=103  WHERE clause specifies selection condition

20 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke20 π-σ-× Queries  SELECT [DISTINCT] S.sname  π sname  FROM Sailors, Reserves  Sailors × Reserves  WHERE S.sid=R.sid AND R.bid=103  σ Sailors.sid = Reserves.sid and Reserves.bid=103  SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid=R.sid AND R.bid=103 = π sname (σ Sailors.sid = Reserves.sid and Reserves.bid=103 ( Sailors × Reserves ))  It is often helpful to write an SQL query in the same order (FROM, WHERE, SELECT).

21 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke21 JOIN ON  With JOIN keyword  ON replaces WHERE SELECT * FROM Sailors S JOIN Reserves R ON S.sid=R.sid AND R.bid=103

22 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke22 Natural Join  forces equality on columns with the same name.  Not supported in SQL Server.  Can replace INTERSECT. SELECT * FROM (SELECT S.sid FROM Sailors S WHERE S.age = 45.0 NATURAL JOIN SELECT S.sid FROM Sailors S WHERE S.rating = 10) SELECT * FROM Sailors NATURAL JOIN Reserves

23 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke23 MySQL Natural Join Syntax SELECT * FROM (SELECT S.sid FROM Sailors S WHERE S.age = 45.0) SailorAge NATURAL JOIN SELECT S.sid FROM Sailors S WHERE S.rating = 10) SailorRating; must name derived (defined) tables could use views instead

24 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke24 Examples and Exercises

25 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke25 Natural Join Exercise 1. What is the natural join of a table with itself? 1.e.g. select * from Sailors natural join Sailors? 2. What is the natural join of two tables that have exactly the same columns?

26 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke26 Find sailors who’ve reserved at least one boat  Would adding DISTINCT to this query make a difference?  What is the effect of replacing S.sid by S.sname in the SELECT clause? Would adding DISTINCT to this variant of the query make a difference? SELECT S.sid FROM Sailors S, Reserves R WHERE S.sid=R.sid

27 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke27 Exercise  Write the following queries in SQL: 1. Find sid’s of sailors who have reserved a red or a green boat. 2. Find sid’s of sailors who have reserved a red and a green boat.

28 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke28 Find sid’s of sailors who’ve reserved a red or a green boat  UNION : Can be used to compute the union of any two union-compatible sets of tuples (which are themselves the result of SQL queries).  If we replace OR by AND in the first version, what do we get?  Also available: EXCEPT (What do we get if we replace UNION by EXCEPT ?) 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’) 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’

29 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke29 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.  Included in the SQL/92 standard, but some systems don’t support it.  Contrast symmetry of the UNION and INTERSECT queries with how much the other versions differ. 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’) 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’ Key field!

30 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke30 Operator Exercise Consider the following schema. Suppliers(sid: integer, sname: string, address: string) Parts(pid: integer, pname: string, color: string) Catalog(sid: integer, pid: integer, cost: real) The Catalog lists the prices charged for parts by Suppliers. Write the following queries in SQL: 1.Find the pnames of parts for which there is some supplier. 2.Find the sids of suppliers who supply a red part or a green part. 3.Find the sids of suppliers who supply a red part and a green part.

31 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke31 Division in SQL  Let’s do it the hard way, without EXCEPT : 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)) 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 Find sailors who’ve reserved all boats. (1) (2)

32 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke32 Intermediate SQL

33 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke33 Multiple Choice Which of the following SQL constructs can be used to rename relations? a.Views. b.range variables. c.keyword AS d.all of the above Which of the following SQL constructs can be used to rename columns? a.Views. b.range variables. c.keyword AS d.all of the above

34 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke34 Renaming Relations: Views  A view is just a relation, but we store a definition, rather than a set of tuples.  Any SQL query can be stored as a view.  Views can be dropped using the DROP VIEW command. CREATE VIEW MySailors (sid, name) AS SELECT S.sid, S.sname FROM Sailors S WHERE S.age = 45.0 OR S.rating = 10

35 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke35 Renaming Columns  the AS keyword can be used to rename columns. SELECT S.sid AS SailorSid, R.sid AS ReserveSid FROM Sailors S, Reserves R

36 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke36 Expressions and Strings  Illustrates use of arithmetic expressions and string pattern matching: Find results for sailors whose names begin and end with B and contain at least three characters.  AS and = 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. case sensitivity Oracle on Stringscase sensitivityOracle on Strings SELECT S.age, age1=S.age-5, 2*S.age AS age2 FROM Sailors S WHERE S.sname LIKE ‘b_%b’

37 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke37 Set Membership  IN returns TRUE if the tuple is contained in the relation.  Can replace INTERSECT. SELECT * FROM Sailors S WHERE S.age = 45.0 AND S.sid IN (SELECT sid FROM Sailors WHERE rating = 10)  Find sailors who are 45 years old and have rating 10.

38 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke38 NOT IN can replace EXCEPT  Find sid’s of sailors who are 45 years old and do not have rating 10. SELECT S.sid FROM Sailors S WHERE S.age = 45.0 AND S.sid NOT IN (SELECT sid FROM Sailors WHERE rating = 10)

39 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke39 NESTED QUERIES

40 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke40 Nested Queries  A powerful feature of SQL: a WHERE clause can itself contain an SQL query!  So can FROM clauses.  To find sailors who’ve not reserved #103, use NOT IN.  To understand semantics of nested queries, think of a nested loops evaluation: For each Sailors tuple, check the qualification by computing the subquery. SELECT S.sid FROM Sailors S WHERE S.sid NOT IN (SELECT sid FROM Sailors WHERE rating = 10)

41 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke41 Nested Queries  A powerful feature of SQL: a WHERE clause can itself contain an SQL query!  So can FROM clauses.  To find sailors who’ve not reserved #103, use NOT IN.  To understand semantics of nested queries, think of a nested loops evaluation: For each Sailors tuple, check the qualification by computing the subquery. SELECT S.sname FROM Sailors S WHERE S.sid IN ( SELECT R.sid FROM Reserves R WHERE R.bid=103) Find names of sailors who’ve reserved boat #103:

42 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke42 Nested Queries with Correlation  EXISTS returns TRUE if the query is not empty.  Subquery must be re-evaluated for each Sailors tuple. SELECT S.sname FROM Sailors S WHERE EXISTS ( SELECT * FROM Reserves R WHERE R.bid=103 AND S.sid=R.sid) Find names of sailors who’ve reserved boat #103:

43 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke43 Rewriting EXCEPT Queries Using NOT IN  Similarly, EXCEPT queries re-written using NOT IN.  To find names (not sid ’s) of Sailors who’ve reserved both red and green boats, just replace S.sid by S.sname in SELECT clause. 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’)

44 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke44 “All” Queries in SQL 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)) Find sailors who’ve reserved all boats. The negation trick. Find sailors who have not reserved all boats. Use NOT or EXCEPT to find the others. find boats that have been reserved by Sailor S exists a not reserved boat? find all boats

45 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke45 Exercise ctd. Consider the following schema. Suppliers(sid: integer, sname: string, address: string) Parts(pid: integer, pname: string, color: string) Catalog(sid: integer, pid: integer, cost: real) The Catalog lists the prices charged for parts by Suppliers. Write the following queries in SQL. You can use NOT EXISTS. 1.Find the sids of suppliers who supply only red parts. 2.Find the snames of suppliers who supply every part.

46 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke46 SET COMPARISONS

47 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke47 More Set-Comparison Operators  We’ve already seen IN, EXISTS.  Also available: op ANY, op ALL  Find sailors whose rating is greater than that of some sailor called Horatio: SELECT * FROM Sailors S WHERE S.rating > ANY ( SELECT S2.rating FROM Sailors S2 WHERE S2.sname=‘Horatio’)

48 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke48 Simple Examples for Any and All  1 = Any {1,3} True  1 = All {1,3} False  1 = Any {}False  1 = All{}True

49 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke49 Exercise (III) Consider the following schema. Suppliers(sid: integer, sname: string, address: string) Parts(pid: integer, pname: string, color: string) Catalog(sid: integer, pid: integer, cost: real) The Catalog lists the prices charged for parts by Suppliers. Write the following query in SQL using the ALL construct, 1.Find the snames of suppliers who supply only red parts.

50 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke50 Summary: SQL Set Operators  UNION, INTERSECT, EXCEPT behave like their set theory/relational algebra counterpart.  New Operator EXISTS tests if a relation is empty.  Can use ANY, ALL to compare a value against values in a set.

51 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke51 Follow-UP  On “not equals”.  The SQL Standard operator ANSI is <>.  Apparently many systems support != as well not equals discussion.not equals discussion  We teach the standard but accept other common uses (unless explicitly ruled out).


Download ppt "Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke1 Basic SQL Queries."

Similar presentations


Ads by Google