Presentation is loading. Please wait.

Presentation is loading. Please wait.

Module 4: Joining Data from Multiple Tables

Similar presentations


Presentation on theme: "Module 4: Joining Data from Multiple Tables"— Presentation transcript:

1 Module 4: Joining Data from Multiple Tables
Course 2778A Module 4: Joining Data from Multiple Tables Presentation: 60 minutes Lab: 60 minutes Module 4: Joining Data from Multiple Tables This module helps students to understand how to query multiple tables by using joins, apply joins to typical reporting needs, and combine and limit join result sets. After completing this module, students will be able to: Query multiple tables by using joins. Apply joins for typical reporting needs. Combine and limit result sets. Required materials To teach this module, you need the Microsoft Office PowerPoint® file 2778A_04.ppt. Important It is recommended that you use PowerPoint 2002 or a later version to display the slides for this course. If you use PowerPoint Viewer or an earlier version of PowerPoint, all the features of the slides might not be displayed correctly. Preparation tasks To prepare for this module: Read all of the materials for this module. Practice performing the demonstrations and the lab exercises. Work through the Module Review and Takeaways section and determine how you will use this section to reinforce student learning and promote knowledge transfer to on-the-job performance. Make sure that students are aware that there are additional information and resources for the module on the Course Companion CD.

2 Module 4: Joining Data from Multiple Tables
Course 2778A 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

3 Lesson 1: Querying Multiple Tables by Using Joins
Course 2778A Lesson 1: Querying Multiple Tables by Using Joins Module 4: Joining Data from Multiple Tables 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 Module 4: Joining Data from Multiple Tables
Course 2778A Fundamentals of Joins Module 4: Joining Data from Multiple Tables Joins: Select Specific Columns from Multiple Tables JOIN keyword specifies that tables are joined and how to join them ON keyword specifies join condition Use this slide to introduce students to join fundamentals including foreign key relationships, what joins do, and a simplified JOIN syntax. By using joins, you can retrieve data from two or more tables based on logical relationships between the tables. Joins indicate how Microsoft SQL Server uses data from one table to select the rows in another table. A table typically has a column or combination of columns that contain values that uniquely identify each row in the table. This column, or columns, is called the primary key (PK) of the table and enforces the entity integrity of the table. A foreign key (FK) is a column or combination of columns that is used to establish and enforce a link between the data in two tables. Foreign key columns are frequently used in join criteria when the data from related tables is combined in queries by matching the column or columns in the FOREIGN KEY constraint of one table with the primary or unique key column or columns in the other table Join conditions can be specified in either the FROM or WHERE clauses; specifying them in the FROM clause is recommended. WHERE and HAVING clauses can also contain search conditions to further filter the rows selected by the join conditions. A join can be expressed in a number of ways in an SQL statement. The exact syntax depends on the database you are using and on how you have defined the join. Syntax options for joining tables include: JOIN qualifier for the FROM clause: the keywords INNER and OUTER specify the join type. This syntax is standard for ANSI 92 SQL. WHERE clause compares columns in both tables: a WHERE clause appears if the database does not support the JOIN syntax (or if you entered it yourself). The syntax shown here is the simplified ISO FROM clause join syntax. join_type specifies what kind of join is performed: an inner, outer, or cross join. join_condition defines the predicate to be evaluated for each pair of joined rows. Note that when there are null values in the columns of the tables being joined, the null values do not match each other. The presence of null values in a column from one of the tables being joined can be returned only by using an outer join (unless the WHERE clause excludes null values). Delivery note: consider using the Order and OrderDetails tables to explain Primary Key and Foreign Key and the need for JOINs. References Using Joins: 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)]

