Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS122 Using Relational Databases and SQL

Similar presentations


Presentation on theme: "CS122 Using Relational Databases and SQL"— Presentation transcript:

1 CS122 Using Relational Databases and SQL
7/29/2018 CS122 Using Relational Databases and SQL 4. Subqueries and joins Randy Moss Department of Computer Science California State University, Los Angeles

2 Outline Subqueries Joining tables Subqueries in the WHERE clause
7/29/2018 Outline Subqueries Subqueries in the WHERE clause Subqueries with IN, ALL & ANY Joining tables Learn how SQL joins tables Join tables using an Equi Join Join tables using an Inner Join 4. Subqueries and joins CS122_W2014

3 Sub-Queries A query within a query Sub-query placed in parentheses
7/29/2018 Sub-Queries A query within a query Sub-query placed in parentheses Sub-queries can be placed in WHERE clause HAVING clause SELECT clause FROM clause 4. Subqueries and joins CS122_W2014

4 Sub-Queries examples (1)
7/29/2018 Sub-Queries examples (1) List the name of the oldest member Find the earliest birthday ( ) Select min(birthday) From Members Find the member whose birthday is ‘ ’ Select firstname, lastname Where birthday = ‘ ’ 4. Subqueries and joins CS122_W2014

5 Sub-Queries examples (1)
7/29/2018 Sub-Queries examples (1) Combine the two queries SELECT firstname, lastname FROM Members WHERE birthday = (SELECT Min(birthday) FROM Members ) 4. Subqueries and joins CS122_W2014

6 Outer query looks for records with Birthday matching Sub-Query value
Sub-Query Example (1) Outer query looks for records with Birthday matching Sub-Query value Select Lastname, Firstname From Members Where Birthday = (Select Min(Birthday) From Members) Sub-Query returns Query returns Lastname Firstname Wong Tony

7 Sub-Queries examples (2)
7/29/2018 Sub-Queries examples (2) List all track titles and lengths of all tracks whose length is longer than the average of all track lengths Find the average track lenghths (276.08) SELECT Avg(lengthseconds) FROM Tracks Find the all track titles and lengths of all tracks whose length is greater than SELECT tracktitle, lengthseconds FROM Tracks WHERE lengthseconds > 4. Subqueries and joins CS122_W2014

8 Sub-Queries examples (2)
7/29/2018 Sub-Queries examples (2) Combine the two queries SELECT tracktitle, lengthseconds FROM Tracks WHERE lengthseconds > ( SELECT Avg(lengthseconds) FROM Tracks ) 4. Subqueries and joins CS122_W2014

9 7/29/2018 Sub-Queries using IN Report the name of all artists who have recorded a title SELECT artistName FROM Artists WHERE artistID IN (SELECT artistID FROM Titles) 4. Subqueries and joins CS122_W2014

10 ALL & ANY Used with Sub-Queries
7/29/2018 ALL & ANY Used with Sub-Queries Can be used with greater than and less than tests If using ANY, then comparison will be true if it satisfies any value produced by the sub-query SOME is functionally equivalent to ANY If using ALL, then comparison will be true if it satisfies all values produced by the sub-query. 4. Subqueries and joins CS122_W2014

11 ALL example 7/29/2018 List the name, region, and birthday of every member who is older than all of the members in Georgia Select Birthday From Members Where Region='GA' Birthday Select Lastname, Firstname, Region, Birthday From Members Where Birthday < ALL(Select Birthday From Members Where Region='GA') Lastname Firstname Region Birthday Ranier Brian ONT Kale Caroline VA Wong Tony ONT Cleaver Vic VT 4. Subqueries and joins CS122_W2014

12 ANY example WHERE region = 'GA' )
7/29/2018 ANY example List the name, region, and birthday of every member who is older than any of the members in Georgia SELECT lastname, firstname, region, birthday FROM Members WHERE birthday < ANY (SELECT birthday FROM Members WHERE region = 'GA' ) 4. Subqueries and joins CS122_W2014

13 7/29/2018 Exercises Report the firstname, lastname and birthday of the members who has the same birthday as someone in Virginia Is the following query correct? SELECT lastname, firstname, region, birthday FROM Members WHERE birthday = ALL (SELECT birthday FROM Members WHERE region = 'GA' ) No! We cannot compare a single value with a LIST of values 4. Subqueries and joins CS122_W2014

