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

Lab Answer Key - Module 4 - Querying Multiple Tables

Uploaded by

ronaldoottoni
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Lab Answer Key - Module 4 - Querying Multiple Tables

Uploaded by

ronaldoottoni
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

09/03/2021 Lab Answer Key: Module 4: Querying Multiple Tables

Destaque Anotação
Lab Answer Key: Module 4: Querying Multiple Tables

Lab: Querying Multiple Tables

Exercise 1: Writing Queries That Use Inner Joins


Es
s
ed
oc
Nã um

Task 1: Prepare the Lab e Environment
pe ron nto
rm a pe
itid ldoo rten
or tto ce
ea n aR
liza i@g on
1. Ensure that the 20461C-MIA-DC rc ma and ald
óp il
ias .com o Ot
nã to
20461C-MIA-SQL virtual machines o a are bothnrunning,
i. and then log on to
uto
riz
20461C-MIA-SQL as ADVENTUREWORKS\Student ad with the password Pa$$w0rd.
as
!
2. In the D:\Labfiles\Lab04\Starter folder, right-click Setup.cmd and then click Run as administrator.

3. In the User Account Control dialog box, click Yes, and then wait for the script to finish.

Es
s
ed
oc
Não a SELECT
Task 2: Write um Statement that Uses an Inner Join
ép en
r t
erm na o pe
o
itid ldoo rten
or t c
ea toni@ e a R
1. On the virtual machine, l i z o
gm Taskbar,
ar on the click SQL Server 2014 Management Studio. In the Connect to
có ail nald
Server window, type MIA-SQL . oO
pia incothe Server
sn m tto name text box and click Connect.
ão ni.
au
2. On the File menu, click Open and click tor Project/Solution.
iza
da
s!
3. In the Open Project window, open the project D:\Labfiles\Lab04\Starter\Project\Project.ssmssln.

4. In Solution Explorer, double-click the query 51 - Lab Exercise 1.sql. (If Solution Explorer is not visible, select
Solution Explorer on the View menu or press Ctrl+Alt+L on the keyboard).

5. When the Esquery window opens, highlight the statement USE TSQL; and click Execute on the toolbar (or
se
do
press
Nã F5 on the cukeyboard).
oé me
pe ron nto
a pe
6. In the queryrmpane,
itid ldtype
o the rte following query after the task 1 description:
o r otto nce
ea n aR
liza i@g
rc ma ona
óp il ld
SELECT ias .com o Ot
nã ton
p.productname, c.categoryname oa i.
uto
FROM Production.Products AS p izad r
as
INNER JOIN Production.Categories AS! c ON p.categoryid = c.categoryid;

7. Highlight the written query and click Execute.

8. ObserveEthe
ss result and answer these questions:
ed
oc
Nã um
oé en
pe r o to
rm nald pert
itid o e
o r otto nce
o Which column ni@ specify
ea did you a as a predicate in the ON clause of the join? Why?
liza
r gm Ron

In this query, the categoryid a
ail column
pia .co ldo O is the predicate. By intuition, most people would say that it is the
s m
predicate because this column existstt in both input tables. By the way, using the same name for columns
that contain the same data but in different tables is a good practice in data modeling. Another possibility

https://www.skillpipe.com/#/reader/urn:uuid:91ddbb8d-bb35-443c-9b77-1e5f0f71fa17@2020-12-11T07:01:36Z/content 1/6
09/03/2021 Lab Answer Key: Module 4: Querying Multiple Tables

is to check for referential integrity through primary and foreign key information using SQL Server
Management Studio. If there are no primary or foreign key constraints, you will have to acquire
information about the data model from the developer.
o Let us say that there is a new row in the Production.Categories table and this new product category
does not have any products associated with it in the Production.Products table. Would this row be
included in the result of the SELECT statement written under the task 1 description?

No, because anEs inner join retrieves only the matching rows based on the predicate from both input tables. Since the
se
new value for the do
categoryid is not present in the categoryid column in the Production.Products table, there would
Nã cu
o me
é p rowsroin the
be no matching ntoresult of the SELECT statement.
erm na pe
itid ldoo rten
or tto ce
ea n aR
liza i@g
r ma ona
Result: After this exercise, you cóp should
il know ld how to use an inner join between two tables.
ias .com o Ot
nã ton
oa i.
uto
riz
Exercise 2: Writing Queries That UseadMultiple-Table as Inner Joins
!

Task 1: Execute the T-SQL Statement

