0% found this document useful (0 votes)
177 views24 pages

CS669 - Lab2 Instructions

CS669 Lab2

Uploaded by

berkleeb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
177 views24 pages

CS669 - Lab2 Instructions

CS669 Lab2

Uploaded by

berkleeb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

MET CS 669 Database Design and Implementation for Business

SQL Lab 2 Instructions: Interconnecting Data

OBJECTIVE
Theobjectiveofthislabistoprovideyouwithapracticalexerciseofcreatingand
usingrelateddatausingtheStructuredQueryLanguage(SQL).Together,wewill
learnhowto:
enforcerelationshipsbetweentwotablesusingaFOREIGNKEYconstraint
addrelateddatatorelatedtables
askquestionsandanswerthemusingSQLqueriesthatrelatedata

PREREQUISITES
Beforeattemptingthislab,itisbesttoreadthetextbookandlecturematerial
coveringtheobjectiveslistedabove.Whilethislabshowsyouhowtocreateanduse
theseconstructsinSQL,thelabdoesnotexplaininfullthetheorybehindthe
constructs,asdoesthelectureandtextbook.

REQUIREDSOFTWARE
TheexamplesinthislabwillexecuteinmodernversionsofOracleandMicrosoftSQL
Serverasis.IfyouhavebeenapprovedtouseadifferentRDBMS,youmayneedto
modifytheSQLforsuccessfulexecution,thoughtheSQLshouldexecuteasisifyour
RDBMSisANSIcompliant.

ThescreenshotsinthislabdisplayexecutionofSQLintheOracleSQLDeveloper
clientandinMicrosoftSQLServerManagementStudio.Notethatifyouareusing
Oracle,youarenotrequiredtouseOracleSQLDeveloper;therearemanycapable
SQLclientsthatconnecttoOracle.

Page1of24
Copyright20122014BostonUniversity.AllRightsReserved.

SAVINGYOURDATA
Ifyouchoosetoperformportionsofthelabindifferentsittings,itisimportantto
commityourdataattheendofeachsession.Thisway,youwillbesuretomake
permanentanydatachangesyouhavemadeinyourcurentsession,sothatyoucan
resumeworkingwithoutissueinyournextsession.Todoso,simplyissuethis
command:

COMMIT;

Wewilllearnmoreaboutcommittingdatainfutureweeks.Fornow,itissufficientto
knowthatdatachangesinonesessionwillonlybevisibleonlyinthatsession,unless
theyarecommitted,atwhichtimethechangesaremadepermanentinthe
database.

LABCOMPLETION
Usethesubmissiontemplateprovidedintheassignmentinboxtocompletethislab.

Page2of24

SECTIONONE
OVERVIEW
InSectionOne,wewillworkwiththeRestaurantandMealtablesillustratedbelow.The
relationshipbetweenthesetwotablesisdescribedbythefollowingbusinessrules:

ARestaurantmayservemanyMeals
AMealmaybeservedataRestaurant

NotethattheboldedcolumnsrepresentthosewithaNOTNULLconstraint.Furthernote
thatrestaurant_idinMealisaforeignkeyreferencingtheRestauranttable.Itisthis
foreignkeythatenforcestheonetomanyrelationshipbetweenMealandRestaurant.

Page3of24

STEPS

1. ExecutethefollowingcommandstocreatetheRestaurantandMealtables.Make
suretotypethecommandsexactlyasillustrated,includingspaces,parentheses,and
newlines.

CREATE TABLE Restaurant (


restaurant_id DECIMAL(12) PRIMARY KEY,
name VARCHAR(64) NOT NULL
);

CREATE TABLE Meal (


meal_nr DECIMAL(12) NOT NULL,
description VARCHAR(255) NOT NULL,
date_served DATE NOT NULL,
restaurant_id DECIMAL(12)
);
ALTER TABLE Meal
ADD CONSTRAINT meal_pk
PRIMARY KEY(meal_nr);

