Presentation is loading. Please wait.

Presentation is loading. Please wait.

Basic SQL Queries Go over example queries, like 10 > ALL.

Similar presentations


Presentation on theme: "Basic SQL Queries Go over example queries, like 10 > ALL."— Presentation transcript:

1 Basic SQL Queries Go over example queries, like 10 > ALL.
Show how create assertion fails. Check into setting up queries in SQL Server.

2 Introduction Introduce SQL, the standard query language for relational DBS. An SQL query takes one or more input tables and returns one output table. We’ll start with the case of one input table

3 Example Instances bid colour 101 green 103 red Sailors Boats Reserves
cmpt354.c4_sailors1 Reserves

4 Overview Basic SQL syntax Set Operations Joins Advanced Queries
nested queries comparing sets, strings.

5 Sinlge-Table SQL Queries

6 Basic SQL Syntax table A table name (possibly with a range-variable).
SELECT [DISTINCT] target-list FROM table WHERE qualification table A table name (possibly with a range-variable). 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! Implementation in SQL different from relational model – multiset vs. set. “select” in SQL = “project” in Relational Algebra.

7 Conceptual Evaluation
Semantics of an SQL query defined in terms of the following conceptual evaluation strategy: Retrieve the tuples in table. Discard resulting tuples if they fail qualifications. Delete attributes that are not in target-list. If DISTINCT is specified, eliminate duplicate rows.

8 Basic Operators in SQL

9 SELECT (columns, values)
SELECT S.sname FROM Sailors S Write out relational algebra, as exercise

10 WHERE The WHERE clause selects/filters rows. SELECT * FROM Sailors S
WHERE S.sid = 58

11 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 Set up and Illustrate in SQL Server. Do views later? How to handle DROP TABLE if there’s a view on the table? DROP TABLE command has options to let the user specify this. Contrast with rho notation ion relational algebra. 18

12 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 Set up and Illustrate in SQL Server. Do views later? How to handle DROP TABLE if there’s a view on the table? DROP TABLE command has options to let the user specify this. Contrast with rho notation ion relational algebra. 18

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’ 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 Strings By default, like is case insensitive. Can make it case sensitive, it’s a bit complicated funny See also Oracle solution For character length: SELECT titles.*, LEN(title) AS TitleLength FROM titles

14 Basic SET Operators iN SQL

15 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 WHERE S.rating = 10 Answer1: boats that are both red and green. % Answer 2: sailors with red boats – sailors with green boats.

16 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 Mysql, but yes in SQL Server SELECT S.sid FROM Sailors S WHERE S.age = 45.0 INTERSECT WHERE S.rating = 10

17 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 but yes in SQL Server. SELECT S.sid FROM Sailors S WHERE S.age = 45.0 EXCEPT WHERE S.rating = 10 What does this query return?

18 multiple tables Table Joins

19 Basic SQL Syntax SELECT [DISTINCT] target-list FROM relation-list WHERE qualification relation-list A list of table names (possibly with range-variables). 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. Implementation in SQL different from relational model – multiset vs. set. “select” in SQL = “project” in Relational Algebra.

20 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. Short version: compute the cross-product of the named tables. Apply single-table evaluation to cross-product.

21 Example of Conceptual Evaluation
SELECT * FROM Sailors S, Reserves R WHERE S.sid=R.sid AND R.bid=103 Try in SQL Server or mysql First equality is join condition. Try leaving it out.

22 Cross Product FROM List is interpreted as cross product.
SELECT * FROM Sailors, Reserves With JOIN keyword SELECT * FROM Sailors CROSS JOIN Reserves

23 Joining Two Tables WHERE clause specifies selection condition SELECT *
FROM Sailors S, Reserves R WHERE S.sid=R.sid (sid) sname rating age bid day 22 dustin 7 45.0 101 10/10/96 58 103 11/12/96 31 lubber 8 55.5 rusty 10 35.0 Try in SQL Server. First equality is join condition. Try leaving it out.

24 JOIN ON With JOIN keyword ON replaces WHERE SELECT *
FROM Sailors S JOIN Reserves R ON S.sid=R.sid AND R.bid=103 Check correctness

25 Natural Join forces equality on columns with the same name.
SELECT * FROM Sailors NATURAL JOIN Reserves forces equality on columns with the same name. Not supported in SQL Server but yes in MySQL. Can replace INTERSECT. SELECT * FROM (SELECT S.sid FROM Sailors S WHERE S.age = 45.0 NATURAL JOIN SELECT S.sid WHERE S.rating = 10) CHECK QUERY. Natural Join doesn’t work in SQL server, see . But it does work in MySQL.

