SlideShare a Scribd company logo
Joins, views, and
subqueries
CMSC 461
Michael Wilson
Multi table selects
 So, we mentioned that we can refer to
multiple tables during the course of our
selects
 How do we do this?
 What does that do for us?
Joins
 We went over the natural join before
 There are actually a billion types of joins you
can explicitly state in ANSI SQL
 Okay, fine. There are 5 types.
 There are a lot of good images on the net
about this, but I’m uncomfortable with their
licensing terms, so I’m going to re-draw them
for you
Joining on
 Most joins require you to join “on” a particular
statement
 The statements are the same kind that are used
in WHERE clauses
 Table1.id = Table2.AddressBookId
 The PostgreSQL refers to this as the join
condition
Join types
 INNER JOIN
 FULL OUTER JOIN
 LEFT OUTER JOIN
 RIGHT OUTER JOIN
 CROSS JOIN
Inner join
 This is one of the more frequent types of joins
 Finds all rows which meet the join condition
 Example
 SELECT * FROM AddressBook a INNER JOIN
CallList c on a.id = c.addressBookId;
 a and c are aliases
Inner join
Left outer join
 Contains all records between T1 and T2 that
meet the join condition, and then any records
in T1 that don’t meet the join condition
 Rows for which the join condition is not met, the
columns of T2 are padded with nulls
Left outer join
Right outer join
 Contains all records between T1 and T2 that
meet the join condition, and then any records
in T2 that don’t meet the join condition
 Rows for which the join condition is not met, the
columns of T1 are padded with nulls
Right outer join
Full outer join
 Contains all records between T1 and T2 that
meet the join condition, and the combination
of a left outer join and right outer join are
appended onto the results
Full outer join
Cross join
 Cross joins have no join condition
 Cross joins literally return the Cartesian product
(discussed in the relational algebra slides)
Implicit join notation vs. explicit
 Inner joins can be accomplished with “implicit”
join notation
 In other words, we don’t literally use the terms
“inner join” in our select statement
 We can use where clauses/multi table selects to
accomplish the same thing
Explicit join
 SELECT * FROM AddressBook a INNER JOIN
CallList c on a.id = c.addressBookId;
Implicit join
 SELECT * FROM AddressBook a, CallList c
WHERE a.id = c.addressBookId;
Which to use?
 Which should you use?
 It’s up to you, really
 My experience
 I never really use explicit syntax
 Implicit makes much more sense to me,
personally
Outer joins, cross joins in the real
world?
 You can very much create a fully functional
database without using left outer joins, right
outer joins, etc.
 These types of joins allow you to collate data in
ways that would be require much more data
munging
 More queries, more tables
 Truth be told, I didn’t realize their power until
writing these slides
Examples
 Get a full list of employees and determine
who has not enrolled in benefits
 SELECT * FROM
employees LEFT OUTER JOIN
benefitsEnrollment ON employees.id =
benefitsEnrollment.employeeId;
 If an employee hasn’t enrolled in benefits, the
benefitsEnrollment columns would come back
as NULL
Views
 A view is kind of like a virtual table
 Views are defined as queries (SELECT
statements)
 They can be queried like tables
 They are read only
 Syntax:
 CREATE VIEW <view-name>
AS <query>
View example
 CREATE VIEW phoneNumbers
AS SELECT phoneNumber FROM
AddressBook;
 This would create a view that only contained
phone numbers from our AddressBook
More complex views
 CREATE VIEW callsAndInfo AS
SELECT * FROM AddressBook a INNER JOIN
CallList c on a.id = c.addressBookId;
 Views are more useful for more complex
queries
 Can join these views on other tables as well
View danger!
 Depending too heavily on views can cause
performance issues if you’re not careful
 You can apply constraints to view queries which
have a heavy performance impact
 If you have views that depend on views that
depend on views
Materialized views
 PostgreSQL has materialized views, which
are views that are stored on disk
 Periodically updated and stored
 Regular views are not stored, so they always hit
dependencies in real time
 Syntax:
 CREATE MATERIALIZED VIEW <view-name>
AS <query>
Subqueries
 You can use selects in your selects!
 This is SUPER confusing
 You can use them in both the FROM and the
WHERE
 Used in the from, kind of like in-lining a view
 Can use them in the where to grab values from
other tables
Subquery
 SELECT * FROM
Stalkers s,
(SELECT * FROM AddressBook a INNER
JOIN CallList c on a.id = c.addressBookId) c
WHERE s.contactName = c.contactName;
Using subqueries in a from
 SELECT * FROM UserProfile