14 Exercises (cont.) How about this query?
7/29/2018 Exercises (cont.) How about this query? SELECT lastname, firstname, region, birthday FROM Members WHERE birthday = (SELECT birthday FROM Members WHERE region = 'GA') No! We cannot compare a single value with a LIST of values We cannot compre 3 with (3,4,5,6) 4. Subqueries and joins CS122_W2014

15 Exercises (cont.) This one?
7/29/2018 Exercises (cont.) This one? SELECT lastname, firstname, region, birthday FROM Members WHERE birthday = ANY (SELECT birthday FROM Members WHERE region = 'GA') Correct! =ANY is equivalent to IN 4. Subqueries and joins CS122_W2014

16 Joins When SQL joins two tables you can select any column from either table as if they were both in same table Joins tables "side-by-side" Tables must share a common field Primary Key – Foreign Key Table 1 Table 2 4. Subqueries and joins CS122_W2014

17 How SQL Joins Tables Step 1: Create Cartesian Product
All possible combinations of data in both tables

18 How SQL Joins Tables Step 2: Eliminate Non-Matching Records

19 Join (another example)
7/29/2018 Join (another example) When information is spread over multiple tables Find the projects which John is working on Projects Employees eid pid 01 T4 X3 02 S2 eid ename 01 John 02 Susan 4. Subqueries and joins CS122_W2014

20 Results eid ename pid John 01 T4 John 01 X3 02 S2 Susan pid T4 X3
7/29/2018 Results eid ename pid John 01 T4 John 01 X3 02 S2 Susan pid T4 X3 4. Subqueries and joins CS122_W2014

21 The kinds of join Cross join Equi Join Inner join Outer join Self join
7/29/2018 The kinds of join Cross join Equi Join Inner join Outer join Left join Right join Self join 4. Subqueries and joins CS122_W2014

22 Step1: Cartesian product
7/29/2018 Step1: Cartesian product Join every row in the first table to every row in the second table in every possible combination Employees Projects eid ename pid John 01 T4 John 01 X3 John 01 02 S2 01 T4 Susan 02 01 X3 Susan 02 02 S2 Susan 4. Subqueries and joins CS122_W2014

23 Step2: Throw out non-matching records
7/29/2018 Step2: Throw out non-matching records pid eid ename John 01 X3 T4 02 S2 Susan Non-matching records 4. Subqueries and joins CS122_W2014

24 Cross Join Builds a Cartesian product Uses no ON keyword

25 Cross Join SELECT firstname, lastname, genre
| firstname | lastname | genre | | Bob | Bentley | alternative | | Lisa | Williams | alternative | | Clint | Sanchez | alternative | | Scott | Bull | alternative | | Bob | Bentley | classical | | Lisa | Williams | classical | | Clint | Sanchez | classical | | Scott | Bull | classical | | Bob | Bentley | jazz | | Lisa | Williams | jazz | | Clint | Sanchez | jazz | | Scott | Bull | jazz | | Bob | Bentley | metal | | Lisa | Williams | metal | | Clint | Sanchez | metal | | Scott | Bull | metal | | Bob | Bentley | R&B | | Lisa | Williams | R&B | | Clint | Sanchez | R&B | | Scott | Bull | R&B | | Bob | Bentley | rap | | Lisa | Williams | rap | | Clint | Sanchez | rap | | Scott | Bull | rap | | Bob | Bentley | pop | | Lisa | Williams | pop | | Clint | Sanchez | pop | | Scott | Bull | pop | SELECT firstname, lastname, genre FROM SalesPeople cross join Genre; 5. More joins CS122_W2014

26 Tips to join tables Find which tables to join: TA, TB
7/29/2018 Tips to join tables Find which tables to join: TA, TB Find the common attributes of those tables: field Specify the relationship in the where clause: TA.field=TB.field Put the two tables’ fields in the select clause as needed 4. Subqueries and joins CS122_W2014