Thestructureofthefirsttwocommandsarefamiliartousfrompreviouslabs.We
havenotyetseentheALTERTABLEcommandinpreviouslabs,soletusexplorewhat
thiscommandisaccomplishing.AnALTERTABLEcommandletsusmodifyallaspects
ofthestructureofatable.AnypropertywecanspecifyinaCREATETABLE
statement,wecanchangeusinganALTERTABLEstatement.Thiscommandisquite
usefulbecauseinproductionsystemswithlivedata,wecannotalwaysdropandre
createanexistingtableinordertomakechangestoit.Instead,weusetheALTER
TABLEstatement.

TheALTERTABLEcommandaddsaprimarykeyconstrainttotheMealtable.Whyis
thisneeded?IfyouexaminetheCREATETABLEfortheMealtable,youllnoticethat
noprimarykeyconstraintispresent.Thiswasleftoutpurposefullytoshowyou
anothermethodofspecifyingprimarykeyconstraints,byusingtheALTERTABLE
commandafterthetableiscreated.Becausetherearemanykindsofchangeswecan
makewithanALTERTABLEcommand,weusedthewordsADDCONSTRAINT
keywordstoindicatethatwearespecificallyaddingaconstraint.

Justaswenametableswithanidentifier,wecannameconstraints.Ifweusethe
shorthandmethodofaddingconstraintsbyincludingthemaspartofacolumn
definitioninaCREATETABLEstatement,suchaswiththeCREATETABLEstatement
thatcreatestheRestauranttable,theRDBMSgeneratesaconstraintnameforus.
Thisisknownasasystemgeneratedconstraintname.Sowhywouldwewantto
nameourconstraints?Systemgeneratednamesusuallydonothelpusidentifythe
table,column,orconditionenforcedbytheconstraint.IfoneofourSQLcommands

Page4of24

violatesaconstraintthathasasystemgeneratedname,oftentimesweneedto
lookuptheconstrainttofindtheconditionthathasbeenviolated.Ifwenameour
constraints,manytimeswewillknowtheconditionbytheconstraintsname,and
canavoidthelookup.

ThewordfollowingtheADDCONSTRAINTkeywords,meal_pkinthiscase,isthe
identifierthatnamesourconstraint.Thoughwecouldhaveusedanylegalidentifier
ofourchoosing,weusedthenameofthetable,followedbypkasanacronymfor
primarykey,toindicatethattheconstraintistheprimarykeyconstraintforthe
Mealtable.Therearemanyconventionsthatcanbeusedwhennamingconstraints,
andmanyorganizationsadopttheirownconventions.Oneimportantaspectofany
namingconventionisconsistency,sothattheconventioncanbeunderstood,andso
thatthereaderisnotrequiredtoguessatwhatthenameoftheconstraintmeans.

ThePRIMARYKEYkeywordsfurtherindicatetotheRDBMSthatweareaddinga
PRIMARYKEYconstraint.Thesyntaxrequiresustothenencloseacommaseparated
listofcolumnnameswithinparentheses.Thecolumnsspecifiedinthislistwillallbe
coveredbythenewprimarykeyconstraint.Inourexample,weaddedonlyone
columnmeal_nrtoindicatethatonlythemeal_nrcolumniscoveredbythe
primarykeyconstraint.

Page5of24

2. Captureascreenshotofthecommandandtheresultofitsexecution.Belowisa
samplescreenshotofthecommandexecutioninOracleSQLDeveloper.

Page6of24

BelowisasamplescreenshotofthecommandexecutioninMicrosoftSQLServer
ManagementStudio.

3. Wewillnowbeginharnessingthemostusefulandpowerfulfeatureofarelational
databaserelateddata!Relateddata,andtheabilitytoaskplannedandunplanned
questionsaboutthisdata,aretheindemandfeaturesofRDBMSstoday,andenable
ustosolveawidevarietyofproblemsusinganRDBMS.