26 MySQL Natural Join Syntax
SELECT * FROM (SELECT S.sid FROM Sailors S WHERE S.age = 45.0) SailorAge NATURAL JOIN WHERE S.rating = 10) SailorRating; view idea is important for assignment 2 must name derived (defined) tables could use views instead

27 Examples and Exercises

28 Natural Join Exercise What is the natural join of a table with itself?
e.g. select * from Sailors natural join Sailors? What is the natural join of two tables that have exactly the same columns? Answer. 1: you get back the original table. Idempotence. 2. the intersection of the two tables.

29 Find sailors who’ve reserved at least one boat
SELECT S.sid FROM Sailors S, Reserves R WHERE S.sid=R.sid 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? Answer 1: yes, if sailors can reserve more than one boat. Answer 2: may lead to loss of information if sailors with different ids have the same name “not equals” = <>. Or !=. See . Try this out in SQL Server.

30 Exercise Write the following queries in SQL:
Find sid’s of sailors who have reserved a red or a green boat. Find sid’s of sailors who have reserved a red and a green boat. SELECT R.sid FROM Boats B, Reserves R WHERE R.bid=B.bid AND B.color=‘red’ UNION WHERE R.bid=B.bid AND B.color=‘green’ For 2: SELECT R.sid INTERSECT Or using natural join: select * from (SELECT R.sid AND B.color='red') RedBoatSailors Natural join AND B.color='green') GreenBoatSailors;

31 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: Find the pnames of parts for which there is some supplier. Find the sids of suppliers who supply a red part or a green part. Find the sids of suppliers who supply a red part and a green part.

32 Intermediate SQL start with Canvas quiz

33 Set Membership Find sailors who are 45 years old and have rating 10. <tuple> IN <relation> 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)

34 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) Look up lack of support. What does this query return?

35 Nested Queries

36 Nested Queries SELECT S.sid FROM Sailors S WHERE S.sid NOT IN (SELECT sid FROM Sailors WHERE rating = 10) 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. Debugging hint: write and run subqueries first.

37 Nested Queries with Correlation
Find names of sailors who’ve reserved boat #103: SELECT S.sname FROM Sailors S WHERE EXISTS (SELECT * FROM Reserves R WHERE R.bid=103 AND S.sid=R.sid) EXISTS <query> returns TRUE if the query is not empty. Subquery must be re-evaluated for each Sailors tuple. Unique (instead of exists) checks for duplicates with respect to entire row. True iff no row appears twice. Illustrates use of *. Without R.bid, we may have two reservations that don’t appear twice. Unique doesn’t seem to have been implemented in SQL server (or anywhere) If UNIQUE is used, and * is replaced by R.bid, finds sailors with at most one reservation for boat #103. (UNIQUE checks for duplicate tuples; * denotes all attributes. Why do we have to replace * by R.bid?)

38 “All” Queries 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)) The negation trick. Find sailors who have not reserved all boats. Use NOT or EXCEPT to find the others. exists a not reserved boat? find all boats show venn diagram show 1st-order logic /* find boats that have been reserved by Sailor */ find boats that have been reserved by Sailor S

39 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. Show examples of tuples that do and don’t satisfy the condition 1. SELECT S.sid FROM Suppliers S EXCEPT /* a part that is supplied by sid and not red */ (SELECT C.sid FROM Parts P, Catalog C WHERE P.pid = C.pid AND P.color <> ‘red’) 2. SELECT S.sname WHERE NOT EXISTS /*find parts that have not been supplied by sid*/ ((SELECT P.pid FROM Parts P) /*find all parts supplied by sid */ (SELECT C.pid FROM Catalog C WHERE C.sid = S.sid)) Find the sids of suppliers who supply only red parts. Find the snames of suppliers who supply every part.

40 Set comparisons

41 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’) Any: there is some member of set that makes comparison true. False on empty set. All: all members of set make comparison true. True on empty set. Hacky! Maybe go to Aggregation Functions now.

42 Simple Examples for Any and All
1 = Any {1,3} True 1 = All {1,3} False 1 = Any {} False 1 = All {} True

43 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, solution for the only red parts example using ALL Select S.sid from Suppliers S where ‘Red’ = ALL (select Parts.color from Catalog, Parts where Catalog.sid = S.sid and Parts.pid = Catalog.pid ) /* the inner query finds the colors of all parts supplied by the supplier. */ Find the snames of suppliers who supply only red parts.

44 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.


Download ppt "Basic SQL Queries Go over example queries, like 10 > ALL."

Similar presentations


Ads by Google