SlideShare a Scribd company logo
1 of 14
03 | Querying Multiple Tables with Joins
Graeme Malcolm | Senior Content Developer, Microsoft
Geoff Allix | Principal Technologist, Content Master
• Join Concepts
• Join Syntax
• Inner Joins
• Outer Joins
• Cross Joins
• Self Joins
Module Overview
Join Concepts
• Combine rows from multiple tables by specifying matching
criteria
– Usually based on primary key – foreign key relationships
– For example, return rows that combine data from the Employee and
SalesOrder tables by matching the Employee.EmployeeID primary key
to the SalesOrder.EmployeeID foreign key
• It helps to think of the tables as sets in a Venn diagram
Employee SalesOrder
Sales orders
that were
taken by
employees
Join Syntax
• ANSI SQL-92
• Tables joined by JOIN operator in FROM Clause
• Preferred syntax
• ANSI SQL-89
• Tables joined by commas in FROM Clause
• Not recommended: Accidental Cartesian products!
SELECT ...
FROM Table1 JOIN Table2
ON <on_predicate>;
SELECT ...
FROM Table1, Table2
WHERE <where_predicate>;
Inner Joins
• Return only rows where a match is found in both input tables
• Match rows based on attributes supplied in predicate
• If join predicate operator is =, also known as equi-join
Employee SalesOrder
Set returned
by inner join
SELECT emp.FirstName, ord.Amount
FROM HR.Employee AS emp
[INNER] JOIN Sales.SalesOrder AS ord
ON emp.EmployeeID = ord.EmployeeID
DEMO
Using Inner Joins
Outer Joins
• Return all rows from one table and any
matching rows from second table
• One table’s rows are “preserved”
– Designated with LEFT, RIGHT, FULL keyword
– All rows from preserved table output to result set
• Matches from other table retrieved
• Additional rows added to results for non-
matched rows
– NULLs added in places where attributes do not
match
• Example: Return all employees and for those
who have taken orders, return the order
amount. Employees without matching orders
will display NULL for order amount.
Employee SalesOrder
Set returned
by left outer
join
SELECT emp.FirstName, ord.Amount
FROM HR.Employee AS emp
LEFT [OUTER] JOIN Sales.SalesOrder AS ord
ON emp.EmployeeID = ord.EmployeeID;
DEMO
Using Outer Joins
Cross Joins
• Combine each row from first table with each
row from second table
• All possible combinations output
• Logical foundation for inner and outer joins
– Inner join starts with Cartesian product, adds filter
– Outer join takes Cartesian output, filtered, adds
back non-matching rows (with NULL
placeholders)
• Due to Cartesian product output, not
typically a desired form of join
– Some useful exceptions:
• Table of numbers, generating data for testing
Employee
EmployeeID FirstName
1 Dan
2 Aisha
Product
ProductID Name
1 Widget
2 Gizmo
Result
FirstName Name
Dan Widget
Dan Gizmo
Aisha Widget
Aisha Gizmo
SELECT emp.FirstName, prd.Name
FROM HR.Employee AS emp
CROSS JOIN Production.Product AS prd;
DEMO
Using Cross Joins
Self Joins
• Compare rows in same table to each
other
• Create two instances of same table
in FROM clause
– At least one alias required
• Example: Return all employees and
the name of the employee’s
manager
Employee
EmployeeID FirstName ManagerID
1 Dan NULL
2 Aisha 1
3 Rosie 1
4 Naomi 3
Result
Employee Manager
Dan NULL
Aisha Dan
Rosie Dan
Naomi Aisha
SELECT emp.FirstName AS Employee,
man.FirstName AS Manager
FROM HR.Employee AS emp
LEFT JOIN HR.Employee AS man
ON emp.ManagerID = man.EmployeeID;
DEMO
Using Self Joins
Querying Multiple Tables with Joins
• Join Concepts
• Join Syntax
• Inner Joins
• Outer Joins
• Cross Joins
• Self Joins
• Lab: Querying Multiple Tables with Joins
©2014 Microsoft Corporation. All rights reserved. Microsoft, Windows, Office, Azure, System Center, Dynamics and other product names are or may be registered trademarks and/or trademarks in the
U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft
must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after
the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

More Related Content

Similar to Querying_with_T-SQL_-_03.pptx

Similar to Querying_with_T-SQL_-_03.pptx (20)

Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)Database Systems - SQL - DDL Statements (Chapter 3/3)
Database Systems - SQL - DDL Statements (Chapter 3/3)
 
Statements,joins and operators in sql by thanveer danish melayi(1)
Statements,joins and operators in sql by thanveer danish melayi(1)Statements,joins and operators in sql by thanveer danish melayi(1)
Statements,joins and operators in sql by thanveer danish melayi(1)
 
Views, Triggers, Functions, Stored Procedures, Indexing and Joins
Views, Triggers, Functions, Stored Procedures,  Indexing and JoinsViews, Triggers, Functions, Stored Procedures,  Indexing and Joins
Views, Triggers, Functions, Stored Procedures, Indexing and Joins
 
0808.pdf
0808.pdf0808.pdf
0808.pdf
 
0808.pdf
0808.pdf0808.pdf
0808.pdf
 
Oracle Course
Oracle CourseOracle Course
Oracle Course
 
