0% found this document useful (0 votes)
212 views

SQL Server More Clause Part 2

This document provides examples of different types of SQL joins and subqueries using the AdventureWorks database. It includes examples of: 1. Inner joins between multiple tables to return data from related tables. 2. Outer joins to return all rows from one table and matched rows from another table. 3. Subqueries to filter results or combine data from multiple tables. 4. Derived tables and common table expressions to simplify complex multi-table queries. The examples cover basic and advanced techniques for querying related data across multiple tables.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
212 views

SQL Server More Clause Part 2

This document provides examples of different types of SQL joins and subqueries using the AdventureWorks database. It includes examples of: 1. Inner joins between multiple tables to return data from related tables. 2. Outer joins to return all rows from one table and matched rows from another table. 3. Subqueries to filter results or combine data from multiple tables. 4. Derived tables and common table expressions to simplify complex multi-table queries. The examples cover basic and advanced techniques for querying related data across multiple tables.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Use the AdventureWorks to complete this exercise.

Querying Multiple Tables

Exercises on querying multiple tables.

Writing Inner Joins

1. The HumanResources.Employee table does not contain the employee names. Join that table to the

Person.Person table on the BusinessEntityID column. Display the job title, birth date, first name,

and last name.

SELECT JobTitle, BirthDate, FirstName, LastName

FROM HumanResources.Employee AS E

INNER JOIN Person.Person AS P ON E.BusinessEntityID = P.BusinessEntityID;

2. The customer names also appear in the Person.Person table. Join the Sales.Customer table to the

Person.Person table. The BusinessEntityID column in the Person.Person table matches the

PersonID column in the Sales.Customer table. Display the CustomerID, StoreID, and TerritoryID

columns along with the name columns.

SELECT CustomerID, StoreID, TerritoryID, FirstName, MiddleName, LastName

FROM Sales.Customer AS C

INNER JOIN Person.Person AS P ON C.PersonID = P.BusinessEntityID;

3. Extend the query written in question 2 to include the Sales.SalesOrderHeader table. Display the

SalesOrderID column along with the columns already specified. The Sales.SalesOrderHeader

table joins the Sales.Customer table on CustomerID.

SELECT c.CustomerID, StoreID, c.TerritoryID, FirstName, MiddleName,

LastName, SalesOrderID

FROM Sales.Customer AS C

INNER JOIN Person.Person AS P ON C.PersonID = P.BusinessEntityID

INNER JOIN Sales.SalesOrderHeader AS S ON S.CustomerID = C.CustomerID;

4. Write a query that joins the Sales.SalesOrderHeader table to the Sales.


SalesPerson table. Join the BusinessEntityID column from the Sales.SalesPerson table to the

SalesPersonID column in the Sales.SalesOrderHeader table. Display the SalesOrderID along with

the SalesQuota and Bonus.

SELECT SalesOrderID, SalesQuota, Bonus

FROM Sales.SalesOrderHeader AS S

INNER JOIN Sales.SalesPerson AS SP

ON S.SalesPersonID = SP.BusinessEntityID;

5. Add the name columns to the query written in question 4 by joining on the Person.Person table.

See whether you can figure out which columns will be used to write the join.

You can join the Person.Person table on the SalesOrderHeader table or the Sales.SalesPerson

table.

SELECT SalesOrderID, SalesQuota, Bonus, FirstName, MiddleName, LastName

FROM Sales.SalesOrderHeader AS S

INNER JOIN Sales.SalesPerson AS SP ON S.SalesPersonID = SP.BusinessEntityID

INNER JOIN Person.Person AS P ON SP.BusinessEntityID = P.BusinessEntityID;

SELECT SalesOrderID, SalesQuota, Bonus, FirstName, MiddleName, LastName

FROM Sales.SalesOrderHeader AS S

INNER JOIN Sales.SalesPerson AS SP ON S.SalesPersonID = SP.BusinessEntityID

INNER JOIN Person.Person AS P ON S.SalesPersonID = P.BusinessEntityID;

6. The catalog description for each product is stored in the Production.ProductModel table. Display

the columns that describe the product from the Production.Product table, such as the color and

size along with the catalog description for each product.

SELECT PM.CatalogDescription, Color, Size

FROM Production.Product AS P

INNER JOIN Production.ProductModel AS PM ON P.ProductModelID = PM.ProductModelID;


7. Write a query that displays the names of the customers along with the product names that they

have purchased. Hint: Five tables will be required to write this query!

SELECT FirstName, MiddleName, LastName, Prod.Name

FROM Sales.Customer AS C

