Presentation is loading. Please wait.

Presentation is loading. Please wait.

A DVANCED SQL Joe Meehean 1. SQL S ET O PERATIONS Syntax SELECT column1, column2, … FROM table1… WHERE conditions SET_KEYWORD SELECT column1, column2,

Similar presentations


Presentation on theme: "A DVANCED SQL Joe Meehean 1. SQL S ET O PERATIONS Syntax SELECT column1, column2, … FROM table1… WHERE conditions SET_KEYWORD SELECT column1, column2,"— Presentation transcript:

1 A DVANCED SQL Joe Meehean 1

2 SQL S ET O PERATIONS Syntax SELECT column1, column2, … FROM table1… WHERE conditions SET_KEYWORD SELECT column1, column2, … FROM table2… WHERE conditions 2

3 U NION O PERATION Uses UNION keyword Combines results of two queries Result contains all rows from both queries 3

4 U NION O PERATION Example: “red and green part ids” Suppliers(sid, sname, address) Parts(pid, pname, color) Catalog(sid, pid, cost) SELECT PartId FROM Parts P1 WHERE P1.color = ‘red’ UNION SELECT PartId FROM Parts P2 WHERE P2.color = ‘green’ 4

5 I NTERSECTION O PERATION Uses the INTERSECT keyword Combines results of two queries Results contains only rows that are in results of both queries 5

6 I NTERSECTION O PERATION Example: “pids of orange bolts” SELECT pid FROM Parts P1 WHERE P1.color = ‘orange’ INTERSECT SELECT pid FROM Parts P2 WHERE P2.pname LIKE ‘%bolt%’ 6

7 D IFFERENCE O PERATION Uses the EXCEPT keyword Combines results of two queries Rows in the first query, but not in second 7

8 D IFFERENCE O PERATION Example: “pids of orange parts that are not bolts” SELECT pid FROM Parts P1 WHERE P1.color = ‘orange’ EXCEPT SELECT pid FROM Parts P2 WHERE P2.pname LIKE ‘%bolt%’ 8

9 U NION C OMPATIBLE Union, intersect, and difference require union compatible queries results of queries must be union compatible cannot combine queries that are not Union compatible tables they have the same number of columns AND corresponding columns have the same data type (e.g., VARCHAR) AND length 9

10 SQL S ET O PERATIONS AND U NIQUENESS SQL set operations UNION, INTERSECT, and EXCEPT removes duplicates If you want duplicates use UNION ALL, INTERSECT ALL, and EXCEPT ALL Number of duplicate rows in result for m in 1 st table and n in 2 nd table UNION ALL: m + n INTERSECT ALL: min ( m, n ) EXCEPT ALL: m − n 10

11 Q UESTIONS ? 11

12 W HAT WE ARE GOING TO L EARN In SQL the result of a query is a table? Can we query the resultant table? I.e., can we query a query? Nested queries query results of a query SELECT inside of a SELECT two types of results two different ways to construct 12

13 2 T YPES OF S UBQUERY R ESULTS Scalar result is a single column and row can use as a subquery to replace any single value e.g., 5000 e.g., students with better than average GPA SELECT StudentID FROM Students WHERE GPA > ( SELECT AVG(GPA) FROM Students ) 13

14 2 T YPES OF S UBQUERY R ESULTS Table result of subquery is a table outer query uses set operations to check contents of inner query results SELECT column1,…. FROM table1 WHERE columnX set_operator ( SELECT columnA, … FROM tableA WHERE condition ) 14

15 N ESTED Q UERIES S ET O PERATORS IN e.g., WHERE a IN nested_query checks whether a is in the results of the nested query EXISTS e.g., WHERE/HAVING EXIST nested_query true if the nested query returned at least one row UNIQUE e.g., WHERE UNIQUE nested_query true if the nested query contains only unique rows NOT e.g., WHERE a NOT IN nested_query negates IN, EXISTS, and UNIQUE 15

16 N ESTED Q UERIES S ET O PERATORS ANY e.g., WHERE a op ANY nested_query a is a column or a constant op is a comparison operator (,>=,>) returns true if a op is true for any row in the nested query e.g., 5,000 < ANY (SELECT salary FROM employee) returns true if any employee salary is greater than 5,000 ALL e.g., WHERE a op ALL nested_query returns true if a op is true for all rows in the nested query 16

17 T YPE I N ESTED Q UERY Nested query evaluates 1 time Produces a table Outer query compares its rows to this table e.g., course descriptions of Spring offerings without a join between Offering and Course tables SELECT CourseDesc FROM Course WHERE CourseNo IN ( SELECT CourseNo FROM Offerings WHERE term = ‘Spring’) 17