Es
1. In Solution seExplorer, double-click the query 61 - Lab Exercise 2.sql.
do
Nã cu
o me
2. When theé p query r nt
window opens, highlight the statement USE TSQL; and click Execute.
erm na o pe
o
itid l d oo rten
o r query t ce the Task 1 description and click Execute.
3. Highlight the written ea toni@under aR
liza o
r c gmai nald
4. Observe that you get the error ó l .
pia message:
c oO
s n om tto
ão ni.
au
tor
iz
Ambiguous column name 'custid'. adas
!

5. This error occurred because the custid column appears in both tables and you have to specify from which
table you would like to retrieve the column values.
Es
eds
oc
Nã um
oé en
r t
erm na o Changes
Task 2: Applypthe Needed
o pe and Execute the T-SQL Statement
itid l d oo rten
or t c
ea toni@ e a R
liza
rc g ma ona
1. Copy the T-SQL statement óp fromil ldo In the query window, click the line after the Task 2 description. On the
ias .cTask
om 1. Ot
nã ton
toolbar, click Paste. oa i.
uto
riz
2. Add the column prefix “Customers” to the ad existing query so that it looks like this:
as
!

SELECT
Customers.custid, contactname, orderid
FROM Sales.Customers
Es
se Sales.Orders ON Customers.custid = Orders.custid;
INNER JOINd oc
Nã um
o ép en
r t
erm ona o pe
itid l d o rte
3. o r otquery
Highlight the modified ncand click Execute.
ea toni@ e a R
liza o
r c gmai nald
óp l.c
ias om o Ot
t
Task 3: Change the Table Aliases

https://www.skillpipe.com/#/reader/urn:uuid:91ddbb8d-bb35-443c-9b77-1e5f0f71fa17@2020-12-11T07:01:36Z/content 2/6
09/03/2021 Lab Answer Key: Module 4: Querying Multiple Tables

1. Highlight the previous query. On the toolbar, click Edit and then Copy.

2. In the query window, click the line after the task 3 description. On the toolbar, click Edit and then Paste. You
have now copied the previous query to the same query window after the task 3 description.

3. Modify the T-SQL statement to use table aliases. Your query should look like this:

SELECT
E
ss c.contactname, o.orderid
c.custid,e do
cu
Nã Sales.Customers
FROM
oé m AS c
e
pe ron nto
INNER JOIN pe
rm Sales.Orders
a AS o ON c.custid = o.custid;
itid ldoo rten
or tto ce
ea ni@ a Ro
liza
r c gmai nald
4. ó
Highlight the written querypand l . oO
co Execute.
ias clickm tto
nã ni.
oa
5. Compare the results with the Task 2 utoresults.
riz
ad
as
!
6. Modify the T-SQL statement to include a full source table name as the column prefix. Your query should now
look like this:

SELECT
ss E
Customers.custid, Customers.contactname, Orders.orderid
e do
FROM cu
Nã Sales.Customers AS c
oé m en
pe ron to
INNER JOIN
rm Sales.Orders
a pe AS o ON c.custid = o.custid;
itid ldoo rten
o tt c ea
rea on
Ro
liza i@
g
rc
ó
m ail nald
7. Highlight the written querypand .
ias click oO
co Execute.
m tto
nã ni.
oa
8. u
Observe that you get the error messages: tor
iza
da
s!

Msg 4104, Level 16, State 1, Line 2


The multi-part identifier "Customers.custid" could not be found.
Msg 4104, Level 16, State 1, Line 2
The multi-part
E identifier "Customers.contactname" could not be found.
ss
Msg 4104,e dLevel
o 16, State 1, Line 2
N cu
Theãomulti-part
m
eidentifier "Orders.orderid" could not be bound.
é n
ron to
pe
rm ald per
itid o te
o r otto nce
ea n aR
liza i@g
You received these error ma onaas, because you are using a different table alias, the full source table
r c messages
óp il.c ld
name you are referencing as om oprefix
iasa column Ot
nã ton no longer exists. Remember that the SELECT clause is
oa i.
evaluated after the FROM clause, so uto you must use the table aliases when specifying columns in the SELECT
riz
clause. ad
as
!
9. Modify the SELECT statement so that it uses the correct table aliases. Your query should look like this:

SELECT Es
s e
do
c.custid, c.contactname, o.orderid
Nã c um
ép o
FROM Sales.Customers en AS c
t
erm rona o pe
itid l d
INNER JOIN Sales.Orders oo rAS
ten o ON c.custid = o.custid;
or tto ce
ea n aR
liza i@g
rc ma ona
óp il ld
ias .com o Ot
t
Task 4: Add an Additional Table and Columns