Thefirststeptorelatingdataissettingupthestructureofthetablestoenforcethe
relationshipsweexpect.Wedothisbycreatingaforeignkeyconstraint.Inour
relationalschema,theMealtablehasaforeignkeytotheRestauranttable.Letusgo
aheadandcreatethatforeignkeyconstraint.

ALTER TABLE Meal


ADD CONSTRAINT meal_restaurant_fk
FOREIGN KEY(restaurant_id)
REFERENCES Restaurant(restaurant_id);

Page7of24

WehaveusedanotherformoftheALTERTABLEcommandwhichwelearnedabout
insteps1and2.ThefirsttwolineshavethesameformatastheALTERTABLE
commandinstep1,thoughwediduseadifferentidentifier,meal_restaurant_fk,
toindicatethattheconstraintdefinesaforeignkeyfromtheMealtabletothe
Restauranttable.Thelettersfkareanacronymtorepresentforeignkey.

Thenextkeywords,FOREIGNKEY,indicatetotheRDBMSthattheconstraintweare
addingisaforeignkeyconstraint.TheRDBMSexpectsacommaseparatedlistof
columnnamesenclosedinparenthesestofollowtheFOREIGNKEYkeywords.Inour
case,onlytherestaurant_idcolumniscoveredbytheforeignkeyconstraint,andso
wehaveidentifiedonlythatcolumn.Notethatthislistofcolumnsidentifiesthe
columnswithinthetablewearealtering,inthiscase,theMealtable.

Thenextkeyword,REFERENCES,indicatesthatwhatfollowsarethetableandcolumn
identitiesthattheforeignkeywillreference.Thefirstfollowingword,Restaurant,
indicatesthattheforeignkeywillreferencetheRestauranttable.Followingthisisa
secondcommaseparatedlistofcolumnnamesenclosedwithinparentheses,
indicatingthatnamesofthecolumnsthatwillbereferencedinthereferencedtable,
inthiscase,Restaurant.

Soinsummary,thefirstcommaseparatedlistidentifiesthecolumnswithinthetable
containingtheforeignkeyconstraint,whilethesecondcommaseparatedlist
identifiesthecolumnswithinthereferencedtable..Inourcase,weonlyhaveone
columnidentifiedineachtablebecauseourforeignkeyspansonlyonecolumn.This
isthecommoncase.

Ifyouworkwithdatabaseslongenough,youwillrunintoasituationwherea
compositeforeignkeycoveringmorethanonecolumnisinuse.Whendefiningthe
constraintforcompositeforeignkeys,thefirstcolumnidentifiedinthefirstlist
referencesthefirstcolumninthesecondlist,thesecondcolumnidentifiedinthe
firstlistreferencesthesecondcolumninthesecondlist,andsoon.

Page8of24

4. Captureascreenshotofthecommandandtheresultofitsexecution.Belowisa
samplescreenshotofthecommandexecutioninOracleSQLDeveloper.

BelowisasamplescreenshotofthecommandexecutioninMicrosoftSQLServer
ManagementStudio.

5. NowthatwehaveenforcedtherelationshipbetweenMealandRestaurantusinga
foreignkeyconstraint,letusaddinsomerelateddatausingthealreadyfamiliar
INSERTINTOcommand.

INSERT INTO Restaurant (restaurant_id, name)


VALUES (31, 'Sunset Grill');
INSERT INTO Restaurant (restaurant_id, name)
VALUES (32, 'Oceanside Beachview');

INSERT INTO Meal (meal_nr, description, date_served, restaurant_id)


VALUES (101, 'Grilled eggplant with sides', CAST('03-Jul-2012' AS DATE), 31);
INSERT INTO Meal (meal_nr, description, date_served, restaurant_id)
VALUES(102, 'Delicious pizza with salad', CAST('09-Jul-2012' AS DATE), 31);
INSERT INTO Meal (meal_nr, description, date_served, restaurant_id)
VALUES(103, 'Five-course luxurious meal', CAST('13-Jul-2012' AS DATE), NULL);

