You are on page 1of 27

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
Joins:
Select Specific Columns from Multiple Tables
JOIN keyword specifies that tables are joined and how to join them

ON keyword specifies join condition

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

Simplified JOIN Syntax: FROM first_table join_type second_table [ON (join_condition)]

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


An inner join is a join in which the values in the columns being joined are compared using a comparison operator

Example:
SELECT e.LoginID FROM HumanResources.Employee AS e INNER JOIN Sales.SalesPerson AS s ON e.BusinessEntityID = s.BusinessEntityID

Result Set:
LoginID ------------------------adventure-works\syed0 adventure-works\david8 adventure-works\garrett1 ... (17 row(s) affected)

Joining Data Using Outer Joins


Outer Joins return all rows from at least one of the tables or views mentioned in the FROM clause

Example:
SELECT p.Name, pr.ProductReviewID FROM Production.Product p LEFT OUTER JOIN Production.ProductReview pr ON p.ProductID = pr.ProductID

Result Set:
Name ProductReviewID ---------------------------------Adjustable Race NULL Bearing Ball NULL ... (505 row(s) affected)

Joining Data Using Cross Joins


In a Cross Join, each row from the left table is combined with all rows from the right table

Example:
SELECT p.BusinessEntityID, t.Name AS Territory FROM Sales.SalesPerson p CROSS JOIN Sales.SalesTerritory t ORDER BY p.BusinessEntityID

Result Set:
BusinessEntityID Territory ---------------------------274 Northwest 274 Northeast ... (170 row(s) affected) Use CROSS JOINs with caution if you do not need a true Cartesian Product

Identifying the Potential Impact of a Cartesian Product


A Cartesian Product:

Is defined as all possible combinations of rows in all tables 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


FROM clauses can contain multiple Join specifications which allows many tables to be joined in a single Query

Example:
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

Result Set:
Name Name ----------------------------------------------LL Mountain Seat/Saddle Chicago City Saddles ML Mountain Seat/Saddle Chicago City Saddles ... (18 row(s) affected)

Joining a Table to Itself


A Table can be Joined to itself by using a Self-Join

Example:
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

Result Set:
ProductID BusinessEntityID -----------------------------317 1578 317 1678 ... (347 row(s) affected)

Joining Tables by Using Non-Equi Joins


The same Operators and Predicates used for Inner Joins can be used for Not-Equal Joins

Example:
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

Result Set:
ProductSubcateogoryID ListPrice ----------------------------------23 8.99 23 9.50 ... (8 row(s) affected)

Joining Tables in a User-Defined Function


User-defined functions can be used to focus, simplify, and customize the perception each user has of the database Example: 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 SELECT * FROM Sales.ufn_SalesByStore (29825) SD.ProductID = P.ProductID JOIN Sales.SalesOrderHeader AS SH ON SH.SalesOrderID = SD.SalesOrderID WHERE SH.CustomerID = @storeid GROUP BY P.ProductID, P.Name ); Result Set: Product ID Name YTD Total -----------------------------------------------707 Sport-100 Helmet, Red 620.250910 708 Sport-100 Helmet, Black 657.636610

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


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: SELECT * FROM testa UNION ALL SELECT * FROM testb;

Result Set:
columna columnb -----------------100 test 100 test ... (8 row(s) affected)

The number and order of columns must be the same in all queries and all data types must be compatible

Limiting Result Sets by Using the EXCEPT and INTERSECT Operators


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

EXCEPT Example:
SELECT ProductID FROM Production.Product EXCEPT SELECT ProductID FROM Production.WorkOrder

Result Sets
ProductID -----------------429 ... (266 row(s) affected)

INTERSECT Example:
SELECT ProductID FROM Production.Product INTERSECT SELECT ProductID FROM Production.WorkOrder
ProductID -----------------3 ... (238 row(s) affected)

Identifying the Order of Precedence of UNION, EXCEPT, and INTERSECT

EXCEPT, INTERSECT, and UNION are evaluated in the context of the following precedence:

1 2 3

Expressions in parentheses
The INTERSECT operand EXCEPT and UNION evaluated from Left to Right based on their position in the expression

Limiting Result Sets by Using the TOP and TABLESAMPLE Operators


TOP and TABLESAMPLE limit the number of rows returned in a result set

Result Sets TOP Example: SELECT TOP (15) FirstName, LastName FROM Person.Person
FirstName LastName -------------------Syed Abbas Catherine Abel ... (15 row(s) affected)

TABLESAMPLE Example: SELECT FirstName, LastName FROM Person.Person TABLESAMPLE (1 PERCENT)

FirstName LastName -------------------Eduardo Barnes Edward Barnes ... (199 row(s) affected)

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 User name Password

NY-SQL-01 Administrator 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

You might also like