5 Categorizing Statements by Types of Joins
Course 2778A Categorizing Statements by Types of Joins Module 4: Joining Data from Multiple Tables 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 Use this slide to discuss how to categorize statements by types of joins. Inner joins (the typical join operation, which uses some comparison operator like = or <>). These include equi-joins and natural joins. Inner joins use a comparison operator to match rows from two tables based on the values in common columns from each table. For example, retrieving all rows where the student identification number is the same in both the students and courses tables. Outer joins. Outer joins can be a left, a right, or full outer join. Outer joins are specified with one of the following sets of keywords when they are specified in the FROM clause: LEFT JOIN or LEFT OUTER JOIN The result set of a left outer join includes all the rows from the left table specified in the LEFT OUTER clause, not just the ones in which the joined columns match. When a row in the left table has no matching rows in the right table, the associated result set row contains null values for all select list columns coming from the right table. RIGHT JOIN or RIGHT OUTER JOIN A right outer join is the reverse of a left outer join. All rows from the right table are returned. Null values are returned for the left table any time a right table row has no matching row in the left table. FULL JOIN or FULL OUTER JOIN A full outer join returns all rows in both the left and right tables. Any time a row has no match in the other table, the select list columns from the other table contain null values. When there is a match between the tables, the entire result set row contains data values from the base tables. Cross joins Cross joins return all rows from the left table. Each row from the left table is combined with all rows from the right table. Cross joins are also called Cartesian products. Note that self joins are discussed in greater detail in the next lesson. References Using Joins:

6 Joining Data Using Inner Joins
Course 2778A Joining Data Using Inner Joins Module 4: Joining Data from Multiple Tables An inner join is a join in which the values in the columns being joined are compared using a comparison operator Use this slide to describe to students how to use Inner Joins to join data. An inner join is a join in which the values in the columns being joined are compared using a comparison operator. In the ISO standard, inner joins can be specified in either the FROM or WHERE clause. This is the only type of join that ISO supports in the WHERE clause. Inner joins specified in the WHERE clause are known as old-style inner joins. This example is an inner join retrieving the employees who are also sales persons. The tables or views in the FROM clause can be specified in any order with an inner join or full outer join. However, the order of tables or views specified when using either a left or right outer join is important. References Using Inner Joins: 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)

7 Joining Data Using Outer Joins
Course 2778A Joining Data Using Outer Joins Module 4: Joining Data from Multiple Tables Outer Joins return all rows from at least one of the tables or views mentioned in the FROM clause Example: Use this slide to describe to students how to use Outer Joins to join data. Outer joins return all rows from at least one of the tables or views mentioned in the FROM clause, as long as those rows meet any WHERE or HAVING search conditions. All rows are retrieved from the left table referenced with a left outer join, and all rows from the right table referenced in a right outer join. All rows from both tables are returned in a full outer join. Consider a join of the Product table and the ProductReview table on their ProductID columns. The results show only the products for which reviews have been written. To include all products, regardless of whether a review has been written for one, you would use an ISO left outer join. Note that more information on Outer Joins, including information on RIGHT and FULL Outer Joins, is available on the Companion CD. References Using Outer Joins: 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)

8 Joining Data Using Cross Joins
Course 2778A Joining Data Using Cross Joins Module 4: Joining Data from Multiple Tables In a Cross Join, each row from the left table is combined with all rows from the right table Example: Use this slide to describe to students how to use Cross Joins to join data. A cross join that does not have a WHERE clause produces the Cartesian product of the tables involved in the join. The size of a Cartesian product result set is the number of rows in the first table multiplied by the number of rows in the second table. Quickdemo: Use the query contained in E:\MOD04\Demofiles\Slide9.sql on the AdventureWorks2008 database to show students a cross join. References Using Cross Joins: SELECT p.BusinessEntityID, t.Name AS Territory FROM Sales.SalesPerson p CROSS JOIN Sales.SalesTerritory t ORDER BY p.BusinessEntityID Result Set: BusinessEntityID Territory Northwest Northeast ... (170 row(s) affected) Use CROSS JOINs with caution if you do not need a true Cartesian Product