Page9of24

Letusexaminetheseinsertionstodeterminetherelationshipsbetweenthedata.
ThefirsttwoinsertcommandssimplyinserttworestaurantsIDsandnames,and
alonedonotcreateanyrelationships;itistheinsertionsintotheMealtablethat
createtherelationships.How?ThefirstthreevaluesineachMealinsertionare
standarddata,butthefourthvalue,theforeignkey,isofinterest.Noticethat31is
theIDforthefirstSunsetGrillRestaurant,andthatthefirsttwomealshave31as
theirrestaurant_idvalue.Howshouldweinterpretthis?Simple!Thefirsttwomeals
wereservedattheSunsetGrillRestaurant.

Doyouseehowthisworks?Todeterminerelatedrows,wearematchingupthe
valueintheforeignkeycolumninthereferencingtabletothevalueinthe
referencedcolumninthereferencedtable,inourexample,therestaurant_idvalues
intheMealtabletotherestaurant_idvaluesintheRestauranttable.Inshort,the
samevalueintwodifferentrowsindicatesarelationshipbetweenthoserows.

HowshouldweinterprettheNULLintherestaurant_idcolumnforthethirdmeal?
Again,simple!Thethirdmealhasnoindicationoftherestaurantthatservedit,sowe
knowthemealwasnotservedattheSunsetGrillRestaurantortheOceanside
BeachviewRestaurant.Simplyput,therestaurantthatservedthethirdmealis
unknown.

WehavedeterminedtherelationshipsbetweentheSunsetGrillRestaurantandits
meals,andhavealsodeterminedthatthethirdmealdoesnotspecifyarestaurant,
butwhatabouttheOceansideBeachviewRestaurant?BecausenoMealrowshavea
foreignkeyvaluecorrespondingtoOceansideBeachviewsprimarykey,32,that
restauranthasservednomeals.

Page10of24

6. Captureascreenshotofthecommandandtheresultofitsexecution.Belowisa
samplescreenshotofthecommandexecutioninOracleSQLDeveloper.

Page11of24

BelowisasamplescreenshotofthecommandexecutioninMicrosoftSQLServer
ManagementStudio.

7. WhatifweattempttoinsertaMealthatreferencesanonexistentRestaurant,by
usinganinvalidrestaurant_id?TheRDBMSwillimmediatelyrejectthestatement
becauseitviolatestheforeignkeyconstraint.Letustryit.

INSERT INTO Meal (meal_nr, description, date_served, restaurant_id)


VALUES(104, 'Juicy entree and french fries', CAST('17-Jul-2012' AS DATE), 57);

Page12of24

8. Captureascreenshotofthecommandandtheresultofitsexecution.Belowisa
samplescreenshotofthecommandexecutioninOracleSQLDeveloper.

NoticethatOraclereportsanerrormessageindicatingthattheconstraint
ASSIGNMENTUSER1659.MEAL_RESTAURANT_FKhasbeenviolated.
ASSIGNMENTUSER1659wastheschemausedwhencreatingthislab,andthatyour
schemawillbedifferent.Alsorecallthatmeal_restaurant_fkisthenamewe
ascribedtheforeignkeyconstraint.Nowyouseethevalueofnamingtheconstraint,
sincewecandeterminethatthemealtorestaurantforeignkeyhasbeenviolated
withoutlookinguptheconstraint.

Oracleprovidesthistext,parentkeynotfound,asanindicationthatweattempted
toinsertavalueintoareferencingcolumn,thatdoesnotexistinareferenced
column.Inourexample,weattempttoinsertrestaurant_id57,whichdoesnotexist
intheRestauranttable.Nowyouseehowtheforeignkeyconstrainthelpsenforce
therelationshipbetweenMealandRestaurant.AllreferencesfromMealto
Restaurantwillbevalidbecauseofthepresenceoftheforeignkeyconstraint.Any
attempttoinsertaninvalidreferenceisrejectedbytheRDBMS.