https://www.skillpipe.com/#/reader/urn:uuid:91ddbb8d-bb35-443c-9b77-1e5f0f71fa17@2020-12-11T07:01:36Z/content 3/6
09/03/2021 Lab Answer Key: Module 4: Querying Multiple Tables

1. In the query pane, type the following query after the task 4 description:

SELECT
c.custid, c.contactname, o.orderid, d.productid, d.qty, d.unitprice
FROM Sales.Customers AS c
INNER JOIN Sales.Orders AS o ON c.custid = o.custid
INNER JOIN Sales.OrderDetails AS d ON d.orderid = o.orderid;
Es
s ed
oc
Nã um
oé en
2. Highlightpthe written
r query
t and click Execute.
erm na o pe
o
itid ldoo rten
t
o r Remember c
3. Observe the result. ea toni@ e athat, Ro
when you have a multiple-table inner join, the logical query processing is
liza g
different from the physical m n
r c implementation.
ald In this case, it means that you cannot guarantee the order in which
óp ail.c
ias om o Ot
the SQL Server optimizer will process nã the ttables.
on For example, you cannot guarantee that the
oa i.
Sales.Customers table will be joined utofirst with the Sales.Orders table, and then with the Sales.OrderDetails
riz
table. ad
as
!

Result: After this exercise, you should have a better understanding of why aliases are important and how to do a
multiple-table join.
Es
s ed
oc
um Queries That Use Self Joins
Nã 3: Writing
Exercise o ép e nt
erm rona o pe
itid l d o rte
o r otto nce
ea n aR
Task 1: Write a Basic SELECT liza i@Statement o
r c gmai nald
óp l.c
ias om o Ot
nã ton
oa i.
uto
1. In Solution Explorer, double-click the query riz 71 - Lab Exercise 3.sql.
ad
as
!
2. When the query window opens, highlight the statement USE TSQL; and click Execute.

3. In the query pane, type the following query after the task 1 description:

SELECTEs
se
do
e.empid, e.lastname, e.firstname, e.title, e.mgrid
Nã c um
FROMo HR.Employees
ép ro
en AS e;
to
erm na
ldo perte
itid
o r otto nce
ea n aR
liza i@g
r ma ona
4. Highlight the written query cópand iclick
l ld
Execute.
ias .com o Ot
nã ton
i
5. Observe that the query retrievedonine au rows. .
tor
iza
da
s!

Task 2: Write a Query that Uses a Self Join

1. HighlightEsthe previous query. On the toolbar, click Edit and then Copy.
se
do
Nã query window,cu
2. In theoé me click the line after the task 2 description. On the toolbar, click Edit and then Paste. You
pe r on nto p
have now copied
rm athe previous
e query to the same query window after the task 2 description.
itid ldoo rten
or tto ce
e ni a
3. Modify the query byaliadding
za @gamselfRojoinna to get information about the managers. The query should look like this:
rc
óp ail.c ld
ias om o Ot
t

https://www.skillpipe.com/#/reader/urn:uuid:91ddbb8d-bb35-443c-9b77-1e5f0f71fa17@2020-12-11T07:01:36Z/content 4/6
09/03/2021 Lab Answer Key: Module 4: Querying Multiple Tables

SELECT
e.empid, e.lastname, e.firstname, e.title, e.mgrid,
m.lastname AS mgrlastname, m.firstname AS mgrfirstname
FROM HR.Employees AS e
INNER JOIN HR.Employees AS m ON e.mgrid = m.empid;

4. HighlightE the written query and click Execute.


ss
ed
oc
5. Nã
Observe
oé that theumquery
e retrieved eight rows and answer these questions:
pe ron nto
rm a pe
itid ldoo rten
or tto ce
ea n aR
liza i@g
rc ma ona
il
óp table ld
o Is it mandatory to use ias .caliases
om o Owhentto
writing a statement with a self join? Can you use a full source
nã ni.
table name as an alias? o a
ut
You must use table aliases. Youorcannot iza use the full source table name as an alias when referencing
da
s!
both input tables. Eventually, you could use a full source table name as an alias for one input table and
another alias for the second input table.
o Why did you get fewer rows in the result from the T-SQL statement under the task 2 description
compared to the result from the T-SQL statement under the task 1 description?