PL_SQL - II.pptx
PL_SQL - II.pptxPL_SQL - II.pptx
PL_SQL - II.pptx
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
Sql server
Sql serverSql server
Sql server
 
SQL200.2 Module 2
SQL200.2 Module 2SQL200.2 Module 2
SQL200.2 Module 2
 
MS SQL Server
MS SQL ServerMS SQL Server
MS SQL Server
 
OracleSQLraining.pptx
OracleSQLraining.pptxOracleSQLraining.pptx
OracleSQLraining.pptx
 
Aggregate functions in SQL.pptx
Aggregate functions in SQL.pptxAggregate functions in SQL.pptx
Aggregate functions in SQL.pptx
 
MS SQL Server.ppt
MS SQL Server.pptMS SQL Server.ppt
MS SQL Server.ppt
 
Module 3 design and implementing tables
Module 3 design and implementing tablesModule 3 design and implementing tables
Module 3 design and implementing tables
 
Interacting with Oracle Database
Interacting with Oracle DatabaseInteracting with Oracle Database
Interacting with Oracle Database
 
Sql server 2016 queries
Sql server 2016 queriesSql server 2016 queries
Sql server 2016 queries
 
5. relational structure
5. relational structure5. relational structure
5. relational structure
 
Sql server introduction to sql server
Sql server introduction to sql server Sql server introduction to sql server
Sql server introduction to sql server
 
Data Retrival
Data RetrivalData Retrival
Data Retrival
 

Recently uploaded

Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxAnaBeatriceAblay2
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 

Recently uploaded (20)

Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 

Querying_with_T-SQL_-_03.pptx

  • 1. 03 | Querying Multiple Tables with Joins Graeme Malcolm | Senior Content Developer, Microsoft Geoff Allix | Principal Technologist, Content Master
  • 2. • Join Concepts • Join Syntax • Inner Joins • Outer Joins • Cross Joins • Self Joins Module Overview
  • 3. Join Concepts • Combine rows from multiple tables by specifying matching criteria – Usually based on primary key – foreign key relationships – For example, return rows that combine data from the Employee and SalesOrder tables by matching the Employee.EmployeeID primary key to the SalesOrder.EmployeeID foreign key • It helps to think of the tables as sets in a Venn diagram Employee SalesOrder Sales orders that were taken by employees
  • 4. Join Syntax • ANSI SQL-92 • Tables joined by JOIN operator in FROM Clause • Preferred syntax • ANSI SQL-89 • Tables joined by commas in FROM Clause • Not recommended: Accidental Cartesian products! SELECT ... FROM Table1 JOIN Table2 ON <on_predicate>; SELECT ... FROM Table1, Table2 WHERE <where_predicate>;
  • 5. Inner Joins • Return only rows where a match is found in both input tables • Match rows based on attributes supplied in predicate • If join predicate operator is =, also known as equi-join Employee SalesOrder Set returned by inner join SELECT emp.FirstName, ord.Amount FROM HR.Employee AS emp [INNER] JOIN Sales.SalesOrder AS ord ON emp.EmployeeID = ord.EmployeeID
  • 7. Outer Joins • Return all rows from one table and any matching rows from second table • One table’s rows are “preserved” – Designated with LEFT, RIGHT, FULL keyword – All rows from preserved table output to result set • Matches from other table retrieved • Additional rows added to results for non- matched rows – NULLs added in places where attributes do not match • Example: Return all employees and for those who have taken orders, return the order amount. Employees without matching orders will display NULL for order amount. Employee SalesOrder Set returned by left outer join SELECT emp.FirstName, ord.Amount FROM HR.Employee AS emp LEFT [OUTER] JOIN Sales.SalesOrder AS ord ON emp.EmployeeID = ord.EmployeeID;
  • 9. Cross Joins • Combine each row from first table with each row from second table • All possible combinations output • Logical foundation for inner and outer joins – Inner join starts with Cartesian product, adds filter – Outer join takes Cartesian output, filtered, adds back non-matching rows (with NULL placeholders) • Due to Cartesian product output, not typically a desired form of join – Some useful exceptions: • Table of numbers, generating data for testing Employee EmployeeID FirstName 1 Dan 2 Aisha Product ProductID Name 1 Widget 2 Gizmo Result FirstName Name Dan Widget Dan Gizmo Aisha Widget Aisha Gizmo SELECT emp.FirstName, prd.Name FROM HR.Employee AS emp CROSS JOIN Production.Product AS prd;
  • 11. Self Joins • Compare rows in same table to each other • Create two instances of same table in FROM clause – At least one alias required • Example: Return all employees and the name of the employee’s manager Employee EmployeeID FirstName ManagerID 1 Dan NULL 2 Aisha 1 3 Rosie 1 4 Naomi 3 Result Employee Manager Dan NULL Aisha Dan Rosie Dan Naomi Aisha SELECT emp.FirstName AS Employee, man.FirstName AS Manager FROM HR.Employee AS emp LEFT JOIN HR.Employee AS man ON emp.ManagerID = man.EmployeeID;
  • 13. Querying Multiple Tables with Joins • Join Concepts • Join Syntax • Inner Joins • Outer Joins • Cross Joins • Self Joins • Lab: Querying Multiple Tables with Joins
  • 14. ©2014 Microsoft Corporation. All rights reserved. Microsoft, Windows, Office, Azure, System Center, Dynamics and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Editor's Notes

  1. 1