9 Identifying the Potential Impact of a Cartesian Product
Course 2778A Identifying the Potential Impact of a Cartesian Product Module 4: Joining Data from Multiple Tables A Cartesian Product: Is defined as all possible combinations of rows in all tables ü Use this slide to discuss the impact a Cross Join, or Cartesian Product, can have on a database. A Cartesian product, or Cross join, is defined as all possible combinations of rows in all tables. Be sure you have joins before trying to return data, because a Cartesian product on tables with many records and/or on many tables could take several hours to complete. A Cartesian product can return all customers for all months. A Cartesian product basically multiplies the first table by the second table and results in a rowset that contains the number of rows in the first table times the number of rows in the second table. Use CROSS JOINs with caution if you do not need a true Cartesian product because they can be very resource intensive. For example, if you do a CROSS JOIN on products and categories and then use a WHERE clause, DISTINCT or GROUP BY to filter out most of the rows, you could have gotten to the same result in a much more efficient manner by using an INNER JOIN. Cartesian products can be very useful when you need the data returned for all possibilities, as in the case when you want to load a graph with monthly sales dates. Note that INNER JOINs are much more efficient in most scenarios. References Data Points: Five Ways to Rev up Your SQL Performance: 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
Course 2778A Demonstration: Querying a Table Using Joins Module 4: Joining Data from Multiple Tables 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 In this demonstration, students will learn how to query a table using inner, outer, and cross joins. Start SQL Server Management Studio and, using the AdventureWorks2008 database, perform each of the queries found in E:\MOD04\Democode\QueryingWithJoins.sql. Leave SQL Server Management Studio open for the next set of demonstrations. When would it make sense to use an outer join instead of an inner join? When you need to return all rows from at least one of the tables or views mentioned in the FROM clause instead of eliminating rows as an inner join would do. Can you think of any scenarios in which you would use a cross join? If you want to run a query that will return data for every month, for example, even on customers that had no orders that particular month, you could use a Cartesian product to get that data. References Using Joins:

11 Lesson 2: Applying Joins for Typical Reporting Needs
Course 2778A Lesson 2: Applying Joins for Typical Reporting Needs Module 4: Joining Data from Multiple Tables 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
Course 2778A Joining Three or More Tables Module 4: Joining Data from Multiple Tables FROM clauses can contain multiple Join specifications which allows many tables to be joined in a single Query Example: Use this slide to describe to the students how to join three or more tables using FROM clauses. Although each join specification joins only two tables, FROM clauses can contain multiple join specifications. This allows many tables to be joined for a single query. The ProductVendor table of the AdventureWorks database offers a good example of a situation in which joining more than two tables is helpful. The example Transact-SQL query here finds the names of all products of a particular subcategory and the names of their vendors. Delivery note: show students the structure of the Production.Product table, Purchasing.ProductVendor table, and Purchasing.Vendor table. Quickdemo: Consider copying the query in the code box into a new query in the AdventureWorks2008 database and showing students the full result set. One of the tables in the FROM clause, ProductVendor, does not contribute any columns to the results. Also, none of the joined columns, ProductID and VendorID, appear in the results. Nonetheless, this join is possible only by using ProductVendor as an intermediate table. The middle table of the join, the ProductVendor table, can be called the translation table or intermediate table, because ProductVendor is an intermediate point of connection between the other tables involved in the join. When there is more than one join operator in the same statement, either to join more than two tables or to join more than two pairs of columns, the join expressions can be connected with AND or with OR. References 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 Result Set: Name Name LL Mountain Seat/Saddle Chicago City Saddles ML Mountain Seat/Saddle Chicago City Saddles ... (18 row(s) affected)

13 Joining a Table to Itself
Course 2778A Joining a Table to Itself Module 4: Joining Data from Multiple Tables A Table can be Joined to itself by using a Self-Join Example: Use this slide to introduce the concept of the self-join. A table can be joined to itself in a self-join. For example, you can use a self-join to find the products that are supplied by more than one vendor. Because this query involves a join of the ProductVendor table with itself, the ProductVendor table appears in two roles. To distinguish these roles, you must give the ProductVendor table two different aliases (pv1 and pv2) in the FROM clause. These aliases are used to qualify the column names in the rest of the query. Code box Example of the self-join Transact-SQL statement. References Using Self-Joins: 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 ... (347 row(s) affected)

14 Joining Tables by Using Non-Equi Joins
Course 2778A Joining Tables by Using Non-Equi Joins Module 4: Joining Data from Multiple Tables The same Operators and Predicates used for Inner Joins can be used for Not-Equal Joins Example: Use this slide to introduce the concept of the non-equal join to students. You can also join values in two columns that are not equal. The same operators and predicates used for inner joins can be used for not-equal joins. The not-equal join (<>) is rarely used. As a general rule, not-equal joins make sense only when used with a self-join. Note that the expression NOT column_name = column_name is equivalent to column_name <> column_name. This not-equal Transact-SQL join and self-join are used to find the subcategories that have at least two different prices less than $15. References Using Inner 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 Result Set: ProductSubcateogoryID ListPrice ... (8 row(s) affected)

