Your SlideShare is downloading. ×
04 qmds2005 session05
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

04 qmds2005 session05

358
views

Published on

Published in: Technology

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
358
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
0
Comments
0
Likes
1
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide
  • Explain the students that in RDBMS the data related to a particular entity might be stored in multiple tables. Therefore, you generally needs to retrieve data from multiple tables. The data from multiple tables can be retrieved using a join. Input To execute the queries for FULL OUTER JOIN and CROSS JOIN, you need to use tables that are not existing in the AdventureWorks database. Therefore, you need to create the tables in the database and insert values in them. For this, you need to run the database scripts provided in the DataFiles_for_faculty\\Chapter 3 folder in the TIRM CD at the beginning of the session.
  • Explain the students that on the basis of the requirement, the database developer might use any of the given type of joins.
  • Explain the diagram to the students. Tell them that, in the above diagram you can see that the common data from both the tables, Table X and Table Y is displayed. The data is displayed on the base of a common column, Column B.
  • Explain the students that an inner join is a join of two tables that returns records for which there is a matching value in the field on which the tables are joined. Also explain them that inner join is the default type of join. Explain the students about table alias. A table alias is name that has been assumed temporarily instead of the actual table name. The scope of the table alias is within the query only. Stress on the fact that there it is very important for the students to understand the concept of joins. Example SELECT e.EmployeeID,e.Title, eph.Rate,eph.PayFrequency FROM HumanResources.Employee e JOIN HumanResources.EmployeePayHistory eph ON e.EmployeeID = eph.EmployeeID Additional Input The INNER JOIN operation can be used in any FROM clause to combine records from two tables. There must be a matching value in a field common to both tables.   An INNER JOIN cannot be nested inside a LEFT JOIN or RIGHT JOIN.
  • Explain the various types of OUTER JOIN to the students with the examples given in the SG. Additional Inputs: An OUTER join can be performed between two tables only. A FULL outer join is the combination of LEFT OUTER JOIN and RIGHT OUTER JOIN. A FULL OUTER JOIN firstly performs a LEFT OUTER JOIN on the underlying tables and then a RIGHT OUTER JOIN. FAQs Question : What is the difference between INNER JOIN and OUTER JOIN? Answer : An INNER JOIN displays only the common data from two tables where as, an OUTER JOIN displays all the data from one table and only matching data from the other one. OUTER JOIN displays NULL in the place where no matching data is found. Question : What is the difference between LEFT OUTER JOIN and RIGHT OUTER JOIN? Answer : A LEFT OUTER JOIN displays all the data from the first table of the join and only matching rows from the second. Where as, RIGHT OUTER JOIN displays all the rows from the second table and only matching rows from the first table.
  • Explain the concept of the LEFT OUTER JOIN to the students using the diagram. Tell them, that as shown in the figure all the rows from first table, Table X are displayed. However, only the matching rows from the second table, Table Y, are displayed. Also tell them that the data is based on the common column between the tables, Column B.
  • Explain the concept of the RIGHT OUTER JOIN to the students using the diagram. Tell them, that as shown in the figure all the rows from second table, Table Y are displayed. However, only the matching rows from the first table, Table X, are displayed. Also tell them that the data is based on the common column between the tables, Column B.
  • Explain the concept of the FULL OUTER join to the students. Tell them that full outer join is a combination of LEFT OUTER join and RIGHT OUTER join. This join returns all the matching and non-matching rows from both the tables.
  • Example: (LEFT OUTER) SELECT p.ProductID, p1.SalesOrderID, p1.UnitPrice FROM Sales.SpecialOfferProduct p LEFT OUTER JOIN [Sales].[SalesOrderDetail] p1 on p. ProductID = p1.ProductID WHERE SalesOrderID IS NULL Example: (RIGHT OUTER) SELECT e.Title, d.JobCandidateID FROM HumanResources.Employee e RIGHT OUTER JOIN HumanResources.JobCandidate d on e.EmployeeID=d.EmployeeID Example: (FULL OUTER) SELECT e.EmployeeID, e.EmployeeName,ed.EmployeeEducationCode, ed.Education FROM Employee e FULL OUTER JOIN Education ed on e.EmployeeEducationCode = ed.EmployeeEducationCode
  • Explain the concept of CROSS JOIN to the students. Tell them that CROSS JOIN displays a combination of all the rows from one table with all the rows from the other one. Also tell them that it shows the Cartesian Product between the rows of first and second table. FAQs Question: What is the difference between FULL OUTER JOIN and CROSS JOIN? Answer : A FULL OUTER JOIN displays all matching and non-matching rows from both the tables and displays NULL in place of non-matching rows. Whereas, a CROSS JOIN displays all the possible combination of all the rows in both the tables. Additional Input A Cartesian Product is the set of all possible ordered pairs between two sets.
  • Example Select A.CompDescription, B.AddOnDescription, A.Price + B.Price as 'Total Cost' from ComputerDetails A CROSS JOIN AddOnDetails B
  • Explain the concept of EQUI join to the student.
  • Conceptually equijoin is same as inner join and is used to list all the columns from the joining tables. Example SELECT * FROM HumanResources.EmployeeDepartmentHistory d JOIN HumanResources.Employee e ON d.EmployeeID = e.EmployeeID JOIN HumanResources.Department p ON p.DepartmentID = d.DepartmentID
  • Example: SELECT a.EmployeeID, a.Title as Employee_Designation, a.ManagerID, b.Title AS Manager_Designation FROM HumanResources.Employee a, HumanResources.Employee b where a.ManagerID = b.EmployeeID
  • Example: SELECT EmployeeID, Title FROM HumanResources.Employee WHERE VacationHours>ALL (SELECT VacationHours FROM HumanResources.Employee WHERE Title ='Recruiter') Additional Inputs If a subquery does not return a single value, you must introduce the subquery with the IN, EXISTS, ANY, or ALL keyword. FAQs Question : What is the difference between a subquery and a join? Answer : Joins are used to display the data form multiple tables whereas a subquery is used to use the output of one query as an input for the condition of another.
  • Explain the students that in a subquery if the inner query is returning only one value, then use the =, >, <, >=, and <= operators. If the inner query is returning more than one value, then use the IN operator. In case of an error while executing a subquery, execute the inner query separately to check whether there is any error in the inner query or not. Example: (IN Keyword) SELECT Name from HumanResources.Department WHERE DepartmentID = (SELECT DepartmentID from HumanResources.EmployeeDepartmentHistory WHERE EmployeeID = 46 and EndDate is NULL) Additional Inputs You cannot use subqueries on columns that contain text and image.
  • FAQs Question: What is the difference between IN and EXISTS clause? Answer : IN returns values from a subquery whereas EXISTS returns Boolean. Example: (EXISTS Keyword) SELECT EmployeeID, Title FROM HumanResources.Employee WHERE EXISTS (SELECT * FROM HumanResources.EmployeeDepartmentHistory WHERE EmployeeID = HumanResources.Employee.EmployeeID AND DepartmentID = 4)
  • Explain the students that is a subquery returns more than one row as the output, normal comparison operators can not be used. So, they need to use the modified comparison operators. Example: SELECT EmployeeID, Title FROM HumanResources.Employee WHERE VacationHours>ALL (SELECT VacationHours FROM HumanResources.Employee WHERE Title ='Recruiter')
  • Additional Input As aggregate functions returns only a single row, you can use normal comparison operators. Example: SELECT EmployeeId FROM HumanResources.Employee Where VacationHours >(SELECT Avg(VacationHours) from HumanResources.Employee where Title = 'Marketing Assistant')
  • Additional Inputs In SQL Server 2005, subqueries can be nested up to 32 levels. Example: SELECT DepartmentID FROM HumanResources.EmployeeDepartmentHistory WHERE EmployeeID = (SELECT EmployeeID FROM HumanResources.Employee WHERE ContactID = (SELECT ContactID FROM Person.Contact WHERE EmailAddress = 'taylor0@adventure-works.com ')) Refer SG for step-wise explanation.
  • Example: SELECT EmployeeID, Title, VacationHours FROM HumanResources.Employee e1 WHERE e1.VacationHours > (SELECT AVG(e2.VacationHours) FROM HumanResources.Employee e2 WHERE e1.Title = e2.Title)
  • You can summarize the session by running through the summary given in SG. In addition, you can also ask students summarize what they have learnt in this session.
  • You can summarize the session by running through the summary given in SG. In addition, you can also ask students summarize what they have learnt in this session.
  • Transcript

    • 1. Querying and Managing Data Using SQL Server 2005Objectives In this session, you will learn to: Query data by using joins Query data by using subqueries Ver. 1.0 Session 5 Slide 1 of 32
    • 2. Querying and Managing Data Using SQL Server 2005Querying Data by Using Joins Joins Allow to retrieve data from multiple tables Can be of the following types: Inner join Outer join Cross join Equi join Self join Ver. 1.0 Session 5 Slide 2 of 32
    • 3. Querying and Managing Data Using SQL Server 2005Using an Inner Join COLUMNS COLUMNS ABC BDE Table X Table Y INNER JOIN ABCDE COMMON ROWS OUTPUT Ver. 1.0 Session 5 Slide 3 of 32
    • 4. Querying and Managing Data Using SQL Server 2005Using an Inner Join (Contd.) Inner Join: Retrieves data from multiple tables by using a comparison operator on a common column Retrieves only those rows that satisfy the join condition Syntax: SELECT column_name, column_name [,column_name] FROM table1_name JOIN table2_name ON table1_name.ref_column_name join_operator table2_name.ref_column_name Let’s see how… Ver. 1.0 Session 5 Slide 4 of 32
    • 5. Querying and Managing Data Using SQL Server 2005Just a minute Why do you need a table alias with the column name? Answer: A table alias is required to uniquely identify columns in the SELECT query to avoid ambiguity that arises due to same column names in multiple tables. Ver. 1.0 Session 5 Slide 5 of 32
    • 6. Querying and Managing Data Using SQL Server 2005Using an Outer Join Outer Join: Displays the result set containing all rows from one table and the matching rows from another table Displays NULL for the columns of the related table where it does not find matching records Is of three types: • Left outer join • Right outer join • Full outer join Ver. 1.0 Session 5 Slide 6 of 32
    • 7. Querying and Managing Data Using SQL Server 2005Using an Outer Join (Contd.) COLUMNS COLUMNS ABC BDE Table X Table Y LEFT OUTER JOIN ABCDE ALL ROWS FROM TABLE X AND COMMON ROWS FROM TABLE Y OUTPUT Ver. 1.0 Session 5 Slide 7 of 32
    • 8. Querying and Managing Data Using SQL Server 2005Using an Outer Join (Contd.) COLUMNS COLUMNS ABC BDE Table X Table Y RIGHT OUTER JOIN ABCDE ALL ROWS FROM TABLE Y AND COMMON ROWS FROM TABLE X OUTPUT Ver. 1.0 Session 5 Slide 8 of 32
    • 9. Querying and Managing Data Using SQL Server 2005Using an Outer Join (Contd.) COLUMNS COLUMNS ABC BDE Table X Table Y FULL OUTER JOIN ABCDE ALL ROWS FROM TABLE Y AND TABLE Y AND COMMON ROWS ONLY ONCE OUTPUT Ver. 1.0 Session 5 Slide 9 of 32
    • 10. Querying and Managing Data Using SQL Server 2005Using an Outer Join (Contd.) Syntax: SELECT column_name, column_name [,column_name] FROM table1_name [LEFT | RIGHT | FULL] OUTER JOIN table2_name ON table1_name.ref_column_name join_operator table2_name.ref_column_name Let’s see how… Ver. 1.0 Session 5 Slide 10 of 32
    • 11. Querying and Managing Data Using SQL Server 2005Just a minute When do you use the right outer join? Answer: You can use the right outer join when you need all the records from the table at the right side of the outer join and only the matching records from the the table at the left side of the outer join. Ver. 1.0 Session 5 Slide 11 of 32
    • 12. Querying and Managing Data Using SQL Server 2005Using a Cross Join COLUMNS COLUMNS ABC BDE Table X Table Y n ROWS CROSS JOIN m ROWS ABCDE ALL ROWS (n X m) EACH ROW OF TABLE X JOINED WITH EACH ROW OF TABLE Y OUTPUT Ver. 1.0 Session 5 Slide 12 of 32
    • 13. Querying and Managing Data Using SQL Server 2005Using a Cross Join (Contd.) Cross Join: Displays each row from the first table joined with each row from the second table Produces the result set as the number of rows in the first table multiplied by the number of rows in the second table Let’s see how… Ver. 1.0 Session 5 Slide 13 of 32
    • 14. Querying and Managing Data Using SQL Server 2005Using an Equi Join COLUMNS COLUMNS ABC BDE Table X Table Y EQUI JOIN ABCDBE COMMON ROWS OUTPUT Ver. 1.0 Session 5 Slide 14 of 32
    • 15. Querying and Managing Data Using SQL Server 2005Using an Equi Join (Contd.) Equi Join: Is same as an inner join Displays all the columns from both the tables Displays redundant column data in the result set Let’s see how… Ver. 1.0 Session 5 Slide 15 of 32
    • 16. Querying and Managing Data Using SQL Server 2005Just a minute What is the difference between an equi and an inner join? Answer: An equi join is used to retrieve all the columns from both the tables. An inner join is used to retrieve selected columns from tables. Ver. 1.0 Session 5 Slide 16 of 32
    • 17. Querying and Managing Data Using SQL Server 2005Using a Self Join Self Join: Is used when one row in a table correlates with other rows in the same table Uses alias name to differentiate the two copies of the same table Let’s see how… Ver. 1.0 Session 5 Slide 17 of 32
    • 18. Querying and Managing Data Using SQL Server 2005Demo: Using Joins Problem Statement: The HR manager of AdventureWorks, Inc. requires a report containing the following details: Employee ID Employee Name Department Name Date of Joining Employee Address How will you generate this report? Ver. 1.0 Session 5 Slide 18 of 32
    • 19. Querying and Managing Data Using SQL Server 2005Demo: Using Joins (Contd.) Solution: To solve the preceding problem, you need to perform the following tasks: 1. Identify the join. 2. Create a query based on joins. 3. Execute the query to verify the result. Ver. 1.0 Session 5 Slide 19 of 32
    • 20. Querying and Managing Data Using SQL Server 2005Querying Data by Using Subqueries Subqueries: Are used when the result set of one query needs to be taken as input for another query Syntax: SELECT column, column [,column] FROM table_name WHERE column = ( SELECT column FROM table_name [WHERE conditional_expression] ) Ver. 1.0 Session 5 Slide 20 of 32
    • 21. Querying and Managing Data Using SQL Server 2005Using the IN and EXISTS Keyword IN keyword: Is used to retrieve rows in a subquery based on the match of values given in a list Syntax: SELECT column, column [,column] FROM table_name WHERE column [ NOT ] IN ( SELECT column FROM table_name [WHERE conditional_expression] ) Let’s see how… Ver. 1.0 Session 5 Slide 21 of 32
    • 22. Querying and Managing Data Using SQL Server 2005Using the IN and EXISTS Keyword (Contd.) EXISTS keyword: Is used to check the existence of the data and returns true or false Syntax: SELECT column, column [,column] FROM table_name WHERE EXISTS ( SELECT column FROM table_name [WHERE conditional_expression] ) Let’s see how… Ver. 1.0 Session 5 Slide 22 of 32
    • 23. Querying and Managing Data Using SQL Server 2005Using Modified Comparison Operators Comparison operators are modified using: ALL keyword that returns TRUE, if all the values retrieved by the subquery satisfy the comparison operator ANY keyword that returns TRUE, if any value retrieved by the subquery satisfies the comparison operator Let’s see how… Ver. 1.0 Session 5 Slide 23 of 32
    • 24. Querying and Managing Data Using SQL Server 2005Just a minute What is the use of EXISTS keyword in a subquery? Answer: The EXISTS keyword is used to check the existence of rows in the result set of an inner query according to the condition specified in the inner query. Ver. 1.0 Session 5 Slide 24 of 32
    • 25. Querying and Managing Data Using SQL Server 2005Using Aggregate Functions Aggregate functions: Can be used in the subquery to generate aggregated values from the inner query Let’s see how… Ver. 1.0 Session 5 Slide 25 of 32
    • 26. Querying and Managing Data Using SQL Server 2005Using Nested Subqueries Nested subqueries: Contain one or more subqueries Can be used when the condition of a query is dependent on the result of another query Let’s see how… Ver. 1.0 Session 5 Slide 26 of 32
    • 27. Querying and Managing Data Using SQL Server 2005Using Correlated Subqueries Correlated subqueries: Can be defined as a query that depends on the outer query for its evaluation Uses the WHERE clause to refer to the table specified in the FROM clause Let’s see how… Ver. 1.0 Session 5 Slide 27 of 32
    • 28. Querying and Managing Data Using SQL Server 2005Just a minute Write a query to determine the Employee ID and the Department ID of all the employees whose Manager ID is 12. Answer: SELECT EmployeeID, DepartmentID FROM HumanResources.EmployeeDepartmentHistory WHERE EmployeeID=(SELECT EmployeeID FROM HumanResources.Employee WHERE ManagerID=12) Ver. 1.0 Session 5 Slide 28 of 32
    • 29. Querying and Managing Data Using SQL Server 2005Demo: Using Subqueries Problem Statement: The management of AdventureWorks, Inc. is planning to revise the pay rate of the employees. For this, they want a report containing the EmployeeID and designation of those employees whose present pay rate is more than 40. How will you generate this report? Ver. 1.0 Session 5 Slide 29 of 32
    • 30. Querying and Managing Data Using SQL Server 2005Demo: Using Subqueries (Contd.) Solution: To solve the preceding problem, you need to perform the following tasks: 1. Create a query. 2. Execute the query to verify the result. Ver. 1.0 Session 5 Slide 30 of 32
    • 31. Querying and Managing Data Using SQL Server 2005Summary In this session, you learned that: Joins and subqueries are used to retrieve data from multiple tables. An inner join combines records from multiple tables by using a comparison operator on a common column. A left outer join returns all the rows from the left table and the matching rows from the right table. A right outer join returns all the rows from the right table and the matching rows from the left table. A full outer join returns all the matching and non-matching rows from both the tables on which join is applied. A cross join returns each row from the first table joined with each row from the second table. An equi join is used to list all the columns from the joining tables. Ver. 1.0 Session 5 Slide 31 of 32
    • 32. Querying and Managing Data Using SQL Server 2005Summary (Contd.) The IN clause in a subquery returns zero or more values. The EXISTS clause in a subquery returns data in terms of a TRUE or FALSE value. The ALL and ANY keyword is used in a subquery to modify the existing comparison operator. Aggregate functions can also be used in subqueries to generate aggregated values from the inner query. Subqueries that contain one or more queries are specified as nested subqueries. A correlated subquery can be defined as a query that depends on the outer query for its evaluation. A self join correlates one row in a table with other rows in the same table. Ver. 1.0 Session 5 Slide 32 of 32