Page13of24

BelowisasamplescreenshotofthecommandexecutioninMicrosoftSQLServer
ManagementStudio.

NoticethatjustasOraclerejectedthestatement,sodidSQLServer,indicatingthat
theforeignkeyconstraintmeal_restaurant_fkwouldbeviolated.Someofthetext
oftheerrormessageistruncated,soitisreproducedbelow:

Msg 547, Level 16, State 0, Line 1


The INSERT statement conflicted with the FOREIGN KEY constraint
"meal_restaurant_fk". The conflict occurred in database "cs6692",
table "dbo.Restaurant", column 'restaurant_id'.
The statement has been terminated.

ThiserrormessagemaybeeasiertointerpretthanthecorrespondingOracleerror
message,becauseitalsoindicatesthetableandcolumnthatparticipatedinthe
attemptedforeignkeyviolation.Sowehavethenameoftheconstraint,
meal_restaurant_fk,aswellasanindicationfromtheRDBMSofthetableand
column,removingallambiguity.Notethatdatabasecs6692wasthedatabaseused
whencreatingthislab,andyourswilllikelybedifferent.

9. Wehavecreatedthetablestructureforourrelationship,andalsoinsertedrelated
data.Nowletuslearntoretrieveourrelateddatainameaningfulway.

Whenweretrievedata,generallywearenotaimlesslyorrandomlyretrievingrows
andcolumnsfromtables;rather,weareansweringaspecificquestionforaspecific
purpose.Forexample,amanagermaybegatheringsomegeneralinformationon
customers,orawebservermaybegeneratingawebpagethatlistsallprevious
ordersplacedbyacustomer.Thoughtherearewidelyvariedquestionstobe
answeredandwidelyvariedpurposesforansweringthem,thesamekindsofSQL
constructscanbeusedforallofthem.

Thequestiontobeansweredcanbesimpleorcomplex,butletusstartwithasimple
question.

Page14of24

Whichmealswereservedbywhichrestaurants?

Thisgeneralquestiongivesusadirection,butweneedmoredetails,namely,
preciselywhatpropertiesofrestaurantsandmealswearelookingfor.Doweneed
theIDs?Doweneedthenamesordescriptions?Doweneeddates?Weneedto
constructourrequesttobespecificenoughtobeimplemented.Letusthenposea
morespecificrequest:

Listthedescriptionanddateservedofallofthemealsservedatarestaurant,andthe
nameoftherestaurantthatservedthemeal.

ThisrequestrequiresdatafromtwotablesRestaurantandMealandwecanfulfill
thisrequestusingaSELECTstatementwithaJOINclause.Trythecommandbelow.

SELECT description, date_served, name


FROM Meal
JOIN Restaurant ON Meal.restaurant_id = Restaurant.restaurant_id;

LetusexaminethisSQLcommandpiecebypiece.Onthefirstline,youseethe
familiarSELECTkeywordalongwiththecolumnnamestoberetrieved.Weretrieved
specificallythedescription,date_served,andnamecolumns.Onthesecondline,you
seethefamiliarFROMkeywordalongwiththenameofthetable.Itisthethirdline
thatintroducestheJOINkeyword.TheJOINinthisstatementindicatesthattheMeal
tablewillbejoinedwiththeRestauranttable.TheONkeywordindicatesthejoin
condition,whichisaBooleanexpressionthatcanusethecolumnsintheMealand
Restauranttables.

RecallthatajoinwithnojoinconditionbetweentwotablesisaCartesianproduct.If
weaddajoincondition,thenweareselectingspecificrowsfromtheresultsofthe
Cartesianproduct.Inotherwords,thejoinconditionisevaluatedforeveryrowinthe
Cartesianproducttodeterminewhichrowswillbeselected.Inthisexample,ourjoin
condition:

Meal.restaurant_id = Restaurant.restaurant_id