15 Joining Tables in a User-Defined Function
Course 2778A Joining Tables in a User-Defined Function Module 4: Joining Data from Multiple Tables User-defined functions can be used to focus, simplify, and customize the perception each user has of the database Example: Use this slide to explain to students how to join a table to a user-defined function. Inline user-defined functions are a subset of user-defined functions that return a table data type. This example returns an table-valued function. It returns three columns ProductID, Name and the aggregate of year-to-date totals by store as YTD Total for each product sold to the store. To invoke the function, run the select query. Inline user-defined functions follow these rules The RETURNS clause contains only the keyword table. You do not have to define the format of a return variable, because it is set by the format of the result set of the SELECT statement in the RETURN clause. There is no function_body delimited by BEGIN and END. The RETURN clause contains a single SELECT statement in parentheses. The result set of the SELECT statement forms the table returned by the function. The SELECT statement used in an inline function is subject to the same restrictions as SELECT statements used in views. The table-valued function accepts only constants arguments References Inline User-defined Functions: CREATE FUNCTION Sales.ufn_SalesByStore 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 GROUP BY P.ProductID, P.Name ); SELECT * FROM Sales.ufn_SalesByStore (29825) Result Set: Product ID Name YTD Total Sport-100 Helmet, Red Sport-100 Helmet, Black

16 Demonstration: Joining Tables
Course 2778A Demonstration: Joining Tables Module 4: Joining Data from Multiple 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 In this demonstration, students will learn how to join more than tables, how to join a table to itself, and how to join a table using a non-equal join. Using the AdventureWorks2008 database, perform each of the queries found in E:\MOD04\Democode\JoiningTables.sql. Leave SQL Server Management Studio open for the next set of demonstrations. What is a translation (or intermediate) table and what is it used for? A translation (or intermediate) table is the middle table in a join when you are joining three or more tables. When does it make sense to use a non-equi join? As a general rule, not-equal joins make sense only when used with a self-join.

17 Lesson 3: Combining and Limiting Result Sets
Course 2778A Lesson 3: Combining and Limiting Result Sets Module 4: Joining Data from Multiple Tables 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
Course 2778A Combining Result Sets by Using the UNION Operator Module 4: Joining Data from Multiple Tables 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 Use this slide to describe how to combine 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. The UNION operation is different from using joins that combine columns from two tables. The following are basic rules for combining the result sets of two queries by using UNION: The number and the order of the columns must be the same in all queries The data types must be compatible This example is a valid UNION expression that returns the all rows from both the testa and testb tables. Quickdemo: consider showing students the records of tables testa and testb. Note that, to do this quickdemo you must first prepare the database by launching SQL Server Management Studio, connecting to NY-SQL-01, browsing to E:\MOD04\Labfiles\Starter and then double-clicking on LabSetup.cmd. References UNION (Transact-SQL): Example: SELECT * FROM testa UNION ALL SELECT * FROM testb; Result Set: columna columnb 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

19 Limiting Result Sets by Using the EXCEPT and INTERSECT Operators
Course 2778A Limiting Result Sets by Using the EXCEPT and INTERSECT Operators Module 4: Joining Data from Multiple Tables 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 Use this slide to describe how to limit result sets by using the EXCEPT and INTERSECT operators, which returns distinct values by comparing the results of two queries. EXCEPT returns any distinct values from the left query that are not also found on the right query, and is used to exempt members from a result set. INTERSECT returns any distinct values that are returned by both the query on the left and right sides of the INTERSECT operand, and is used to determine which tables share similar data. The basic rules for combining the result sets of two queries that use EXCEPT or INTERSECT are the following: The number and the order of the columns must be the same in all queries The data types must be compatible Code box 1 This example returns any distinct values from the query to the left of the EXCEPT operand that are not also found on the right query. . Code box 2 This example returns any distinct values that are returned by both the query on the left and right sides of the INTERSECT operand. References EXCEPT and INTERSECT (Transact-SQL): EXCEPT Example: Result Sets SELECT ProductID FROM Production.Product EXCEPT FROM Production.WorkOrder ProductID 429 ... (266 row(s) affected) INTERSECT Example: SELECT ProductID FROM Production.Product INTERSECT FROM Production.WorkOrder ProductID 3 ... (238 row(s) affected)

