Presentation is loading. Please wait.

Presentation is loading. Please wait.

Module 4: Joining Data from Multiple Tables. Querying Multiple Tables by Using Joins Applying Joins for Typical Reporting Needs Combining and Limiting.

Similar presentations


Presentation on theme: "Module 4: Joining Data from Multiple Tables. Querying Multiple Tables by Using Joins Applying Joins for Typical Reporting Needs Combining and Limiting."— Presentation transcript:

1 Module 4: Joining Data from Multiple Tables

2 Querying Multiple Tables by Using Joins Applying Joins for Typical Reporting Needs Combining and Limiting Result Sets

3 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

4 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)] 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

5 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

6 Joining Data Using Inner Joins SELECT e.LoginID FROM HumanResources.Employee AS e INNER JOIN Sales.SalesPerson AS s ON e.BusinessEntityID = s.BusinessEntityID SELECT e.LoginID FROM HumanResources.Employee AS e INNER JOIN Sales.SalesPerson AS s ON e.BusinessEntityID = s.BusinessEntityID LoginID ------------------------- adventure-works\syed0 adventure-works\david8 adventure-works\garrett1... (17 row(s) affected) LoginID ------------------------- adventure-works\syed0 adventure-works\david8 adventure-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:

7 Joining Data Using Outer Joins SELECT p.Name, pr.ProductReviewID FROM Production.Product p LEFT OUTER JOIN Production.ProductReview pr ON p.ProductID = pr.ProductID SELECT p.Name, pr.ProductReviewID FROM Production.Product p LEFT OUTER JOIN Production.ProductReview pr ON 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 NULL Bearing Ball NULL... (505 row(s) affected) Name ProductReviewID ---------------------------------- Adjustable Race NULL Bearing Ball NULL... (505 row(s) affected) Example: Result Set:

8 Joining Data Using Cross Joins SELECT p.BusinessEntityID, t.Name AS Territory FROM Sales.SalesPerson p CROSS JOIN Sales.SalesTerritory t ORDER BY p.BusinessEntityID SELECT p.BusinessEntityID, t.Name AS Territory FROM Sales.SalesPerson p CROSS JOIN Sales.SalesTerritory t ORDER 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 Northwest 274 Northeast... (170 row(s) affected) BusinessEntityID Territory ---------------------------- 274 Northwest 274 Northeast... (170 row(s) affected) Example: Result Set: Use CROSS JOINs with caution if you do not need a true Cartesian Product

9 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!

10 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

11 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

12 Joining Three or More Tables SELECT p.Name, v.Name FROM Production.Product p JOIN Purchasing.ProductVendor pv ON p.ProductID = pv.ProductID JOIN Purchasing.Vendor v ON pv.BusinesEntityID = v.BusinessEntityID WHERE ProductSubcategoryID = 15 ORDER BY v.Name SELECT p.Name, v.Name FROM Production.Product p JOIN Purchasing.ProductVendor pv ON p.ProductID = pv.ProductID JOIN Purchasing.Vendor v ON pv.BusinesEntityID = v.BusinessEntityID WHERE ProductSubcategoryID = 15 ORDER BY v.Name Example: FROM clauses can contain multiple Join specifications which allows many tables to be joined in a single Query Name ----------------------------------------------- LL Mountain Seat/Saddle Chicago City Saddles ML Mountain Seat/Saddle Chicago City Saddles... (18 row(s) affected) Name ----------------------------------------------- LL Mountain Seat/Saddle Chicago City Saddles ML Mountain Seat/Saddle Chicago City Saddles... (18 row(s) affected) Result Set:

13 Joining a Table to Itself SELECT DISTINCT pv1.ProductID, pv1.BusinessEntityID FROM Purchasing.ProductVendor pv1 INNER JOIN Purchasing.ProductVendor pv2 ON pv1.ProductID = pv2.ProductID AND pv1.BusinessEntityID <> pv2.BusinessEntityID ORDER BY pv1.ProductID SELECT DISTINCT pv1.ProductID, pv1.BusinessEntityID FROM Purchasing.ProductVendor pv1 INNER JOIN Purchasing.ProductVendor pv2 ON pv1.ProductID = pv2.ProductID AND pv1.BusinessEntityID <> pv2.BusinessEntityID ORDER BY pv1.ProductID A Table can be Joined to itself by using a Self-Join ProductID BusinessEntityID ------------------------------ 317 1578 317 1678... (347 row(s) affected) ProductID BusinessEntityID ------------------------------ 317 1578 317 1678... (347 row(s) affected) Result Set: Example:

14 Joining Tables by Using Non-Equi Joins SELECT DISTINCT p1.ProductSubcategoryID, p1.ListPrice FROM Production.Product p1 INNER JOIN Production.Product p2 ON p1.ProductSubcateogoryID = p2.ProductSubcategoryID AND p1.ListPrice <> p2.ListPrice WHERE p1.ListPrice < $15 AND p2.ListPrice < $15 ORDER BY ProductSubcategoryID SELECT DISTINCT p1.ProductSubcategoryID, p1.ListPrice FROM Production.Product p1 INNER JOIN Production.Product p2 ON p1.ProductSubcateogoryID = p2.ProductSubcategoryID AND p1.ListPrice <> p2.ListPrice WHERE p1.ListPrice < $15 AND p2.ListPrice < $15 ORDER BY ProductSubcategoryID The same Operators and Predicates used for Inner Joins can be used for Not-Equal Joins Example: ProductSubcateogoryID ListPrice ----------------------------------- 23 8.99 23 9.50... (8 row(s) affected) ProductSubcateogoryID ListPrice ----------------------------------- 23 8.99 23 9.50... (8 row(s) affected) Result Set:

15 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.250910 708 Sport-100 Helmet, Black 657.636610 Product ID Name YTD Total ------------------------------------------------ 707 Sport-100 Helmet, Red 620.250910 708 Sport-100 Helmet, Black 657.636610 Example: Result Set:

16 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

17 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

18 Combining Result Sets by Using the UNION Operator SELECT * FROM testa UNION ALL SELECT * FROM testb; SELECT * FROM testa UNION ALL SELECT * 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 test... (8 row(s) affected) columna columnb ------------------ 100 test... (8 row(s) affected) Result Set:

19 Limiting Result Sets by Using the EXCEPT and INTERSECT Operators SELECT ProductID FROM Production.Product EXCEPT SELECT ProductID FROM Production.WorkOrder SELECT ProductID FROM Production.Product EXCEPT SELECT ProductID FROM Production.WorkOrder SELECT ProductID FROM Production.Product INTERSECT SELECT ProductID FROM Production.WorkOrder SELECT ProductID FROM Production.Product INTERSECT SELECT 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

20 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 1 1 The INTERSECT operand 2 2 EXCEPT and UNION evaluated from Left to Right based on their position in the expression 3 3

21 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.Person TABLESAMPLE (1 PERCENT) SELECT FirstName, LastName FROM Person.Person TABLESAMPLE (1 PERCENT) FirstName LastName -------------------- Syed Abbas Catherine Abel... (15 row(s) affected) FirstName LastName -------------------- Syed Abbas Catherine Abel... (15 row(s) affected) FirstName LastName -------------------- Eduardo Barnes Edward Barnes... (199 row(s) affected) FirstName LastName -------------------- Eduardo Barnes Edward Barnes... (199 row(s) affected) TOP Example: TABLESAMPLE Example: Result Sets

22 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

23 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

24 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 machineNY-SQL-01 User nameAdministrator Password Pa$$w0rd Estimated time: 60 minutes

25 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.

26 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?

27 Module Review and Takeaways Review Questions Best Practices

28 Notes Page Over-flow Slide. Do Not Print Slide. See Notes pane.


Download ppt "Module 4: Joining Data from Multiple Tables. Querying Multiple Tables by Using Joins Applying Joins for Typical Reporting Needs Combining and Limiting."

Similar presentations


Ads by Google