Es
se
In task 2’s T-SQL do
statement, the inner join used an ON clause based on manager information (column mgrid). The
Nã cu
o me
employee who é pis theroCEO ntohas a missing value in the mgrid column so this row is not included in the result.
erm na pe
itid ldoo rten
or tto ce
ea n aR
liza i@g
Result: After this exercise,ryou ma onhaveal an understanding of how to write T-SQL statements that use self
có should
pia il.co do O
joins. sn m tto
ão ni.
au
tor
iza
da
s!
Exercise 4: Writing Queries That Use Outer Joins

Task 1: Write a SELECT Statement that Uses an Outer Join

Es
s ed
1. In Solution oc
Explorer,
Nã um double-click the query 81 - Lab Exercise 4.sql.
oé e
pe ron nto
r a
mi window pe
2. When the query tid ldoot opens, rte
nc
highlight the statement USE TSQL; and click Execute.
or to e
ea n i@ aR
liza the
3. In the query pane, type ma onaquery after the task 1 description:
r c gfollowing
óp il ld
ias .com o Ot
nã ton
oa i.
SELECT uto
riz
ad
c.custid, c.contactname, o.orderid as
!
FROM Sales.Customers AS c
LEFT OUTER JOIN Sales.Orders AS o ON c.custid = o.custid;

4. HighlightEsthe
se written query and click Execute.
do
Nã cu
5. Inspect o éthe result.mNotice
e that the custid 22 and custid 57 rows have a missing value in the orderid column.
pe r on nto p
r
This is because mi therea e
tid ldootarertno e rows in the Sales.Orders table for these two values of the custid column. In
business terms, this
or ton nthat
ea means
ce
there are currently no orders for these two customers.
aR
liza i@g
rc ma ona
óp il ld
ias .com o Ot
t
Result: After this exercise, you should have a basic understanding of how to write T-SQL statements that use
outer joins.

https://www.skillpipe.com/#/reader/urn:uuid:91ddbb8d-bb35-443c-9b77-1e5f0f71fa17@2020-12-11T07:01:36Z/content 5/6
09/03/2021 Lab Answer Key: Module 4: Querying Multiple Tables

Exercise 5: Writing Queries That Use Cross Joins

Task 1: Execute the T-SQL Statement

1. In Solution Explorer, double-click the query 91 - Lab Exercise 5.sql.


Es
se
do
2. When Nã the querycuwindow
me opens, highlight the statement USE TSQL; and click Execute.

pe ron nto
rmT-SQL a pe
3. Highlight the itid ldocode rtunder
e the task 1 description and click Execute. Don’t worry if you do not
o r otto nce
ea
understand the provided ni@ a code, as it is used here to provide a more realistic example for a cross join in
liza T-SQL gm Ron
the next task. r c a il ald
óp
ias .com o Ot
nã ton
oa i.
uto
riz
ad
a
Task 2: Write a SELECT Statement that Uses sa! Cross Join

1. In the query pane, type the following query after the task 2 description:

Es
s
ed
SELECT oc
Nã um

e.empid, e
e.firstname, e.lastname, c.calendardate
pe ron nto
r mi a p e
tid ldoot ASrteenc
FROM HR.Employees
or
ea toni@ eASa Rc;
CROSS JOIN HR.Calendar liza o
r c gmai nald
óp l.c
ias om o Ot
nã ton
oa i.
2. Highlight the written query and click utExecute.
ori
za
da
s
3. Observe that the query retrieved 3,285 rows! and that there are nine rows in the HR.Employees table.
Because a cross join produces a Cartesian product of both inputs, it means that there are 365 (3,285/9) rows
in the HR.Calendar table.

Es
se
do
Task 3: Drop the HR.Calendar Table
Nã cu
oé me
ro nto
pe
rm nald pert
itid o e
o r otto nce
1. Highlight the written ea query ni@under a Rthe task 3 description and click Execute.
liza o
r c gmai nald
óp l.c
ias om o Ot
nã ton
oa i.
Result: After this exercise, you should uhave tor an understanding of how to write T-SQL statements that use cross
iza
joins.. da
s!

Es
s ed
oc
Nã um
o ép en
r t
erm ona o pe
itid l d o rte
o r otto nce
ea ni@ aR
liza o
r c gmai nald
óp l.c
ias om o Ot
t

https://www.skillpipe.com/#/reader/urn:uuid:91ddbb8d-bb35-443c-9b77-1e5f0f71fa17@2020-12-11T07:01:36Z/content 6/6

You might also like