WHERE userId = (SELECT userId FROM
MostPopularUser ORDER BY popularity
LIMIT 1);

More Related Content

Similar to 10-Joins, views, and subqueries.pptx

Something About Mysql Database Index
Something About Mysql Database IndexSomething About Mysql Database Index
Something About Mysql Database Index
dearhwj
 
SQL200.2 Module 2
SQL200.2 Module 2SQL200.2 Module 2
SQL200.2 Module 2
Dan D'Urso
 
SQL Introduction to displaying data from multiple tables
SQL Introduction to displaying data from multiple tables  SQL Introduction to displaying data from multiple tables
SQL Introduction to displaying data from multiple tables
Vibrant Technologies & Computers
 
SQL_Part1
SQL_Part1SQL_Part1
SQL_Part1
Rick Perry
 
Question 2B
Question 2BQuestion 2B
Question 2B
Stefanie Wong
 
Advance sqlite3
Advance sqlite3Advance sqlite3
Advance sqlite3
Raghu nath
 
15 questions sql advance
15 questions sql   advance15 questions sql   advance
15 questions sql advance
NaviSoft
 
Dbms interview questions
Dbms interview questionsDbms interview questions
Dbms interview questions
ambika93
 
18 database features
18 database features18 database features
18 database features
Rebecca Jones
 
Ejb4
Ejb4Ejb4
Steps towards of sql server developer
Steps towards of sql server developerSteps towards of sql server developer
Steps towards of sql server developer
Ahsan Kabir
 
Naming Standards, Clean Code
Naming Standards, Clean CodeNaming Standards, Clean Code
Naming Standards, Clean Code
CleanestCode
 
1. access
1. access1. access
Sql join
Sql  joinSql  join
Sql join
Vikas Gupta
 
Join sql
Join sqlJoin sql
Join sql
Vikas Gupta
 
Physical elements of data
Physical elements of dataPhysical elements of data
Physical elements of data
Dimara Hakim
 
Intro To TSQL - Unit 1
Intro To TSQL - Unit 1Intro To TSQL - Unit 1
Intro To TSQL - Unit 1
iccma
 
Les05
Les05Les05
Sql Commands
Sql CommandsSql Commands
Sql Commands
Sachin MK
 
Day-2 SQL Theory_V1.pptx
Day-2 SQL Theory_V1.pptxDay-2 SQL Theory_V1.pptx
Day-2 SQL Theory_V1.pptx
uzmasulthana3
 

Similar to 10-Joins, views, and subqueries.pptx (20)

Something About Mysql Database Index
Something About Mysql Database IndexSomething About Mysql Database Index
Something About Mysql Database Index
 
SQL200.2 Module 2
SQL200.2 Module 2SQL200.2 Module 2
SQL200.2 Module 2
 
SQL Introduction to displaying data from multiple tables
SQL Introduction to displaying data from multiple tables  SQL Introduction to displaying data from multiple tables
SQL Introduction to displaying data from multiple tables
 
SQL_Part1
SQL_Part1SQL_Part1
SQL_Part1
 
Question 2B
Question 2BQuestion 2B
Question 2B
 
Advance sqlite3
Advance sqlite3Advance sqlite3
Advance sqlite3
 
15 questions sql advance
15 questions sql   advance15 questions sql   advance
15 questions sql advance
 
Dbms interview questions
Dbms interview questionsDbms interview questions
Dbms interview questions
 
18 database features
18 database features18 database features
18 database features
 
Ejb4
Ejb4Ejb4
Ejb4
 
Steps towards of sql server developer
Steps towards of sql server developerSteps towards of sql server developer
Steps towards of sql server developer
 
Naming Standards, Clean Code
Naming Standards, Clean CodeNaming Standards, Clean Code
Naming Standards, Clean Code
 
1. access
1. access1. access
1. access
 
Sql join
Sql  joinSql  join
Sql join
 
Join sql
Join sqlJoin sql
Join sql
 
Physical elements of data
Physical elements of dataPhysical elements of data
Physical elements of data
 
Intro To TSQL - Unit 1
Intro To TSQL - Unit 1Intro To TSQL - Unit 1
Intro To TSQL - Unit 1
 
Les05
Les05Les05
Les05
 
Sql Commands
Sql CommandsSql Commands
Sql Commands
 
Day-2 SQL Theory_V1.pptx
Day-2 SQL Theory_V1.pptxDay-2 SQL Theory_V1.pptx
Day-2 SQL Theory_V1.pptx
 

Recently uploaded

Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
paigestewart1632
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
Celine George
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
Celine George
 
Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5
sayalidalavi006
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
simonomuemu
 