INNER JOIN Person.Person AS P ON C.PersonID = P.BusinessEntityID

INNER JOIN Sales.SalesOrderHeader AS SOH ON C.CustomerID = SOH.CustomerID

INNER JOIN Sales.SalesOrderDetail AS SOD

ON SOH.SalesOrderID = SOD.SalesOrderID

INNER JOIN Production.Product AS Prod ON SOD.ProductID = Prod.ProductID;

Writing Outer Joins

Use AdventureWorks (question 7) databases to complete this exercise.

1. Write a query that displays all the products along with the SalesOrderID even if an order has never

been placed for that product. Join to the Sales.SalesOrderDetail table using the ProductID

column.

SELECT SalesOrderID, P.ProductID, P.Name

FROM Production.Product AS P

LEFT OUTER JOIN Sales.SalesOrderDetail

AS SOD ON P.ProductID = SOD.ProductID;

2. Change the query written in question 1 so that only products that have not been ordered show up

in the query.

SELECT SalesOrderID, P.ProductID, P.Name

FROM Production.Product AS P

LEFT OUTER JOIN Sales.SalesOrderDetail

AS SOD ON P.ProductID = SOD.ProductID

WHERE SalesOrderID IS NULL;


3. Write a query that returns all the rows from the Sales.SalesPerson table joined to the

Sales.SalesOrderHeader table along with the SalesOrderID column even if no orders match.

Include the SalesPersonID and SalesYTD columns in the results.

SELECT SalesOrderID, SalesPersonID, SalesYTD

FROM Sales.SalesPerson AS SP

LEFT OUTER JOIN Sales.SalesOrderHeader AS SOH

ON SP.BusinessEntityID = SOH.SalesPersonID;

4. Change the query written in question 3 so that the salesperson’s name also displays from the

Person.Person table.

SELECT SalesOrderID, SalesPersonID, SalesYTD, FirstName,

MiddleName, LastName

FROM Sales.SalesPerson AS SP

LEFT OUTER JOIN Sales.SalesOrderHeader AS SOH

ON SP.BusinessEntityID = SOH.SalesPersonID

LEFT OUTER JOIN Person.Person AS P

ON P.BusinessEntityID = SP.BusinessEntityID;

5. The Sales.SalesOrderHeader table contains foreign keys to the Sales.CurrencyRate and

Purchasing.ShipMethod tables. Write a query joining all three tables, making sure it contains all

rows from Sales.SalesOrderHeader. Include the CurrencyRateID, AverageRate, SalesOrderID, and

ShipBase columns.

SELECT CR.CurrencyRateID, CR.AverageRate, SM.ShipBase, SalesOrderID

FROM Sales.SalesOrderHeader AS SOH

LEFT OUTER JOIN Sales.CurrencyRate AS CR

ON SOH.CurrencyRateID = CR.CurrencyRateID

LEFT OUTER JOIN Purchasing.ShipMethod AS SM

ON SOH.ShipMethodID = SM.ShipMethodID;
6. Write a query that returns the BusinessEntityID column from the Sales.SalesPerson table along

with every ProductID from the Production.Product table.

SELECT SP.BusinessEntityID, P.ProductID

FROM Sales.SalesPerson AS SP CROSS JOIN Production.Product AS P;

7. Starting with the query written in Listing 4-13, join the table a to the Person.Contact table to

display the employee’s name. The EmployeeID column joins the ContactID column.

USE AdventureWorks;

GO

SELECT a.EmployeeID AS Employee,

a.Title AS EmployeeTitle,

b.EmployeeID AS ManagerID,

b.Title AS ManagerTitle,

c.FirstName, c.MiddleName, c.LastName

FROM HumanResources.Employee AS a

LEFT OUTER JOIN HumanResources.Employee AS b

ON a.ManagerID = b.EmployeeID

LEFT OUTER JOIN Person.Contact AS c ON a.EmployeeID = c.ContactID;

Writing Subqueries

Use the AdventureWorks database to complete this exercise.

1. Using a subquery, display the product names and product ID numbers from the

Production.Product table that have been ordered.

SELECT ProductID, Name

FROM Production.Product

WHERE ProductID IN (SELECT ProductID FROM Sales.SalesOrderDetail);


2. Change the query written in question 1 to display the products that have not been ordered.

SELECT ProductID, Name

FROM Production.Product

WHERE ProductID NOT IN (

SELECT ProductID FROM Sales.SalesOrderDetail

WHERE ProductID IS NOT NULL);

3. If the Production.ProductColor table is not part of the AdventureWorks2008 database, run the