indicatesthatweonlywanttherowsfromtheCartesianproductwherethe
restaurant_idvaluesareequalinthetwotables.InplainEnglishthismeanswewant
onlywantthemealsthatwereservedatrestaurants,andonlytherestaurantthat
servedthemealwillbelistedwithameal.

Page15of24

10. Captureascreenshotofthecommandandtheresultofitsexecution.Belowisa
samplescreenshotofthecommandexecutioninOracleSQLDeveloper.

BelowisasamplescreenshotofthecommandexecutioninMicrosoftSQLServer
ManagementStudio.

Theresultsetatthebottomisexactlywhatweexpected.Thefirsttwomeals
descriptionsanddatesservedwerelisted,alongwiththeRestauranttheywere
servedat,theSunsetGrill.WehavesatisfiedtherequestinStep9infull.Thisis
exciting!WehavelearnedtoretrieverelateddatausingasingleSQLcommand!

Thekindofjoinillustratedaboveisknownasaninnerjoin.Thereareseveral
differentwaysinSQLtospecifyinnerjoins,andthesearecoveredinthetextbook
andlectures.However,thestyleusedaboveisdefinedintheANSIstandardsandis
therecommendedstyletouseformaximumportabilityandeaseofuse.

Page16of24

11. Althoughinnerjoinscanbeusedtofulfillmanyrequestswehavewithourrelated
data,somerequestscanonlybeansweredwithanouterjoin.Forexample,wecould
notuseaninnerjointofulfillthisrequest:

Listthedescriptionanddateservedofallofthemeals,andifthemeal
wasservedatarestaurant,listthenameoftherestaurantthatserved
themeal.

DoyouseethedifferencebetweenthisrequestandtherequestinStep9?The
requestinStep9onlyasksformealsthatwereservedatrestaurants.Therequestin
thisstephoweverisaskingforallmeals,whetherornottheywereservedata
restaurant.Wewillfulfillthisrequestbyusingaleftouterjoin.Weonlyneedadd
onewordtotheSQLquerylistedinStep9todoso.

SELECT description, date_served, name


FROM Meal
LEFT JOIN Restaurant ON Meal.restaurant_id = Restaurant.restaurant_id;

WhatdoesthisLEFTkeyworddoforus?ItinstructstheRDBMStoretrieveallrows
thatmatchthejoincondition,andalsoretrieverowsfromthefirsttablelistedthat
donotmatchthejoincondition.Inourexample,theMealtableisthefirsttable
listed,andsoanymealsthatdonothaverestaurantswillalsobelisted.Letustryit.

12. Captureascreenshotofthecommandandtheresultofitsexecution.Belowisa
samplescreenshotofthecommandexecutioninOracleSQLDeveloper.

Page17of24

BelowisasamplescreenshotofthecommandexecutioninMicrosoftSQLServer
ManagementStudio.

Noticethatinthisresultset,thetwomatchingrowsarelisted,justaswiththeinner
join,butathirdrowisalsolisted.Thefivecourseluxuriousmealislisted,andNULL
isindicatedfortherestaurantname.Thisisbecausewhenweinsertedourdata,the
fivecourseluxuriousmealwasnotgivenarestaurant_idbecauseitwasnotserved
atarestaurantwehadinoursystem.

13. Theinverserequestisstraightforward.;however,letusenhancetherequestby
introducinganotherrequirement,whichisthatofsortingtheresultsbaseduponthe
nameoftherestaurant.

Listthenameofallrestaurants,orderedalphabetically.Iftherestaurant
servedanymeals,listthedescriptionanddateservedofeachmeal.

WefulfillthisrequestbyusingarightouterjoinandanORDERBYconstruct.

SELECT description, date_served, name


FROM Meal
RIGHT JOIN Restaurant ON Meal.restaurant_id = Restaurant.restaurant_id
ORDER BY name;

Thedifferencebetweenarightouterjoinandaleftouterjoinisthatarightouter
joinretrievesrowsthatdonotmatchfromthesecondtablelisted,whilealeftouter
joinretrievesrowsthatdonotmatchfromthefirsttablelisted.

