SlideShare a Scribd company logo
1 of 28
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 Indexdearhwj
 
SQL200.2 Module 2
SQL200.2 Module 2SQL200.2 Module 2
SQL200.2 Module 2Dan D'Urso
 
Advance sqlite3
Advance sqlite3Advance sqlite3
Advance sqlite3Raghu nath
 
15 questions sql advance
15 questions sql   advance15 questions sql   advance
15 questions sql advanceNaviSoft
 
Dbms interview questions
Dbms interview questionsDbms interview questions
Dbms interview questionsambika93
 
18 database features
18 database features18 database features
18 database featuresRebecca Jones
 
Steps towards of sql server developer
Steps towards of sql server developerSteps towards of sql server developer
Steps towards of sql server developerAhsan Kabir
 
Naming Standards, Clean Code
Naming Standards, Clean CodeNaming Standards, Clean Code
Naming Standards, Clean CodeCleanestCode
 
Physical elements of data
Physical elements of dataPhysical elements of data
Physical elements of dataDimara Hakim
 
Intro To TSQL - Unit 1
Intro To TSQL - Unit 1Intro To TSQL - Unit 1
Intro To TSQL - Unit 1iccma
 
Sql Commands
Sql CommandsSql Commands
Sql CommandsSachin MK
 
Day-2 SQL Theory_V1.pptx
Day-2 SQL Theory_V1.pptxDay-2 SQL Theory_V1.pptx
Day-2 SQL Theory_V1.pptxuzmasulthana3
 

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

UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024Borja Sotomayor
 
Trauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical PrinciplesTrauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical PrinciplesPooky Knightsmith
 
Book Review of Run For Your Life Powerpoint
Book Review of Run For Your Life PowerpointBook Review of Run For Your Life Powerpoint
Book Review of Run For Your Life Powerpoint23600690
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxAdelaideRefugio
 
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinhĐề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinhleson0603
 
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxAnalyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxLimon Prince
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...Nguyen Thanh Tu Collection
 
Graduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxGraduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxneillewis46
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismDabee Kamal
 
e-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopale-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi RajagopalEADTU
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...Gary Wood
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital ManagementMBA Assignment Experts
 
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMDEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMELOISARIVERA8
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesAmanpreetKaur157993
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...Nguyen Thanh Tu Collection
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文中 央社
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project researchCaitlinCummins3
 

Recently uploaded (20)

UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024
 
Trauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical PrinciplesTrauma-Informed Leadership - Five Practical Principles
Trauma-Informed Leadership - Five Practical Principles
 
Book Review of Run For Your Life Powerpoint
Book Review of Run For Your Life PowerpointBook Review of Run For Your Life Powerpoint
Book Review of Run For Your Life Powerpoint
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptx
 
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinhĐề tieng anh thpt 2024 danh cho cac ban hoc sinh
Đề tieng anh thpt 2024 danh cho cac ban hoc sinh
 
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptxAnalyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
Analyzing and resolving a communication crisis in Dhaka textiles LTD.pptx
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 
Graduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptxGraduate Outcomes Presentation Slides - English (v3).pptx
Graduate Outcomes Presentation Slides - English (v3).pptx
 
An overview of the various scriptures in Hinduism
An overview of the various scriptures in HinduismAn overview of the various scriptures in Hinduism
An overview of the various scriptures in Hinduism
 
Supporting Newcomer Multilingual Learners
Supporting Newcomer  Multilingual LearnersSupporting Newcomer  Multilingual Learners
Supporting Newcomer Multilingual Learners
 
e-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopale-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopal
 
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...When Quality Assurance Meets Innovation in Higher Education - Report launch w...
When Quality Assurance Meets Innovation in Higher Education - Report launch w...
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMDEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
 
Major project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategiesMajor project report on Tata Motors and its marketing strategies
Major project report on Tata Motors and its marketing strategies
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
24 ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH SỞ GIÁO DỤC HẢI DƯ...
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project research
 

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);