CS122 Using Relational Databases and SQL

Slides:



Advertisements
Similar presentations
Multiple Table Queries
Advertisements

© 2007 by Prentice Hall (Hoffer, Prescott & McFadden) 1 Joins and Sub-queries in SQL.
Chapter 4 Joining Multiple Tables
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 3: Joins Part I.
A Guide to SQL, Seventh Edition. Objectives Use joins to retrieve data from more than one table Use the IN and EXISTS operators to query multiple tables.
4d. Structured Query Language – JOIN Operation Lingma Acheson Department of Computer and Information Science IUPUI CSCI N207 Data Analysis with Spreadsheets.
Relational Algebra, Join and QBE Yong Choi School of Business CSUB, Bakersfield.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 7: Subqueries and Set Operations.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 9: Data Manipulation Language.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 7: Aggregates.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 5: Subqueries and Set Operations.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 4: Joins Part II.
Using Relational Databases and SQL Department of Computer Science California State University, Los Angeles Lecture 7:
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 2: Single-Table Selections.
Using Relational Databases and SQL Steven Emory Department of Computer Science California State University, Los Angeles Lecture 4: Joins Part II.
Inner join, self join and Outer join Sen Zhang. Joining data together is one of the most significant strengths of a relational database. A join is a query.
Using Relational Databases and SQL Department of Computer Science California State University, Los Angeles Lecture 8: Subqueries.
Using Relational Databases and SQL John Hurley Department of Computer Science California State University, Los Angeles Lecture 3: Joins Part I.
Lecture 2 of Advanced Databases Advanced SQL Instructor: Mr.Ahmed Al Astal.
Chapter 9 Joining Data from Multiple Tables
A Guide to MySQL 5. 2 Objectives Use joins to retrieve data from more than one table Use the IN and EXISTS operators to query multiple tables Use a subquery.
1 CS 430 Database Theory Winter 2005 Lecture 12: SQL DML - SELECT.
Using Relational Databases and SQL Department of Computer Science California State University, Los Angeles Lecture 6: Midterm Review.
Chapter 4Introduction to Oracle9i: SQL1 Chapter 4 Joining Multiple Tables.
Using Relational Databases and SQL John Hurley Department of Computer Science California State University, Los Angeles Lecture 2: Single-Table Selections.
Using Relational Databases and SQL Department of Computer Science California State University, Los Angeles Lecture 4: Joins Part II.
In this session, you will learn to: Query data by using joins Query data by using subqueries Objectives.
Manipulating Data Lesson 3. Objectives Queries The SELECT query to retrieve or extract data from one table, how to retrieve or extract data by using.
CS122 Using Relational Databases and SQL Huiping Guo Department of Computer Science California State University, Los Angeles 2. Single Table Queries.
Slide 1 of 32ASH-Training Querying and Managing Data Using SQL Server 2014 By: Segla In this session, you will learn to: Query data by using joins Query.
CS 122: Lecture 3 Joins (Part 1) Tarik Booker CS 122 California State University, Los Angeles October 7, 2014.
 MySQL  DDL ◦ Create ◦ Alter  DML ◦ Insert ◦ Select ◦ Update ◦ Delete  DDL(again) ◦ Drop ◦ Truncate.
Lecture 7: Subqueries Tarik Booker California State University, Los Angeles.
Tarik Booker CS 122. What we will cover… Tables (review) SELECT statement DISTINCT, Calculated Columns FROM Single tables (for now…) WHERE Date clauses,
Advanced SQL Advanced Database Dr. AlaaEddin Almabhouh.
Joins (Part II) Tarik Booker California State University, Los Angeles.
CS122 Using Relational Databases and SQL Huiping Guo Department of Computer Science California State University, Los Angeles 4. Subqueries and joins.
Using Subqueries to Solve Queries
CS3220 Web and Internet Programming More SQL
CS122 Using Relational Databases and SQL
Lyric Database Lyric Music
Subqueries Schedule: Timing Topic 25 minutes Lecture
CS122 Using Relational Databases and SQL
Displaying Data from Multiple Tables
03 | Querying Multiple Tables with Joins
SQL – Subqueries.
CS122 Using Relational Databases and SQL
David M. Kroenke and David J
JOINS (Joinining multiple tables)
CSC 453 Database Systems Lecture
CS122 Using Relational Databases and SQL
Putting it back together
CS122 Using Relational Databases and SQL
CS4222 Principles of Database System
CS122 Using Relational Databases and SQL
CS122 Using Relational Databases and SQL
CSC 453 Database Systems Lecture
CS122 Using Relational Databases and SQL
CS1222 Using Relational Databases and SQL
CS122 Using Relational Databases and SQL
Displaying Data from Multiple Tables
Displaying Data from Multiple Tables
Manipulating Data Lesson 3.
JOINS (Joinining multiple tables)
CS122 Using Relational Databases and SQL
Lyric Database Lyric Music
CS122 Using Relational Databases and SQL
Presentation transcript:

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

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

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

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

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

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 ---------- 1955-11-01 Query returns Lastname Firstname ------------------------- ------------------------- Wong Tony

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 276.08 SELECT tracktitle, lengthseconds FROM Tracks WHERE lengthseconds > 276.08 4. Subqueries and joins CS122_W2014

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

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

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

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 ----------- 1963-08-04 1959-06-22 1964-03-15 Select Lastname, Firstname, Region, Birthday From Members Where Birthday < ALL(Select Birthday From Members Where Region='GA') Lastname Firstname Region Birthday -------------------- ------------------ ---------- ------------ Ranier Brian ONT 1957-10-19 Kale Caroline VA 1956-05-30 Wong Tony ONT 1955-11-01 Cleaver Vic VT 1957-02-10 4. Subqueries and joins CS122_W2014

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

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

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

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

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

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

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

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

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

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

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

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

Cross Join Builds a Cartesian product Uses no ON keyword

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 ----------- ---------------------------- ----------- 1 The Neurotics 1 2 Louis Holiday 2 3 Word NULL 5 Sonata 5 10 The Bullets 10 14 Jose MacArthur NULL 15 Confused 15 17 The Kicks NULL 16 Today NULL 18 21 West Elm NULL 11 Highlander NULL 5. More joins CS122_W2014

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

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

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

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

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

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

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