module 4: joining data from multiple tables. querying multiple tables by using joins applying joins...
TRANSCRIPT
Module 4:Joining Data from
Multiple Tables
Module 4: Joining Data from Multiple Tables
• Querying Multiple Tables by Using Joins
• Applying Joins for Typical Reporting Needs
• Combining and Limiting Result Sets
Lesson 1: Querying Multiple Tables by Using Joins
• Fundamentals of Joins
• Categorizing Statements by Types of Joins
• Joining Data Using Inner Joins
• Joining Data Using Outer Joins
• Joining Data Using Cross Joins
• Identifying the Potential Impact of a Cartesian Product
Fundamentals of Joins
• Select Specific Columns from Multiple Tables• JOIN keyword specifies that tables are joined and how
to join them
• ON keyword specifies join condition
FROM first_table join_type second_table [ON (join_condition)]FROM first_table join_type second_table [ON (join_condition)]
Joins:
Simplified JOIN Syntax:
• Query Two or More Tables to Produce a Result Set• Use Primary and Foreign Keys as join conditions
• Use columns common to specified tables to join tables
Categorizing Statements by Types of Joins
• Inner Join
Includes equi-joins and natural joins
Use comparison operators to match rows
• Outer Join
Includes left, right, or full outer joins
• Cross Join
Also called Cartesian products
• Self Join
Refers to any join used to join a table to itself
Joining Data Using Inner Joins
SELECT e.LoginIDFROM HumanResources.Employee AS e INNER JOIN Sales.SalesPerson AS s ON e.BusinessEntityID = s.BusinessEntityID
SELECT e.LoginIDFROM HumanResources.Employee AS e INNER JOIN Sales.SalesPerson AS s ON e.BusinessEntityID = s.BusinessEntityID
LoginID-------------------------adventure-works\syed0adventure-works\david8adventure-works\garrett1...(17 row(s) affected)
LoginID-------------------------adventure-works\syed0adventure-works\david8adventure-works\garrett1...(17 row(s) affected)
• An inner join is a join in which the values in the columns being joined are compared using a comparison operator
Result Set:
Example:
Joining Data Using Outer Joins
SELECT p.Name, pr.ProductReviewIDFROM Production.Product pLEFT OUTER JOIN Production.ProductReview prON p.ProductID = pr.ProductID
SELECT p.Name, pr.ProductReviewIDFROM Production.Product pLEFT OUTER JOIN Production.ProductReview prON p.ProductID = pr.ProductID
• Outer Joins return all rows from at least one of the tables or views mentioned in the FROM clause
Name ProductReviewID----------------------------------Adjustable Race NULLBearing Ball NULL...(505 row(s) affected)
Name ProductReviewID----------------------------------Adjustable Race NULLBearing Ball NULL...(505 row(s) affected)
Example:
Result Set:
Joining Data Using Cross Joins
SELECT p.BusinessEntityID, t.Name AS TerritoryFROM Sales.SalesPerson pCROSS JOIN Sales.SalesTerritory tORDER BY p.BusinessEntityID
SELECT p.BusinessEntityID, t.Name AS TerritoryFROM Sales.SalesPerson pCROSS JOIN Sales.SalesTerritory tORDER BY p.BusinessEntityID
• In a Cross Join, each row from the left table is combined with all rows from the right table
BusinessEntityID Territory----------------------------274 Northwest274 Northeast...(170 row(s) affected)
BusinessEntityID Territory----------------------------274 Northwest274 Northeast...(170 row(s) affected)
Example:
Result Set:
Use CROSS JOINs with caution if you do not need a true Cartesian ProductUse CROSS JOINs with caution if you do not need a true Cartesian Product
Identifying the Potential Impact of a Cartesian Product
• Is defined as all possible combinations of rows in all tables
A Cartesian Product:
• Results in a rowset containing the number of rows in the first table times the number of rows in the second
• Can result in huge result sets that take several hours to complete!
Demonstration: Querying a Table Using Joins
In this demonstration, you will see how to:
• Query the Table Using an Inner Join
• Query the Table Using an Outer Join
• Query the Table Using a Cross Join
Lesson 2: Applying Joins for Typical Reporting Needs
• Joining Three or More Tables
• Joining a Table to Itself
• Joining Tables by Using Non-Equi Joins
• Joining Tables in a User-Defined Function
Joining Three or More Tables
SELECT p.Name, v.NameFROM Production.Product pJOIN Purchasing.ProductVendor pvON p.ProductID = pv.ProductIDJOIN Purchasing.Vendor vON pv.BusinesEntityID = v.BusinessEntityIDWHERE ProductSubcategoryID = 15ORDER BY v.Name
SELECT p.Name, v.NameFROM Production.Product pJOIN Purchasing.ProductVendor pvON p.ProductID = pv.ProductIDJOIN Purchasing.Vendor vON pv.BusinesEntityID = v.BusinessEntityIDWHERE ProductSubcategoryID = 15ORDER BY v.Name
Example:
• FROM clauses can contain multiple Join specifications which allows many tables to be joined in a single Query
Name Name-----------------------------------------------LL Mountain Seat/Saddle Chicago City SaddlesML Mountain Seat/Saddle Chicago City Saddles...(18 row(s) affected)
Name Name-----------------------------------------------LL Mountain Seat/Saddle Chicago City SaddlesML Mountain Seat/Saddle Chicago City Saddles...(18 row(s) affected)
Result Set:
Joining a Table to Itself
SELECT DISTINCT pv1.ProductID, pv1.BusinessEntityIDFROM Purchasing.ProductVendor pv1INNER JOIN Purchasing.ProductVendor pv2ON pv1.ProductID = pv2.ProductID AND pv1.BusinessEntityID <> pv2.BusinessEntityIDORDER BY pv1.ProductID
SELECT DISTINCT pv1.ProductID, pv1.BusinessEntityIDFROM Purchasing.ProductVendor pv1INNER JOIN Purchasing.ProductVendor pv2ON pv1.ProductID = pv2.ProductID AND pv1.BusinessEntityID <> pv2.BusinessEntityIDORDER BY pv1.ProductID
• A Table can be Joined to itself by using a Self-Join
ProductID BusinessEntityID------------------------------317 1578317 1678...(347 row(s) affected)
ProductID BusinessEntityID------------------------------317 1578317 1678...(347 row(s) affected)
Result Set:
Example:
Joining Tables by Using Non-Equi Joins
SELECT DISTINCT p1.ProductSubcategoryID, p1.ListPriceFROM Production.Product p1 INNER JOIN Production.Product p2 ON p1.ProductSubcateogoryID = p2.ProductSubcategoryID AND p1.ListPrice <> p2.ListPriceWHERE p1.ListPrice < $15 AND p2.ListPrice < $15ORDER BY ProductSubcategoryID
SELECT DISTINCT p1.ProductSubcategoryID, p1.ListPriceFROM Production.Product p1 INNER JOIN Production.Product p2 ON p1.ProductSubcateogoryID = p2.ProductSubcategoryID AND p1.ListPrice <> p2.ListPriceWHERE p1.ListPrice < $15 AND p2.ListPrice < $15ORDER BY ProductSubcategoryID
• The same Operators and Predicates used for Inner Joins can be used for Not-Equal Joins
Example:
ProductSubcateogoryID ListPrice-----------------------------------23 8.9923 9.50...(8 row(s) affected)
ProductSubcateogoryID ListPrice-----------------------------------23 8.9923 9.50...(8 row(s) affected)
Result Set:
SELECT * FROM Sales.ufn_SalesByStore (29825)SELECT * FROM Sales.ufn_SalesByStore (29825)
Joining Tables in a User-Defined Function
CREATE FUNCTION Sales.ufn_SalesByStore (@storeid int)RETURNS TABLE AS RETURN ( SELECT P.ProductID, P.Name, SUM(SD.LineTotal) AS 'YTD Total‘ FROM Production.Product AS P JOIN Sales.SalesOrderDetail AS SD ON SD.ProductID = P.ProductID JOIN Sales.SalesOrderHeader AS SH ON SH.SalesOrderID = SD.SalesOrderID WHERE SH.CustomerID = @storeid GROUP BY P.ProductID, P.Name );
CREATE FUNCTION Sales.ufn_SalesByStore (@storeid int)RETURNS TABLE AS RETURN ( SELECT P.ProductID, P.Name, SUM(SD.LineTotal) AS 'YTD Total‘ FROM Production.Product AS P JOIN Sales.SalesOrderDetail AS SD ON SD.ProductID = P.ProductID JOIN Sales.SalesOrderHeader AS SH ON SH.SalesOrderID = SD.SalesOrderID WHERE SH.CustomerID = @storeid GROUP BY P.ProductID, P.Name );
• User-defined functions can be used to focus, simplify, and customize the perception each user has of the database
Product ID Name YTD Total------------------------------------------------707 Sport-100 Helmet, Red 620.250910708 Sport-100 Helmet, Black 657.636610
Product ID Name YTD Total------------------------------------------------707 Sport-100 Helmet, Red 620.250910708 Sport-100 Helmet, Black 657.636610
Example:
Result Set:
Demonstration: Joining Tables
In this demonstration, you will see how to:
• Join Three or More Tables
• Join a Table to Itself
• Join a Table using a Non-Equi Join
Lesson 3: Combining and Limiting Result Sets
• Combining Result Sets by Using the UNION Operator
• Limiting Result Sets by Using the EXCEPT and INTERSECT Operators
• Identifying the Order of Precedence of UNION, EXCEPT, and INTERSECT
• Limiting Result Sets by Using the TOP and TABLESAMPLE Operators
• Categorizing Statements that Limit Result Sets
Combining Result Sets by Using the UNION Operator
SELECT * FROM testaUNION ALLSELECT * FROM testb;
SELECT * FROM testaUNION ALLSELECT * FROM testb;
The number and order of columns must be the same
in all queries and all data types must be compatible
The number and order of columns must be the same
in all queries and all data types must be compatible
• UNION combines the results of two or more queries into a single result set that includes all the rows that belong to all queries in the union
Example:
columna columnb------------------100 test100 test...(8 row(s) affected)
columna columnb------------------100 test100 test...(8 row(s) affected)
Result Set:
Limiting Result Sets by Using the EXCEPT and INTERSECT Operators
SELECT ProductID FROM Production.ProductEXCEPTSELECT ProductID FROM Production.WorkOrder
SELECT ProductID FROM Production.ProductEXCEPTSELECT ProductID FROM Production.WorkOrder
SELECT ProductID FROM Production.ProductINTERSECTSELECT ProductID FROM Production.WorkOrder
SELECT ProductID FROM Production.ProductINTERSECTSELECT ProductID FROM Production.WorkOrder
• EXCEPT returns any distinct values from the query to the left of the EXCEPT operand that are not also returned from the right query
• INTERSECT returns any distinct values that are returned by both the query on the left and right sides of the INTERSECT operand
ProductID------------------429...(266 row(s) affected)
ProductID------------------429...(266 row(s) affected)
ProductID------------------3...(238 row(s) affected)
ProductID------------------3...(238 row(s) affected)
EXCEPT Example:
INTERSECT Example:
Result Sets
Identifying the Order of Precedence of UNION, EXCEPT, and INTERSECT
EXCEPT, INTERSECT, and UNION are evaluated in the context of the following precedence:
Expressions in parentheses 11
The INTERSECT operand 22
EXCEPT and UNION evaluated from Left to Right based on their position in the expression
33
Limiting Result Sets by Using the TOP and TABLESAMPLE Operators
• TOP and TABLESAMPLE limit the number of rows returned in a result set
SELECT TOP (15)FirstName, LastName
FROM Person.Person
SELECT TOP (15)FirstName, LastName
FROM Person.Person
SELECT FirstName, LastName
FROM Person.PersonTABLESAMPLE (1 PERCENT)
SELECT FirstName, LastName
FROM Person.PersonTABLESAMPLE (1 PERCENT)
FirstName LastName--------------------Syed AbbasCatherine Abel...(15 row(s) affected)
FirstName LastName--------------------Syed AbbasCatherine Abel...(15 row(s) affected)
FirstName LastName--------------------Eduardo BarnesEdward Barnes...(199 row(s) affected)
FirstName LastName--------------------Eduardo BarnesEdward Barnes...(199 row(s) affected)
TOP Example:
TABLESAMPLE Example:
Result Sets
Categorizing Statements That Limit Result Sets
• UNION
Combines the results of two or more SELECT statements into a single result set
• EXCEPT and INTERSECT
Compares the results of two or more SELECT statements and return distinct values
• TOP
Specifies that only the first set of rows will be returned from the query result
• TABLESAMPLE
Limits the number of rows returned from a table in the FROM clause to a sample number or PERCENT of rows
Demonstration: Combining and Limiting Result Sets
In this demonstration, you will see how to:
• Combine Result Sets
• Limit Result Sets using TABLESAMPLE
• Limit Result Sets using TOP
Lab: Joining Data from Multiple Tables
• Exercise 1: Querying Multiple Tables by Using Joins
• Exercise 2: Applying Joins for Typical Reporting Needs
• Exercise 3: Combining and Limiting Result Sets
Logon information
Virtual machine NY-SQL-01
User name Administrator
Password Pa$$w0rd
Estimated time: 60 minutes
Lab Scenario
•You are a database developer at Adventure Works. You have been asked by the various managers to prepare several reports for use in the quarterly financial statements being produced by the company. To create these reports you will use several different joins and join operators.
Lab Review
• What results did the Inner Join in Exercise 1 return?
• What results did the Left Outer Join and Right Outer Join in Exercise 1 return?
• Why was the ProductVendor table given two different table aliases in the FROM clause of Exercise 2?
• What would happen if we added an ORDER BY clause to the TOP select statement in Exercise 3?
Module Review and Takeaways
• Review Questions
• Best Practices