TheORDERBYconstructtellstheRDBMStosorttheresultsbaseduponthevaluesin
acolumnorgroupofcolumns.Acommaseparatedlistofcolumnnamesfollowsthe
ORDERBYkeywords.Inourexample,weonlywantedtosortbytherestaurantname,
andsowehavelistedonlyonecolumn.

Page18of24

14. Captureascreenshotofthecommandandtheresultofitsexecution.Belowisa
samplescreenshotofthecommandexecutioninOracleSQLDeveloper.

BelowisasamplescreenshotofthecommandexecutioninMicrosoftSQLServer
ManagementStudio.

Noticethatinthisresultset,thesecondandthirdrowsarethematchingrows,and
arethesamerowsreturnedwithbytheequivalentinnerjoin.Thefirstrowistherow
thatdoesnotmatchintheRestauranttable,resultingfromtherightouterjoinwe
performed.OceansideBeachviewistherestaurantname,andNULLisindicatedfor
theMealcolumns.Recallthatwhenweinsertedthedata,wedidnotindicatethat
theOceansideBeachviewRestaurantservedanymeals.

Page19of24

Furthernoticethattheresultshavebeenorderedjustaswespecified.SinceO
comesbeforeS,theOceansideBeachviewrestaurantisorderedbeforetheSunset
Grillrestaurant.IfwehadnotusedtheORDERBYconstruct,theOceanside
Beachviewrowwouldhavecomelast,sinceitwasinsertedaftertheSunsetGrill
rows.

15. Wecanalsoretrievematchingrowsandrowsthatdonotmatchinbothtables,
whichisacombinationofwhatwedidinSteps11and13.Belowisarequestthat
asksustodoso.

Listthedescriptionsanddatesservedofallmeals,andthenamesofall
restaurants.Showwhichrestaurantsservedwhichmeals.Thelistshould
besortedbythedescriptionsofthemealsinreversealphabeticalorder.

Thisrequestcanbefulfilledwithafullouterjoin,whichreturnsthematchingrows,
andalsorowsthatdonotmatchinboththefirstandsecondtables.Inshort,afull
outerjoinisacombinationofleftandrightouterjoins.Weagainneedtousethe
ORDERBYconstructtofulfillthesortingrequirement.

SELECT description, date_served, name


FROM Meal
FULL JOIN Restaurant ON Meal.restaurant_id = Restaurant.restaurant_id
ORDER BY description DESC;

WeaddedaqualificationtotheORDERBYconstructbyplacingtheDESCkeyword
afterthelistofcolumnnames.Therequestaskedustosortbythemealdescriptions
inreversealphabeticalorder.ThekeywordDESCisshortfordescending,meaning
thattheorderingwillbereversed.Whenwewanttosortinorder,wecaneitheruse
thekeywordASC,whichisshortforascending,orwecanomitthesewords
altogether,becauseascendingisthedefaultwhenORDERBYisused.

Page20of24

16. Captureascreenshotofthecommandandtheresultofitsexecution.Belowisa
samplescreenshotofthecommandexecutioninOracleSQLDeveloper.

BelowisasamplescreenshotofthecommandexecutioninMicrosoftSQLServer
ManagementStudio.

Page21of24

Noticethatinthisresultset,thetwomatchingrowsarelisted,justaswiththeinner
join.Inaddition,therowthatdoesnotmatchfromtheMealtableislisted,asisthe
rowthatdoesnotmatchfromtheRestauranttable.Theseresultswereasexpected
fromthefullouterjoinweusedabove.Weretrievedwhichmealswereservedat
whichrestaurants,retrievedthemealsthatwerenotservedatrestaurants,and
retrievedtherestaurantsthatdidnotserveanymeals.

