Title | CS669 Lab1Explanation |
---|---|
Author | april hus |
Course | Database Design and implementation for Business |
Institution | Boston University |
Pages | 39 |
File Size | 2.5 MB |
File Type | |
Total Downloads | 52 |
Total Views | 130 |
Download CS669 Lab1Explanation PDF
MET CS 669 Database Design and Implementation for Business Lab 1 Explanation: SQL From Scratch
DocumentOverview
Thepurposeofthisdocumentistoexplain,step‐by‐step,howtocompleteLab1.Theexplanationscoverthe conceptsyouneedlearn,andprovideplentyofexamples.Youcanthinkofthisdocumentasanassistantthat isheretohelpyoucompletethelab. Thisdocumentisorganizedbythelab’sstepnumbers.So,ifforexample,youareworkingonstep1,you wouldreadthroughthestep1sectioninthisdocumenttolearnhowtocompletestep1.Thesamegoesforall ofthesteps.Readeachstep’sexplanationherefirst,thencompletethestep.
Page1of39 Copyright2012,2013,2015,2018‐2019BostonUniversity.AllRightsReserved.
Table of Contents SectionOne–AbsoluteFundamentals...................................................................................................................3 STEP1..................................................................................................................................................................3 STEP2..................................................................................................................................................................6 STEP3..................................................................................................................................................................8 STEP4..................................................................................................................................................................9 STEP5................................................................................................................................................................12 STEP6................................................................................................................................................................14 STEP7................................................................................................................................................................17 SectionTwo–MorePreciseDataHandling..........................................................................................................18 STEP8................................................................................................................................................................18 STEP9................................................................................................................................................................21 STEP10..............................................................................................................................................................27 STEP11..............................................................................................................................................................28 STEP12..............................................................................................................................................................32 STEP13..............................................................................................................................................................33 STEP14..............................................................................................................................................................35 STEP15..............................................................................................................................................................37 STEP16..............................................................................................................................................................38
Page2of39
SectionOne–AbsoluteFundamentals
STEP 1
CreatetheMovietable.Asareminder,makesuretofollowalongintheLab1 Explanationsdocumentasitshowsyouhowtocreatetablesandcompletetheother steps.
Toshowyouhowtocreateatable,we’llshowyouanexampleofcreatingasimplePersontable,whichwill lookasfollows.
ThisPersontablehasthreecolumns‐‐person_id,first_name,andlast_name‐‐withdatatypesspecifiedinthe diagramabove.We’llusethepersontablethroughthefirstsectiontoillustratethevariouscommands. First,let’slookatthecommandweusetocreatethePersontable. CREATE TABLE Person( person_id DECIMAL(12), first_name VARCHAR(256), last_name VARCHAR(256) ); Thefirstthingtonoteisthatthespaces,parentheses,andnewlinesareallimportant.TheseassisttheSQL processorindifferentiatingonewordfromthenext.Removingthesecancauseerrors. Next,letuslookatandunderstandvariousaspectsofthiscommand.ThecommandbeginswiththeSQL keywordsCREATETABLE.ASQLkeywordisawordthatthedesignersoftheSQLlanguagechosetocarry specialmeaningwithinthelanguage.ThetwokeywordsCREATETABLEtogetherindicatetotheSQLcompiler thatwearebeginningacommandtocreateatable.Thenextword,"Person",isthenameofthetableweare creating.Thisisnotakeyword,butsimplyanidentifierofourchoosing.Wecouldhavechosenanalternative identifier,limitedonlytowhatisrelevantandourimagination.SQLcompilersknowthatbydefinition,the identifierfollowingtheCREATETABLEkeywordsdefinesthenameofthetable.Onlycertaincharactersare legalinidentifiers,andthelegalcharactersdependupontheparticulardatabaseweareusing.Probablythe mostcommoncharactersusedareletters,numbers,andtheunderscore. Nextletusexaminetheclausethatbeginsandendswithparentheses.Theleftparenthesisbeginsthe specificationofthecolumnsandconstraintsforthetable,whiletherightparenthesisclosesthesame specification.Wewilllearnaboutconstraintsnextweek.Fornow,wefocusonthecolumnspecifications.The firstthingyoumaynoticeisthateachcolumnspecificationisseparatedbyacomma,andthelastspecification Page3of39
inthelisthasnocomma.Wewouldputfewerspecificationsifwehadfewercolumns,andmorespecifications formorecolumns. Thenextthingyoumaynoticeisthateachcolumnspecificationhastwowords.Althougheachcolumn specificationmayhavemorethantwowordsthatdefineadditionalaspectsofthecolumn,itmusthaveata minimumboththecolumn'snameandthecolumn'sdatatype.Justaswiththetablename,thecolumnname identiferisnotaSQLkeyword,andwecanchooseavarietyofnames.Agoodidentifierdescribeswellwhatit represents.Forourfirstcolumn,wechose“person_id”.ThesecondwordinacolumnspecificationisaSQL keywordindicatingthecolumn'sdatatype.Forourfirstcolumn,thedatatypeis“DECIMAL(12)”. Letusbrieflydiscussthetwodatatypesillustratedinourexample.Adatatyperestrictsthesetoflegalvalues foracolumntoaparticulardomain.TheDECIMALdatatypeinourexampleindicatesthatwearerestricting thevaluesforperson_idtonumbers.The“(12)”aftertheDECIMALkeywordindicatesthatwearerestricting thenumbersfurthersothattherearenodecimalpoints,andamaximumof12digits.Ifwehadput“(12,2)”, forexample,wewouldallowtwodecimalpointsforamaximumof12digits. TheVARCHARdatatypeforthefirst_namecolumnindicatesthatwearerestrictingthatcolumn’svaluesto charactersequences,forexample,“abcd”.The“(256)”meansthatthemaximumnumberofbytesis256. SomeRDBMSallowyoutochangethemeaningofthisnumberfrombytestocharacters,sothatthe256 wouldmean256characters,regardlessofthenumberofbytespercharacter. InmostmodernRDBMS,bothspacesandnewlinesbetweenSQLkeywordsarecategorizedsimplyas "whitespace",andaretreatedidenticallybytheDBMS.Thisabstractionmeansthatonecouldusespacesin lieuofnewlines,therebycontainingtheSQLcommandtoasingleline.However,acommonconvention,as illustratedabove,usesnewlinestoincreasethereadabilityandclarityoftheSQLcommand. InmostmodernRDBMSincludingOracle,MicrosoftSQLServerandPostgreSQL,SQLkeywordsarenotcase‐ sensitive,meaningthatthechoicetouseanuppercaseorlowercasecharacterdoesnotmattertotheDBMS. Acommonconvention,asillustratedabove,istocapitalizeSQLkeywords,capitalizethefirstletterofeach wordforthetablename(knownascamelcase),anduselowercaseforotheritems. Belowarescreenshotsofthiscommandbeingexecutedinthethreesupporteddatabases. OracleSQLDeveloper MicrosoftSQLServer pgAdmin
NoticethatthescreenshotscontaintheSQLcommandandtheresultoftheSQLcommand,andonly capturestherelevantportionofthescreen.Youshoulddothesame. Page4of39
OnedatatypetheMovietableincludes,butthePersontabledoesnot,isDATE.TheDATEdatatypeletsus trackcalendardates,asitsnamesuggests.
Page5of39
STEP 2
Insertthefirstrowwherethetitleis“Furious7”,thegenreis“ActionFilm”,therelease dateis4/1/2015,andthepriceis$9.94.
Addingdatatoatableismoretechnicallynamedan“insert”inSQL.FollowingwithourPersonexample,here isthecommandtoinsertarowwithvaluesperson_id=1,first_name=John,andlast_name=Smithby executingthefollowingcommand. INSERT INTO Person (person_id, first_name, last_name) VALUES (1, 'John', 'Smith'); Thecommaseparatedlistonthefirstlineindicatesthenamesofthecolumns,andthecommaseparatedlist onthesecondlineindicatesthevaluestoinsertintothosecolumns,respectively.Thevalue1isinsertedinto totheperson_idcolumn,thevalue“John”isinsertedintothefirst_namecolumn,andthevalue“Smith”is insertedintothelast_namecolumn.Thoughitispossibletoomitthefirstcommaseparatedlistbyinserting thevaluesintheordertheyexistinthedatabase,itisnotrecommendedtodoso.ProductionstrengthSQL insertionsspecifythecolumnnamesasillustratedabove,tohelppreventseveralcaseswheredatais unknowinglyinsertedintothewrongcolumn. Numericvaluescanbetypedwithoutapostrophes.Characterbasedvaluessuchasafirst_nameand last_namemustbequotedwithanapostrophe(').TheseapostrophestelltheRDMBSwherethecharacter sequencebeginsandends.Onereasonapostrophesarenecessaryisthatcharactersequencescancontain spaces,andtheRDBMSneedsawaytoknowwhenaspaceisaseparatorforatokenintheSQLlanguage,and whenaspaceispartofasinglesequenceofcharactersforavalue.Makesuretousetheregularapostrophe ('),andnotthetypographer'sapostrophe(`). Belowisascreenshotofthecommandandtheresultofitsexecution. OracleSQL Developer
Page6of39
MicrosoftSQL Server Management Studio pgAdmin
SincethepersontabledoesnotincludeaDATEdatatype,hereisthesyntaxofhowyoucanhardcodea particulardate: CAST(’01‐MAR‐2019’ASDATE) Thisexamplehardcodes3/1/2019asadate.Thedaynumbercomesfirst,followedbyamonthabbreviation, followedbytheyear.
Page7of39
STEP 3
Selectallrowsinthetabletoviewtherowyouinserted.
It’snottoocomplextoretrieveallrowsfromatable.Thetechnicalwordforretrievingdatais“select”in SQL.Asanexample,wecanselectallrowsfromthePersontablebyexecutingthefollowingcommand. SELECT * FROM Person; ThefirstlineinstructstheRDBMStoretrieveallcolumns,becausethe"*"valueindicates"all".Thesecond lineinstructstheRDBMStoretrievefromthePersontable.Ascreenshotofthecommandandtheresultof itsexecutionisbelow. OracleSQL Developer
MicrosoftSQL Server Management Studio
pgAdmin
Noticethatweseetherowwejustinsertedintheresultset. Page8of39
STEP 4
Updatethepriceoftherowinthetableto$10.15,thenselectallrowsinthetableto viewtherowyouupdated.
NowyouhaveachancetoupdateexistingdataintheMovietable.Hereisanexampleofhowweupdateall rowsinthePersontable.SincethereisonlyonerowithastheeffectofupdatingthelastnameofJohnSmith from“Smith”to“Glass”. UPDATE Person SET last_name = 'Glass'; Thefirstword“UPDATE”indicatestotheRDBMSthatweareupdatingrow(s)inatable.Thesecondword “Person”indicatesthatweareupdatingrow(s)inthePersontable.TheSETkeywordonthesecondlinebegins acomma‐separatedlistofcolumnnamesandtheirnewvalues.Byusingthephrase: last_name = 'Glass' weareinstructingtheRDBMStosetthevalueofthelast_namecolumntothevalue“Glass”.Ifwehadinstead usedthephrase: first_name = 'Jane' forexample,wewouldbeinstructingtheRDBMStosetthefirst_namevalueto“Jane”. TheUPDATEcommandaboveupdatesallrowsinthePersontable.Ifthereweretobemorethanonerowin thePersontable,thelast_namevaluesforalloftherowswouldbeupdated.Wewilllearninthenextsection howtolimitupdatestoaspecificroworgroupofrows. Hereisascreenshotofthecommandtheresultofitsexecution. OracleSQLDeveloper
Page9of39
MicrosoftSQLServer ManagementStudio
pgAdmin
Weviewtheresultsofourupdatebyselectingallrowsinthetable. SELECT * FROM Person; Inthescreenshotsbelow,you’llnoticethelastnameisnow“Glass”. OracleSQLDeveloper
MicrosoftSQLServerManagementStudio
Page10of39
pgAdmin
Page11of39
STEP 5
Removeallrowsfromthetable,thenselectallrowsinthetabletoverifythereare norows.
Toremoveallrowsfromatable,youusetheDELETEcommand.Hereisanexampleofdoingsowiththe Persontable. DELETE FROM Person; TheDELETEFROMkeywordsindicatetotheRDBMSthatwearedeletingoneormorerowsfromatable.The nextword,“Person”,indicatesthatthetableisthePersontable. ExecutingthecommandabovewilldeleteallrowsinthePersontable.Inourexampleweonlyhaveonerow, buttablesinproductionenvironmentsusuallyhavemanyrows.Wewilllearninthenextsectionhowtolimita deletetoaspecificroworgroupofrows. Hereisascreenshotofexecutingthiscommand. OracleSQL Developer
MicrosoftSQL Server Management Studio
Page12of39
pgAdmin
NoticethateachRDBMSindicatethenumberofrowsthatweredeleted. Inordertoseethatthetablenowhasnorows,letusagainselectallrowsinthetable. OracleSQL Developer
MicrosoftSQLServer ManagementStudio
pgAdmin
Noticethatalthoughthecolumnsstillappearintheresultset,norowsofdataappear.Thisisbecauseallrows havebeenremovedfromthePersontable.
Page13of39
STEP 6
DroptheMovietable,thenselectallrowsinthetabletoverifythetabledoesn’t exist.
ThecommandforgettingridofatableisDROP.TodropthePersontable,wewouldusethiscommand. DROP TABLE Person; ThefirsttwokeywordsDROPTABLEinstructtheRDBMStoremoveatable.Thethirdword,“Person”,isthe nameofthetabletobedropped,inthiscase,thePersontable. AlthoughinthisexercisewearecasuallydroppingthePersontable,inproductionenvironmentscommand shouldbeusedwithextremecare.Allofthedatainthetablewillalsoberemoved,andthedatacannot alwaysberecoveredifyoulaterdecidethatyouwanttokeepthedata. BelowisascreenshotofdroppingthePersontable. OracleSQL Developer
MicrosoftSQL Server Management Studio
Page14of39
pgAdmin
Forgoodmeasure,letusattempttoretrievedatafromthePersontablewejustdeleted.Ofcourse,nowthat thePersontablehasbeendropped,thecommandwillnotbeabletoretrievetheresults.Itishelpfulhowever tobecomeaccustomedtotheerrormessageindicatingthatthetabledoesnotexist. OracleSQL Developer
Microsoft SQLServer Management Studio
Page15of39
pgAdmin
Page16of39
STEP 7
Explainhowyouwouldusetheerrormessageresultingfromstep#6,inconjunction withtheSELECTcommand,todiagnosetheerror.
OracleExplanation TheOracleerrormessageclearlystatesthatthetableorviewbeingreferencedinthecommanddoesnot exist.Thereasonfortheadditionalclause“orview”intheerrormessageisthatwhereveratableisusedina command,aviewcanbeusedaswell.Wewillstudyviewsinfutureweeks. Todiagnosetheissue,theerrormessageandSQLcommandneedtobeanalyzedtogether.Eitheralonedoes notprovidesufficientinformation.Forexample,inthiscase,theerrormessagedoesnotstatethatitwasthe referenceto“Person”thatwasinvalid.WemustdeducethatbyreviewingourSQLcommand.Theerror messagehasonemorepieceofinformationthatwillhelpusdoso,whichisalinenumberandacolumn number.Inthiscase,theerrormessageisstatingthatthesourceoftheerrorbeginsatline2,column5.Ifwe reviewourcommand,weseethattheword“Person”beginsatline2,column5,andsothatisthesourceof theerror.ThefactthatPersondoesnotexistisexpected,sincewepreviouslydroppedthattable. MicrosoftSQLServerExplanation TheerrormessagegeneratedbySQLServermaybesomewhatdifficulttointerpretfromarelationalpointof view,becauseitdoesnotusethefamiliarterm“table”intheerrormessage.SQLServerusesthegenericterm “object”todenoteanydurableentitythatitsupports,includingtablesandviews.Thereforewecanintepret thephrase“Invalidobjectname‘Person’”tomeanthatweattemptedtousethename“Person”asa referencetoadurableentityintheSQLcommand,butnodurableentityexistsbythatname. JustaswiththeOracleerrormessages,weneedtousetheSQLServererrormessage,incombinationwiththe SQLcommand,todiagnosetheissue.Theerrormessagedoesprovidealinenumberindicatingthestartofthe commandwiththeissue.Sinceinthiscaseweonlyhaveonecommand,itstatesthatitbeginsonline1.Ifwe weretobeexecutingmultiplecommands,thelinenumberwouldbehelpful. Whenweseethiserrormessage,weneedtothink,“Somehwereinthecommandthatbeginsonline1isa referenceto‘Person’thatdoesnotexist.”Wecanthensearchthroughthecommandandfindtheinvalid reference.Inoursimplecase,weonlyhaveonereferenceto“Person”,andweattemptedtoreferenceitasa table,andsoweknowthatthePersontabledoesnotexist.Thisiswhatweexpected,sincewepreviously droppedthePersontable. PostgreSQLExplanation UsingtheprovidederrormessagealongwiththeSQLcommandweareabletodiagnosetheissue. TheerrormessagegeneratedinPostgreSQLspecifiesashortdescriptionoftheerrormessagealongwiththe linenumberinthescripttheerrorcorrespondstoandthemorecomplextheSQLcommandthemore beneficialthelinenumberbecomes.Inthisexampletheerrormessagestatesthatthe“person”doesnotexist andpointsustoLine2wherethe“person”objectisreferencedin...