20 Identifying the Order of Precedence of UNION, EXCEPT, and INTERSECT
Course 2778A Identifying the Order of Precedence of UNION, EXCEPT, and INTERSECT Module 4: Joining Data from Multiple Tables EXCEPT, INTERSECT, and UNION are evaluated in the context of the following precedence: Use this slide to introduce the order of precedence when using UNION, EXCEPT, and INTERSECT. If EXCEPT or INTERSECT is used together with other operators in an expression, it is evaluated in the context of the following precedence: Expressions in parentheses The INTERSECT operand EXCEPT and UNION evaluated from left to right based on their position in the expression If EXCEPT or INTERSECT is used to compare more than two sets of queries, data type conversion is determined by comparing two queries at a time, and following the previously mentioned rules of expression evaluation. This means that, for example, a subquery contained in a query would be evaluated before other expressions in the same query, then the INTERSECT portion of the query would be evaluated, and finally any EXCEPT or UNION clause would be evaluated. Note to students that using one ORDER BY clause applies only to when using UNION, EXCEPT and INTERSECT in a top-level query and not in a subquery. References EXCEPT and INTERSECT (Transact-SQL): Expressions in parentheses 1 The INTERSECT operand 2 EXCEPT and UNION evaluated from Left to Right based on their position in the expression 3

21 Limiting Result Sets by Using the TOP and TABLESAMPLE Operators
Course 2778A Limiting Result Sets by Using the TOP and TABLESAMPLE Operators Module 4: Joining Data from Multiple Tables TOP and TABLESAMPLE limit the number of rows returned in a result set Result Sets Use this slide to describe to students how to limit results sets by using the TOP and TABLESAMPLE operators. TOP specifies that only the first set of rows will be returned from the query result. The set of rows can be either a number or a percent of the rows. The TOP expression can be used in SELECT, INSERT, UPDATE, and DELETE statements. TABLESAMPLE limits the number of rows returned from a table in the FROM clause to a sample number or PERCENT of rows. The TABLESAMPLE clause limits the number of rows returned from a table in the FROM clause to a sample number or PERCENT of rows. You can use TABLESAMPLE to quickly return a sample from a large table when either of the following conditions is true: The sample does not have to be a truly random sample at the level of individual rows. Rows on individual pages of the table are not correlated with other rows on the same page. When would you use TOP to limit a result set? Sometimes you want to determine how many rows are returned by a query, for example in a table that contains dates you may only want to return some number or percentage of the most recent rows added or modified. You can use the TOP clause to do this. When would you use TABLESAMPLE to limit a result set? Whenever you need a truly random sample of data from your database, such as in some data mining applications where you need a sampling mechanism, you can use TABLESAMPLE. With TABLESAMPLE you are able to get a sample set of data without having to sift through the database manually. References Limiting Result Sets by Using TOP and PERCENT: Limiting Result Sets by Using TABLESAMPLE: TOP Example: FirstName LastName Syed Abbas Catherine Abel ... (15 row(s) affected) SELECT TOP (15) FirstName, LastName FROM Person.Person TABLESAMPLE Example: FirstName LastName Eduardo Barnes Edward Barnes ... (199 row(s) affected) SELECT FirstName, LastName FROM Person.Person TABLESAMPLE (1 PERCENT)

22 Categorizing Statements That Limit Result Sets
Course 2778A Categorizing Statements That Limit Result Sets Module 4: Joining Data from Multiple Tables 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 Use this slide to describe how to categorize statements that limit result sets. 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. The UNION operation is different from using joins that combine columns from two tables. EXCEPT and INTERSECT EXCEPT returns any distinct values from the left query that are not also found on 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. TABLESAMPLE The TABLESAMPLE clause limits the number of rows returned from a table in the FROM clause to a sample number or PERCENT of rows. TOP Limits the number of rows that are returned in the result set. If a SELECT statement that includes TOP also has an ORDER BY clause, the rows to be returned are selected from the ordered result set. References UNION (Transact-SQL): EXCEPT and INTERSECT (Transact-SQL): Limiting Result Sets by Using TOP and PERCENT: Limiting Result Sets by Using TABLESAMPLE:

23 Demonstration: Combining and Limiting Result Sets
Course 2778A Demonstration: Combining and Limiting Result Sets Module 4: Joining Data from Multiple Tables In this demonstration, you will see how to: Combine Result Sets Limit Result Sets using TABLESAMPLE Limit Result Sets using TOP In this demonstration, show how to combine result sets and how to limit result sets. First, prepare the AdventureWorks2008 database using the query found at E:\MOD04\Democode\PrepareResultSets.sql. Then, using the AdventureWorks2008 database, perform each of the queries found in E:\MOD04\Democode\ResultSets.sql. What are the basic rules for combining the result sets of two queries by using UNION? The following are basic rules for combining the result sets of two queries by using UNION: The number and the order of the columns must be the same in all queries. The data types must be compatible. How do you think rows are returned from a SELECT TOP statement that also has an ORDER BY clause? If a SELECT statement that includes TOP also has an ORDER BY clause, the rows to be returned are selected from the ordered result set. The whole result set is built in the specified order and the top n rows in the ordered result set are returned. What conditions must be met in order to use TABLESAMPLE to return a sample from a large table? You can use TABLESAMPLE to quickly return a sample from a large table when either of the following conditions is true: The sample does not have to be a truly random sample at the level of individual rows. Rows on individual pages of the table are not correlated with other rows on the same page.

24 Lab: Joining Data from Multiple Tables Page 164
Course 2778A Lab: Joining Data from Multiple Tables Page 164 Module 4: 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 In this lab, students will learn how to join data from multiple tables. Exercise 1 In this exercise, students will query multiple tables by using joins. Exercise 2 In this exercise, students will apply joins for typical reporting needs. Exercise 3 In this exercise, students will both combine and limit result sets. Before the students begin the lab, read the scenario associated with each exercise to the class. This will reinforce the broad issue that the students are troubleshooting and will help to facilitate the lab discussion at the end of the module. Remind the students to complete the discussion questions after the last lab exercise. Note: The lab exercise answer keys are provided on the Course Companion CD. To access the answer key, click the link located at the bottom of the relevant lab exercise page. Logon information Virtual machine NY-SQL-01 User name Administrator Password Pa$$w0rd Estimated time: 60 minutes

25 Module 4: Joining Data from Multiple Tables
Course 2778A Lab Scenario Module 4: Joining Data from Multiple Tables 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 Module 4: Joining Data from Multiple Tables
Course 2778A Lab Review Module 4: Joining Data from Multiple Tables 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? Use the questions on the slide to guide the debriefing after students have completed the lab exercises. Question: What results did the Inner Join in Exercise 1 return? Answer: All the columns in both tables, and returns only the rows for which there is an equal value in the join column. Question: What results did the Left Outer Join and Right Outer Join in Exercise 1 return? Answer: The Left Outer Join included all rows in the Product table in the results, whether or not there was a match on the ProductID column in the ProductReview table. The Right Outer Join returned all sales persons in the results, regardless of whether they are assigned a territory. Question: Why was the ProductVendor table given two different table aliases in the FROM clause of Exercise 2? Answer: Because the ProductVendor table appears in two roles and those aliases were used to qualify the column names in the rest of the query. Question: What would happen if we added an ORDER BY clause to the TOP select statement in Exercise 3? Answer: The rows to be returned would be selected from the ordered result set instead of from the standard, unordered result set.

27 Module Review and Takeaways
Course 2778A Module Review and Takeaways Module 4: Joining Data from Multiple Tables Review Questions Best Practices Review Questions Point the students to the appropriate section in the course so that they are able to answer the questions presented in this section. Question: How does a join condition define the way two tables are related in a query? Answer: By specifying the column from each table to be used for the join or by specifying a logical operator (for example, = or <>,) to be used in comparing values from the columns. Question: How can multiple join operators be combined in the same statement? Answer: The join expressions can be connected using the AND or OR operators. Question: What options are available to the TABLESAMPLE clause and what are they used for? Answer: SYSTEM and REPEATABLE. SYSTEM returns an approximate percentage of rows and generates a random value for each physical 8-KB page in the table. REPEATABLE causes a selected sample to be returned again. Best Practices related to using Joins Supplement or modify the following best practices for your own work situations: Specifying the join conditions in the FROM clause helps separate them from any other search conditions that may be specified in a WHERE clause, and is the recommended method for specifying joins. Columns used in a join condition are not required to have the same name or be the same data type. However, if the data types are not identical, they must be compatible, or be types that SQL Server can implicitly convert. To retain the nonmatching information by including nonmatching rows in the results of a join, use a full outer join. SQL Server provides the full outer join operator, FULL OUTER JOIN, which includes all rows from both tables, regardless of whether or not the other table has a matching value.


Download ppt "Module 4: Joining Data from Multiple Tables"

Similar presentations


Ads by Google