18 W HEN TO U SE T YPE I N ESTED Q UERY Do not need to reference outer query at all nested query is independent of outer query Type I queries cannot reference outer query Type I queries like a procedure call takes no parameters from outer query returns result for outer query to use 18

19 W HEN TO U SE T YPE I N ESTED Q UERY Deleting rows related to other rows delete with join only supported by Access more generally done nested queries e.g., remove failing athletes from Athletes(StudentId, TeamId) DELETE FROM Athletes WHERE StudentNo IN ( SELECT StudentNo FROM Students WHERE Students.GPA < 2.0 ) 19

20 W HEN TO U SE T YPE I N ESTED Q UERY Simple difference problems like EXCEPT without union compatible requirement generally of the form “ blank that are not blank ” e.g., “all the employees who are not pilots: e.g., “all the parts not supplied by ‘Knockoff Parts’” e.g., “all of the students who are not athletes” SELECT FirstName, LastName FROM Students WHERE StudentNo NOT IN ( SELECT StudentNo FROM Athletes ) 20

21 W HEN TO U SE T YPE I N ESTED Q UERY Why can’t we use “not equals” (<>) for this e.g., “all of the students who are not athletes” SELECT FirstName, LastName FROM Students, Athletes WHERE Students.StudentNo <> Athletes.StudentNo Will return all students effectively does a cross-product compares Students.StudentNo to all Athletes.StudentNo each student has an athlete that has a different StudentNo 21

22 R EFERENCING S AME T ABLE I N N ESTED Q UERY Use the rename operator AS e.g., “Employees who are not managers” SELECT E1.EmpID FROM Employees AS E1 WHERE E1.EmpID NOT IN (SELECT E2. ManagerID FROM Employees AS E2) 22

23 T YPE II N ESTED Q UERY References column(s) from outer query Executed once for every row in outer query like a nested loop e.g., “all of the students who are not athletes” SELECT FirstName, LastName FROM Students WHERE NOT EXISTS ( SELECT * FROM Athletes WHERE Students.StudentNo = Athletes.StudentNo ) 23

24 W HEN TO U SE T YPE II N ESTED Q UERY More difficult difference problems 24

25 W HEN TO U SE T YPE II N ESTED Q UERY e.g., “Sophmores that never took a class from Phil Park” SELECT FirstName, LastName FROM Students S WHERE Class = ‘So’ AND NOT EXISTS (SELECT * FROM (Enrollment E JOIN Offering O USING OfferNo) JOIN Faculty F USING FacultyNo WHERE S.StudentNo = E.StudentNo AND F.FirstName = ‘Phil’ AND F.LastName = ‘Park’) 25

26 W HEN TO USE N ESTED Q UERIES You need to query a query we did not cover all possible examples difference problems are most common division problems also require nested queries Then decide whether to use a Type I or II Type I is cheaper 26

27 Q UESTIONS ? 27

28 D IVISION Represented by / Combines two relations (tables), A & B A has two attributes (x,y) B has one attribute (y) A/B is all x’s such that (x,y) exists in A for all y’s in B Result has only a single attribute (x) 28

29 D IVISION O PERATOR For each x value in A consider the set of y values x maps to in A if this set contains all y values in B then x is in A/B e.g. supplier names that supply all parts find all the parts (pids) see if an sid maps to all of those pids see if the catalog has a supplier that has a row for every part 29

30 D IVISION O PERATOR Derive A/B think about what doesn’t belong in result get set of all x,y mappings remove those mappings that appear in A what’s left must be x’s that don’t map to all y’s remove them from the set of x’s 30

31 D IVISION O PERATOR Derive A/B example derivation on chalk board 31

32 D IVISION IN SQL How do we do this in SQL? Use Type I nested query GROUP BY HAVING COUNT (*) 32

33 D IVISION IN SQL Example: “sids of suppliers who supply all parts” SELECT sid FROM Catalog GROUP BY sid HAVING COUNT(*) = ( SELECT COUNT(*) FROM Parts) 33

34 D IVISION IN SQL Example: “sids of suppliers who supply all of the red parts” SELECT sid FROM Catalog C JOIN Parts P1 USING pid WHERE P1.color = ‘red’ GROUP BY sid HAVING COUNT(*) = ( SELECT COUNT(*) FROM Parts P2 WHERE P2.color = ‘red’) 34

35 Q UESTIONS ? 35


Download ppt "A DVANCED SQL Joe Meehean 1. SQL S ET O PERATIONS Syntax SELECT column1, column2, … FROM table1… WHERE conditions SET_KEYWORD SELECT column1, column2,"

Similar presentations


Ads by Google