code in Listing 4-11 to create it. Write a query using a subquery that returns the rows from the

Production.ProductColor table that are not being used in the Production.Product table.

SELECT Color

FROM Production.ProductColor

WHERE Color NOT IN (

SELECT Color FROM Production.Product WHERE Color IS NOT NULL);

4. Write a query that displays the colors used in the Production.Product table that are not listed in

the Production.ProductColor table using a subquery. Use the keyword DISTINCT before the

column name to return each color only once.

SELECT DISTINCT Color

FROM Production.Product

WHERE Color NOT IN (

SELECT Color FROM Production.ProductColor WHERE Color IS NOT NULL);

5. Write a UNION query that combines the ModifiedDate from Person.Person and the HireDate from

HumanResources.Employee.

SELECT ModifiedDate

FROM Person.Person

UNION

SELECT HireDate

FROM HumanResources.Employee;
Exploring Derived Tables and Common

Table Expressions

Use the AdventureWorks database to complete this exercise.

1. Using a derived table, join the Sales.SalesOrderHeader table to the Sales.SalesOrderDetail table.

Display the SalesOrderID, OrderDate, and ProductID columns in the results. The

Sales.SalesOrderDetail table should be inside the derived table query.

SELECT SOH.SalesOrderID, SOH.OrderDate, ProductID

FROM Sales.SalesOrderHeader AS SOH

INNER JOIN (

SELECT SalesOrderID, ProductID

FROM Sales.SalesOrderDetail) AS SOD

ON SOH.SalesOrderID = SOD.SalesOrderID;

2. Rewrite the query in question 1 with a common table expression.

WITH SOD AS (

SELECT SalesOrderID, ProductID

FROM Sales.SalesOrderDetail

SELECT SOH.SalesOrderID, SOH.OrderDate, ProductID

FROM Sales.SalesOrderHeader AS SOH

INNER JOIN SOD ON SOH.SalesOrderID = SOD.SalesOrderID;

3. Write a query that displays all customers along with the orders placed in 2001. Use a common

table expression to write the query and include the CustomerID, SalesOrderID, and OrderDate

columns in the results.

WITH SOH AS (
SELECT SalesOrderID, OrderDate, CustomerID
FROM Sales.SalesOrderHeader
WHERE OrderDate BETWEEN '1/1/2001' AND '12/31/2001'
)
SELECT C.CustomerID, SalesOrderID, OrderDate
FROM Sales.Customer AS C
LEFT OUTER JOIN SOH ON C.CustomerID = SOH.CustomerID;
Thinking About Performance

Use the AdventureWorks database to complete this exercise.

Run the following code to add and populate a new column, OrderID, to the

Sales.SalesOrderDetail table. After running the code, the new column will contain the same data as the

SalesOrderID column.

USE AdventureWorks;

GO

ALTER TABLE Sales.SalesOrderDetail ADD OrderID INT NULL;

GO

UPDATE Sales.SalesOrderDetail SET OrderID = SalesOrderID;

1. Make sure that the Include Actual Execution Plan is turned on before running the following code.

View the execution plans, and explain why one query performs better than the other.

--1

SELECT o.SalesOrderID,d.SalesOrderDetailID

FROM Sales.SalesOrderHeader AS o

INNER JOIN Sales.SalesOrderDetail AS d ON o.SalesOrderID = d.SalesOrderID;

--2

SELECT o.SalesOrderID,d.SalesOrderDetailID

FROM Sales.SalesOrderHeader AS o

INNER JOIN Sales.SalesOrderDetail AS d

ON o.SalesOrderID = d.OrderID;

Query 1, which joins the Sales.SalesOrderDetail table to Sales.SalesOrderHeader on the

SalesOrderID column, performs better because there is a nonclustered index defined on the

SalesOrderID column. There is not an index on the new OrderID column, so a clustered index

scan is performed on the Sales.SalesOrderDetail table to join the tables in query 2.

2. Compare the execution plans of the derived table example and the CTE example

. Explain why the query performance is the same or why one query performs better

than the other.


The performance of the two queries is the same. These two techniques are just different ways to

do the same thing in this case.

1.use SalesLT.SalesOrderHeader; -- pull customerid na 500 to 800

2.HumanResources.Employee -- retrieve jobtitle equal VP of engineering

3.HumanResources.Employee -- concatenate [loginID - jobtitle]

SELECT *

select * from HumanResources.Employee

select

'['+LoginID + ' - ' + JobTitle + ']' as "Login with Position"

from HumanResources.Employee

You might also like