Inthisresultset,themealdescriptionsweresortedinreversealphabeticalorderjust
aswespecifiedinourcommand.YoumayhavenoticedthattherowwiththeNULL
descriptionisfirstintheresultsetwithOracle,andlastwithSQLServer.Because
NULLrepresentsnovalueatall,oneRDBMSwilltreatitasgreaterthanallvalues,
whileanotherRDBMSwilltreatitaslessthanallvalues,asdemonstratedabove.This
smallexamplehashintedattheworldofnuancesandcomplexitiesthatexistwith
NULL.

Page22of24

SECTIONTWO
OVERVIEW
InSectionTwo,youwillapplywhatyoulearnedinSectionOnetonewtables,without
beinggiventhecommandsandscreenshots.YouwillworkwithDelivery_serviceand
Packagetablesthatarerelatedviaadeliversrelationship,allofwhichare
diagrammedbelow.NotethattheboldedcolumnsrepresentthosewithaNOTNULL
constraint.

STEPS

1. CreatetheDelivery_serviceandPackagetables,includingalloftheircolumns,
datatypes,andconstraints.Makesuretocreatetheforeignkeyconstraint.
2. Captureascreenshotofthecommandsandtheresultsoftheirexecution.
3. InsertthefollowingdeliveryservicesintotheDelivery_serviceusing
delivery_service_idsofyourchoosing.
UnitedPackageDelivery
FederalDelivery
DynamicDuoDelivery
4. Captureascreenshotoftheinsertcommandsandtheresultsoftheirexecution.
5. InsertthefollowingpackagesintothePackagetableusingpackage_nrvaluesofyour
choosing.

DeliveredbyUnitedPackageDelivery:
description=Perfectdiamonds
date_delivered=29Apr2012

DeliveredbyFederalDelivery:
description=Carepackage
date_delivered=14Jun2012

Page23of24

Nodeliveryservice:
description=Frenchwine
date_delivered=19Jul2012

6. Captureascreenshotoftheinsertcommandsandtheresultsoftheirexecution.
7. AttempttoinsertaPackagethatreferencesanonexistentdeliveryservice.
8. Captureascreenshotofthecommandandtheresultofitsexecution.
9. Explain:
a. whytheinsertioninStep7failed,and
b. howyouwouldinterprettheerrormessagefromyourRDBMSsothat
youknowthattheerrorindicatesthedeliveryserviceIDwasinvalid
10. Explainthesimilaritiesanddifferencesbetweenaninnerjoin,aleftjoin,arightjoin,
andafullouterjoin.
11. WithasingleSQLquery,fulfillthefollowingrequest:

Listthedescriptionanddatedeliveredofallpackagesdeliveredbyadeliveryservice,
aswellasthenameofthedeliveryservicethatdeliveredthepackage.

12. Captureascreenshotofthecommandandtheresultofitsexecution.
13. ExplainwhysomerowsinDelivery_serviceandsomerowsinPackagewerenot
listedinStep11.
14. WithasingleSQLquery,fulfillthefollowingrequest:

Listthenamesofalldeliveryservices,andifthedeliveryservicedeliveredany
packages,listthedescriptionsanddeliverydatesforthosepackages.

15. Captureascreenshotofthecommandandtheresultofitsexecution.
16. WithasingleSQLquery,fulfillthefollowingrequest:

Listthedescriptionanddatedeliveredofallpackages,andifthepackagewas
deliveredbyadeliveryservice,listthenameofthedeliveryservice.Thelistshouldbe
orderedalphabeticallybythenameofthedeliveryservice.

17. Captureascreenshotofthecommandandtheresultofitsexecution.
18. WithasingleSQLquery,fulfillthefollowingrequest:

Listthedescriptionsanddatesdeliveredofallpackages,andalsolistthenamesofall
deliveryservices.Indicatewhichpackagesweredeliveredbywhichdeliveryservices.
Thepackagedescriptionsshouldbelistedinreversealphabeticalorder.

19. Captureascreenshotofthecommandandtheresultofitsexecution.

Page24of24

You might also like