27 Which fields to match (throw non-matching fields
7/29/2018 Equi Join example 1 List the CD title and the title of all tracks recorded in Studio 2 SELECT title, tracktitle FROM Titles, Tracks WHERE Titles.titleID = Tracks.titleID AND studioID=2 Which tables to join Which fields to match (throw non-matching fields 4. Subqueries and joins CS122_W2014

28 Equi Join example 2 List the names of members from Georgia (GA) and their salespeople. Select Members.Lastname, Members.FirstName, Salespeople.Lastname,Salespeople.Firstname From Members, Salespeople Where Members.SalesID= SalesPeople.SalesID And Region='GA' 4. Subqueries and joins CS122_W2014

29 Table Aliases Saves typing Table name cannot be used in rest of query
7/29/2018 Table Aliases Saves typing Table name cannot be used in rest of query Case-sensitive in some systems Example List the names of members from Georgia (GA) and their salespeople SELECT M.Lastname, M.FirstName, S.Lastname,S.Firstname FROM Members M, Salespeople S WHERE M.SalesID= S.SalesID And Region='GA' 4. Subqueries and joins CS122_W2014

30 7/29/2018 Equi join example 3 List the names of all artists who have recorded a title and the number of titles they have SELECT artistname, COUNT(Titles.artistID) AS NumTitles FROM Artists, Titles WHERE Artists.artistID=Titles.artistID GROUP BY artistname 4. Subqueries and joins CS122_W2014

31 Equi Join example 4 List the names of members in The Bullets.
Select Members.Lastname, Members.FirstName From Members, XRefArtistsMembers, Artists Where Members.MemberID = XRefArtistsMembers.MemberID And Artists.ArtistID = XRefArtistsMembers.ArtistID And Artistname = 'The Bullets' 4. Subqueries and joins CS122_W2014

32 Equi join summary The tables to join are in the FROM clause
7/29/2018 Equi join summary The tables to join are in the FROM clause Only join just enough tables The relationship specifications are in the WHERE clause WHERE clause will get messy if more tables are added 4. Subqueries and joins CS122_W2014

33 Inner Join Same result as Equi Join Different Syntax
7/29/2018 Inner Join Same result as Equi Join Different Syntax Tables are listed with the keyword INNER JOIN Relationship specifications moved from WHERE clause to ON clause Free WHERE clause for traditional conditions 4. Subqueries and joins CS122_W2014

34 7/29/2018 Inner Join example 1 List the CD title and the title of all tracks recorded in Studio 2 SELECT title, tracktitle FROM Titles INNER JOIN Tracks ON Titles.titleid = Tracks.titleid WHERE studioID=2 Tables to join Relationship specification 4. Subqueries and joins CS122_W2014

35 Inner Join example 2 List the names of members from Georgia (GA) and their salespeople. Select Members.Lastname, Members.FirstName, Salespeople.Lastname,Salespeople.Firstname From Members Inner Join Salespeople On Members.SalesID= Salespeople.SalesID Where Region='GA' 4. Subqueries and joins CS122_W2014

36 7/29/2018 Inner Join example 3 List the names of all artists who have recorded a title and the number of titles they have SELECT artistname, COUNT(Titles.artistID) AS NumTitles FROM Artists INNER JOIN Titles ON Artists.artistID=Titles.artistID GROUP BY artistName 4. Subqueries and joins CS122_W2014

37 Inner Join example 4 List the names of members in The Bullets.
Select Members.Lastname, Members.FirstName From Members Inner Join XrefArtistsMembers On Members.MemberID = XRefArtistsMembers.MemberID Inner Join Artists On Artists.ArtistID = XRefArtistsMembers.ArtistID Where Artistname = 'The Bullets' Note: some systems require joins be grouped with parentheses. List the names of members in The Bullets. Select Members.Lastname, Members.FirstName From (Members Inner Join XrefArtistsMembers On Members.MemberID = XRefArtistsMembers.MemberID) Inner Join Artists On Artists.ArtistID = XRefArtistsMembers.ArtistID Where Artistname = 'The Bullets' 4. Subqueries and joins CS122_W2014

38 Inner Join example 4 with Aliases
List the names of members in The Bullets. Select M.Lastname, M.FirstName From (Members M Inner Join XrefArtistsMembers X On M.MemberID = X.MemberID) Inner Join Artists A On A.ArtistID = X.ArtistID Where Artistname = 'The Bullets' 4. Subqueries and joins CS122_W2014

39 Outer Join Left join Right join The order of tables MATTERS
7/29/2018 Outer Join Left join Report all of the records of the first (left) of two tables plus matching records in the second (right) table. Right join Report all of the records of the second (right) of two tables plus matching records in the first (left) table The order of tables MATTERS 5. More joins CS122_W2014

40 Inner Joins vs. Outer Joins
7/29/2018 Inner Joins vs. Outer Joins List the names of all artists who have recorded a title and the titles they have SELECT Artistname, Title FROM Artists A Inner Join Titles T ON A.ArtistID=T.ArtistID Artistname Title The Neurotics Meet the Neurotics Confused Smell the Glove The Bullets Time Flies The Neurotics Neurotic Sequel Sonata Sonatas Louis Holiday Louis at the Keys 5. More joins CS122_W2014

41 Inner Joins vs. Outer Joins
7/29/2018 Inner Joins vs. Outer Joins List the names of all artists and the titles(if any) that they have recorded SELECT Artistname, Title From Artists A Left Join Titles T ON A.ArtistID=T.ArtistID Artistname Title The Neurotics Meet the Neurotics The Neurotics Neurotic Sequel Louis Holiday Louis at the Keys Word NULL Sonata Sonatas The Bullets Time Flies Jose MacArthur NULL Confused Smell the Glove The Kicks NULL Today NULL 21 West Elm NULL Highlander NULL 5. More joins CS122_W2014

42 Another outer Join example
7/29/2018 Another outer Join example List every genre from the Genre table and a count of the number of recorded tracks in that genre, if any SELECT G.Genre, Count(Tracknum) As NumTracks FROM (Genre G LEFT JOIN Titles TI ON G.Genre = TI.Genre) LEFT JOIN Tracks TR ON TI.TitleID = TR.TitleID GROUP BY G.Genre 5. More joins CS122_W2014

43 Using Outer Join to Duplicate NOT IN Functionality
7/29/2018 Using Outer Join to Duplicate NOT IN Functionality Report artists who don’t have titles SELECT A.ArtistID, Artistname, T.ArtistID FROM Artists A Left Join Titles T ON A.ArtistID=T.ArtistID ArtistID Artistname ArtistID The Neurotics Louis Holiday Word NULL Sonata The Bullets Jose MacArthur NULL Confused The Kicks NULL Today NULL West Elm NULL Highlander NULL 5. More joins CS122_W2014

44 Using Outer Join to Duplicate Not IN Functionality (cont.)
7/29/2018 Using Outer Join to Duplicate Not IN Functionality (cont.) Report artists who don’t have titles SELECT Artistname FROM Artists A Left Join Titles T ON A.ArtistID=T.ArtistID WHERE T.ArtistID Is Null Artistname Word Jose MacArthur The Kicks Today 21 West Elm Highlander SELECT Artistname FROM Artists WHERE ArtistID NOT IN (SELECT ArtistID FROM Titles) Artistname Word Jose MacArthur The Kicks Today 21 West Elm Highlander 5. More joins CS122_W2014

45 Joining on More Than One Column
7/29/2018 Joining on More Than One Column Include AND in ON or WHERE clause to link on second, third, etc. columns Works with either Equi Join or Inner/Outer Join syntax Inner Join Select TrackTitle From Tracks T Inner Join AudioFiles A On T.TitleID=A.TitleID And T.Tracknum=A.Tracknum Where AudioFormat='MP3' Equi Join Select TrackTitle From Tracks T, AudioFiles A Where T.TitleID=A.TitleID And T.Tracknum=A.Tracknum And AudioFormat='MP3' 5. More joins CS122_W2014

46 Self Joins Table 2 Table 2 Table 1 Joining two tables Self Join
7/29/2018 Self Joins Joining two tables Self Join Table 2 Table 2 Table 1 5. More joins CS122_W2014

47 Example Self Joining Table
7/29/2018 Example Self Joining Table 5. More joins CS122_W2014

48 Self-Join Join a table to itself Can be either an INNER or OUTER JOIN
7/29/2018 Self-Join Join a table to itself Can be either an INNER or OUTER JOIN A self join always uses two fields in a table. Need to use table aliases for differentiate two instances of the same table 5. More joins CS122_W2014

49 Self Join Example List the names of all salespeople who have supervisors along with the names of their supervisors. Select Sales.Firstname As EmpFirst, Sales.Lastname as EmpLast, Sup.Firstname as SupFirst, Sup.Lastname as SupLast From Salespeople Sales Inner Join Salespeople Sup On Sales.Supervisor=Sup.SalesID EmpFirst EmpLast SupFirst SupLast Bob Bentley Scott Bull Lisa Williams Scott Bull Clint Sanchez Bob Bentley

50 Joins Compared Inner (Equi) Joins Outer Joins Self Joins Cross Joins
Reports only matched rows Outer Joins Reports all of records from one table plus matching records from the other table Self Joins Column in one table matched to another column in same table Cross Joins Cartesian product without dealing with matches


Download ppt "CS122 Using Relational Databases and SQL"

Similar presentations


Ads by Google