Recently uploaded (20)

Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
 
Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
 

10-Joins, views, and subqueries.pptx

  • 2. Multi table selects  So, we mentioned that we can refer to multiple tables during the course of our selects  How do we do this?  What does that do for us?
  • 3. Joins  We went over the natural join before  There are actually a billion types of joins you can explicitly state in ANSI SQL  Okay, fine. There are 5 types.  There are a lot of good images on the net about this, but I’m uncomfortable with their licensing terms, so I’m going to re-draw them for you
  • 4. Joining on  Most joins require you to join “on” a particular statement  The statements are the same kind that are used in WHERE clauses  Table1.id = Table2.AddressBookId  The PostgreSQL refers to this as the join condition
  • 5. Join types  INNER JOIN  FULL OUTER JOIN  LEFT OUTER JOIN  RIGHT OUTER JOIN  CROSS JOIN
  • 6. Inner join  This is one of the more frequent types of joins  Finds all rows which meet the join condition  Example  SELECT * FROM AddressBook a INNER JOIN CallList c on a.id = c.addressBookId;  a and c are aliases
  • 8. Left outer join  Contains all records between T1 and T2 that meet the join condition, and then any records in T1 that don’t meet the join condition  Rows for which the join condition is not met, the columns of T2 are padded with nulls
  • 10. Right outer join  Contains all records between T1 and T2 that meet the join condition, and then any records in T2 that don’t meet the join condition  Rows for which the join condition is not met, the columns of T1 are padded with nulls
  • 12. Full outer join  Contains all records between T1 and T2 that meet the join condition, and the combination of a left outer join and right outer join are appended onto the results
  • 14. Cross join  Cross joins have no join condition  Cross joins literally return the Cartesian product (discussed in the relational algebra slides)
  • 15. Implicit join notation vs. explicit  Inner joins can be accomplished with “implicit” join notation  In other words, we don’t literally use the terms “inner join” in our select statement  We can use where clauses/multi table selects to accomplish the same thing
  • 16. Explicit join  SELECT * FROM AddressBook a INNER JOIN CallList c on a.id = c.addressBookId;
  • 17. Implicit join  SELECT * FROM AddressBook a, CallList c WHERE a.id = c.addressBookId;
  • 18. Which to use?  Which should you use?  It’s up to you, really  My experience  I never really use explicit syntax  Implicit makes much more sense to me, personally
  • 19. Outer joins, cross joins in the real world?  You can very much create a fully functional database without using left outer joins, right outer joins, etc.  These types of joins allow you to collate data in ways that would be require much more data munging  More queries, more tables  Truth be told, I didn’t realize their power until writing these slides
  • 20. Examples  Get a full list of employees and determine who has not enrolled in benefits  SELECT * FROM employees LEFT OUTER JOIN benefitsEnrollment ON employees.id = benefitsEnrollment.employeeId;  If an employee hasn’t enrolled in benefits, the benefitsEnrollment columns would come back as NULL
  • 21. Views  A view is kind of like a virtual table  Views are defined as queries (SELECT statements)  They can be queried like tables  They are read only  Syntax:  CREATE VIEW <view-name> AS <query>
  • 22. View example  CREATE VIEW phoneNumbers AS SELECT phoneNumber FROM AddressBook;  This would create a view that only contained phone numbers from our AddressBook
  • 23. More complex views  CREATE VIEW callsAndInfo AS SELECT * FROM AddressBook a INNER JOIN CallList c on a.id = c.addressBookId;  Views are more useful for more complex queries  Can join these views on other tables as well
  • 24. View danger!  Depending too heavily on views can cause performance issues if you’re not careful  You can apply constraints to view queries which have a heavy performance impact  If you have views that depend on views that depend on views
  • 25. Materialized views  PostgreSQL has materialized views, which are views that are stored on disk  Periodically updated and stored  Regular views are not stored, so they always hit dependencies in real time  Syntax:  CREATE MATERIALIZED VIEW <view-name> AS <query>
  • 26. Subqueries  You can use selects in your selects!  This is SUPER confusing  You can use them in both the FROM and the WHERE  Used in the from, kind of like in-lining a view  Can use them in the where to grab values from other tables
  • 27. Subquery  SELECT * FROM Stalkers s, (SELECT * FROM AddressBook a INNER JOIN CallList c on a.id = c.addressBookId) c WHERE s.contactName = c.contactName;
  • 28. Using subqueries in a from  SELECT * FROM UserProfile WHERE userId = (SELECT userId FROM MostPopularUser ORDER BY popularity LIMIT 1);