Está en la página 1de 36

MET CS 669 Database Design and Implementation for Business

Lab 1 Instructions: SQL From Scratch

OVERVIEWOFTHELAB
TheStructuredQueryLanguage(SQL)isthedefactoquerylanguageformodern
relationaldatabasemanagementsystems(RDBMS).Allmajor,modernRDBMS
supportSQL.Databasedevelopers,administrators,andevensoftwareapplications
accessRDBMSthroughtheuseofSQL.FamiliaritywithSQLisessentialforworking
withandunderstandingmodernRDBMS.

ThefirstobjectiveofthislabistoprovideyouwithapracticalexerciseofusingSQL
tocreateanddropatable,andtoinsert,update,delete,andselectarowinatable.

Thesecondobjectiveofthislabistoprovideyouwithapracticalexerciseofusing
theStructuredQueryLanguage(SQL)todothefollowing:
AddaNOTNULLconstrainttoatablecolumn
AddaPRIMARYKEYconstrainttoatablecolumn
Usedates
InsertaNULLvalueintoatablerow
UseaWHEREclausetolimitthenumberofrowsaffectedbytheSELECT,
UPDATE,andDELETEcommands
SELECTonlyasubsetofcolumnsinaresultset

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

ThescreenshotsinthislabdisplayexecutionofSQLintheOracleSQLDeveloper
clientandinMicrosoftSQLServerManagementStudio.Notethatifyouareusing
Oracle,youarenotrequiredtouseOracleSQLDeveloper;therearemanycapable
SQLclientsthatconnecttoOracle.

Page1of36
Copyright2012,2013,2015BostonUniversity.AllRightsReserved.

PREPARINGFORTHELAB
YouwillneedtoinstallaRDBMSpriortocompletingthislab.IfyouareusingOracle,
itishighlyrecommendedthatyoucreateandloginasanonsystemuser,toavoid
damagingthedatabase.Youcancreateauserwiththefollowingcommands:

CREATE USER username IDENTIFIED BY password DEFAULT TABLESPACE users


TEMPORARY TABLESPACE temp;
GRANT connect, resource TO username;

Youwillthenbeabletologinasthenewuser.

IfyouareusingMicrosoftSQLServer,itishighlyrecommendedthatyoucreateand
useadatabaseotherthantheMasterdatabase.Youcandosowiththefollowing
commands:

CREATE DATABASE database_name;


GO;
USE database_name;

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

COMMIT;

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

COMPLETINGYOURLAB
Usethesubmissiontemplateprovidedintheassignmentinboxtocompletethislab.

Page2of36

SECTIONONE
OVERVIEW
InSectionOnewewillcreatethePersontableillustratedbelow:

ThisPersontablehasthreecolumnsperson_id,first_name,andlast_namewith
datatypesspecifiedinthediagramabove.

Wewillcreatethistable,tryoutsomedatamanipulationcommands,andultimately
removethetable.

STEPS

1. ExecutethefollowingcommandtocreatethePersontable.Makesuretotypethe
commandexactlyasillustrated,includingspaces,parentheses,andnewlines.

CREATE TABLE Person(


person_id DECIMAL(12),
first_name VARCHAR(256),
last_name VARCHAR(256)
);

Letuslookatandunderstandvariousaspectsofthiscommand.Thecommandbegins
withtheSQLkeywordsCREATETABLE.ASQLkeywordisawordthatthedesignersof
theSQLlanguagechosetocarryspecialmeaningwithinthelanguage.Thetwo
keywordsCREATETABLEtogetherindicatetotheSQLcompilerthatwearebeginning
acommandtocreateatable.Thenextword,"Person",isthenameofthetablewe
arecreating.Thisisnotakeyword,butsimplyanidentifierofourchoosing.Wecould
havechosenanalternativeidentifier,limitedonlytowhatisrelevantandour

Page3of36

imagination.SQLcompilersknowthatbydefinition,theidentifierfollowingthe
CREATETABLEkeywordsdefinesthenameofthetable.Onlycertaincharactersare
legalinidentifiers,andthelegalcharactersdependupontheparticulardatabasewe
areusing.Probablythemostcommoncharactersusedareletters,numbers,andthe
underscore.

Nextletusexaminetheclausethatbeginsandendswithparentheses.Theleft
parenthesisbeginsthespecificationofthecolumnsandconstraintsforthetable,
whiletherightparenthesisclosesthesamespecification.Wewilllearnabout
constraintsnextweek.Fornow,wefocusonthecolumnspecifications.Thefirst
thingyoumaynoticeisthateachcolumnspecificationisseparatedbyacomma,and
thelastspecificationinthelisthasnocomma.Wewouldputfewerspecificationsif
wehadfewercolumns,andmorespecificationsformorecolumns.

Thenextthingyoumaynoticeisthateachcolumnspecificationhastwowords.
Althougheachcolumnspecificationmayhavemorethantwowordsthatdefine
additionalaspectsofthecolumn,itmusthaveataminimumboththecolumn'sname
andthecolumn'sdatatype.Justaswiththetablename,thecolumnnameidentiferis
notaSQLkeyword,andwecanchooseavarietyofnames.Agoodidentifier
describeswellwhatitrepresents.Forourfirstcolumn,wechoseperson_id.The
secondwordinacolumnspecificationisaSQLkeywordindicatingthecolumn's
datatype.Forourfirstcolumn,thedatatypeisDECIMAL(12).

Letusbrieflydiscussthetwodatatypesillustratedinourexample.Adatatype
restrictsthesetoflegalvaluesforacolumntoaparticulardomain.TheDECIMAL
datatypeinourexampleindicatesthatwearerestrictingthevaluesforperson_idto
numbers.The(12)aftertheDECIMALkeywordindicatesthatwearerestrictingthe
numbersfurthersothattherearenodecimalpoints,andamaximumof12digits.If
wehadput(12,2),forexample,wewouldallowtwodecimalpointsfora
maximumof12digits.

TheVARCHARdatatypeforthefirst_namecolumnindicatesthatwearerestricting
thatcolumnsvaluestocharactersequences,forexample,abcd.The(256)means
thatthemaximumnumberofbytesis256.SomeRDBMSallowyoutochangethe
meaningofthisnumberfrombytestocharacters,sothatthe256wouldmean256
characters,regardlessofthenumberofbytespercharacter.

InmostmodernRDBMS,bothspacesandnewlinesbetweenSQLkeywordsare
categorizedsimplyas"whitespace",andaretreatedidenticallybytheDBMS.This
abstractionmeansthatonecouldusespacesinlieuofnewlines,therebycontaining
theSQLcommandtoasingleline.However,acommonconvention,asillustrated
above,usesnewlinestoincreasethereadabilityandclarityoftheSQLcommand.
InmostmodernRDBMSincludingOracleandMicrosoftSQLServer,SQLkeywordsare
notcasesensitive,meaningthatthechoicetouseanuppercaseorlowercase

Page4of36

characterdoesnotmattertotheDBMS.Acommonconvention,asillustratedabove,
istocapitalizeSQLkeywords,capitalizethefirstletterofeachwordforthetable
name(knownascamelcase),anduselowercaseforotheritems.
2. Captureascreenshotofthecommandandtheresultofitsexecution.Belowisa
samplescreenshotofthecommandexecutioninOracleSQLDeveloper.

BelowisasamplescreenshotofthecommandexecutioninMicrosoftSQLServer
ManagementStudio.

AcompletescreenshotcontainstheSQLcommandandtheresultoftheSQL
command.Thescreenshotwillbemorelegibleifyouuseoneofthemanyfreetools
tocaptureonlytherelevantportionofthescreen,ratherthancapturingtheentire
applicationwindow.

Page5of36

3. Insertarowwithvaluesperson_id=1,first_name=John,andlast_name=Smithby
executingthefollowingcommand.

INSERT INTO Person (person_id, first_name, last_name)


VALUES (1, 'John', 'Smith');

Thecommaseparatedlistonthefirstlineindicatesthenamesofthecolumns,and
thecommaseparatedlistonthesecondlineindicatesthevaluestoinsertintothose
columns,respectively.Thevalue1isinsertedintototheperson_idcolumn,thevalue
Johnisinsertedintothefirst_namecolumn,andthevalueSmithisinsertedinto
thelast_namecolumn.Thoughitispossibletoomitthefirstcommaseparatedlistby
insertingthevaluesintheordertheyexistinthedatabase,itisnotrecommendedto
doso.ProductionstrengthSQLinsertionsspecifythecolumnnamesasillustrated
above,tohelppreventseveralcaseswheredataisunknowinglyinsertedintothe
wrongcolumn.

Numericvaluescanbetypedwithoutapostrophes.Characterbasedvaluessuchasa
first_nameandlast_namemustbequotedwithanapostrophe(').Theseapostrophes
telltheRDMBSwherethecharactersequencebeginsandends.Onereason
apostrophesarenecessaryisthatcharactersequencescancontainspaces,andthe
RDBMSneedsawaytoknowwhenaspaceisaseparatorforatokenintheSQL
language,andwhenaspaceispartofasinglesequenceofcharactersforavalue.
Makesuretousetheregularapostrophe('),andnotthetypographer'sapostrophe
(`).

4. Captureascreenshotofthecommandandtheresultofitsexecution.Belowisa
samplescreenshotofthecommandexecutioninOracleSQLDeveloper.

Page6of36

BelowisasamplescreenshotofthecommandexecutioninMicrosoftSQLServer
ManagementStudio.

5. Selectallrowsinthetablebyexecutingthefollowingcommand.

SELECT *
FROM Person;

ThefirstlineinstructstheRDBMStoretrieveallcolumns,becausethe"*"value
indicates"all".ThesecondlineinstructstheRDBMStoretrievefromthePerson
table.

6. Captureascreenshotofthecommandtheresultofitsexecution.Belowisasample
screenshotofthecommandexecutioninOracleSQLDeveloper.

Page7of36

BelowisasamplescreenshotofthecommandexecutioninMicrosoftSQLServer
ManagementStudio.

Noticethatweseetherowwejustinsertedintheresultset.
7. UpdatethelastnameofJohnSmithfromSmithtoGlassbyexecutingthe
followingcommand:

UPDATE Person
SET last_name = 'Glass';

ThefirstwordUPDATEindicatestotheRDBMSthatweareupdatingrow(s)ina
table.ThesecondwordPersonindicatesthatweareupdatingrow(s)inthePerson
table.TheSETkeywordonthesecondlinebeginsacommaseparatedlistofcolumn
namesandtheirnewvalues.Byusingthephrase:

last_name = 'Glass'

weareinstructingtheRDBMStosetthevalueofthelast_namecolumntothevalue
Glass.Ifwehadinsteadusedthephrase:

first_name = 'Jane'

forexample,wewouldbeinstructingtheRDBMStosetthefirst_namevalueto
Jane.

TheUPDATEcommandaboveupdatesallrowsinthePersontable.Iftherewereto
bemorethanonerowinthePersontable,thelast_namevaluesforalloftherows
wouldbeupdated.Wewilllearnnextweekhowtolimitupdatestoaspecificrowor
groupofrows.

Page8of36

8. Captureascreenshotofthecommandtheresultofitsexecution.Belowisasample
screenshotofthecommandexecutioninOracleSQLDeveloper.

BelowisasamplescreenshotofthecommandexecutioninMicrosoftSQLServer
ManagementStudio.

9. Inordertoseetheresultsofourupdate,letusagainselectallrowsinthetableby
executingthefollowingcommand.

SELECT *
FROM Person;

Page9of36

10. Captureascreenshotofthecommandtheresultofitsexecution.Belowisasample
screenshotofthecommandexecutioninOracleSQLDeveloper.

BelowisasamplescreenshotofthecommandexecutioninMicrosoftSQLServer
ManagementStudio.

NoticethatthelastnameisnowGlass.

11. Next,wearegoingtoremoveallrowsfromthetable.Wedosowiththefollowing
command.

DELETE FROM Person;

TheDELETEFROMkeywordsindicatetotheRDBMSthatwearedeletingoneormore
rowsfromatable.Thenextword,Person,indicatesthatthetableisthePerson
table.

Page10of36

ExecutingthecommandabovewilldeleteallrowsinthePersontable.Inour
exampleweonlyhaveonerow,buttablesinproductionenvironmentsusuallyhave
manyrows.Wewilllearnnextweekhowtolimitadeletetoaspecificroworgroup
ofrows.

12. Captureascreenshotofthecommandtheresultofitsexecution.Belowisasample
screenshotofthecommandexecutioninOracleSQLDeveloper.

BelowisasamplescreenshotofthecommandexecutioninMicrosoftSQLServer
ManagementStudio.

NoticethatbothRDBMSindicatethenumberofrowsthatweredeleted.

Page11of36

13. Inordertoseethatthetablenowhasnorows,letusagainselectallrowsinthe
tablebyexecutingthefollowingcommand.

SELECT *
FROM Person;

14. Captureascreenshotofthecommandtheresultofitsexecution.Belowisasample
screenshotofthecommandexecutioninOracleSQLDeveloper.

BelowisasamplescreenshotofthecommandexecutioninMicrosoftSQLServer
ManagementStudio.

Noticethatalthoughthecolumnsstillappearintheresultset,norowsofdata
appear.ThisisbecauseallrowshavebeenremovedfromthePersontable.

Page12of36

15. Sothatweknowhowtoremovetablesthatwecreate,letustrythatnow.

DROP TABLE Person;


Thetechnicalwordforremovingatableisdrop,andsothefirsttwokeywords
DROPTABLEinstructtheRDBMStoremoveatable.Thethirdword,Person,isthe
nameofthetabletobedropped,inthiscase,thePersontable.
AlthoughinthisexercisewearecasuallydroppingthePersontable,inproduction
environmentscommandshouldbeusedwithextremecare.Allofthedatainthe
tablewillalsobedropped,andthedatacannotalwaysberecoveredifyoulater
decidethatyouwanttokeepthedata.
16. Captureascreenshotofthecommandtheresultofitsexecution.Belowisasample
screenshotofthecommandexecutioninOracleSQLDeveloper.

BelowisasamplescreenshotofthecommandexecutioninMicrosoftSQLServer
ManagementStudio.

Page13of36

17. Forgoodmeasure,letusattempttoretrievedatafromthePersontablewejust
deleted.Ofcourse,nowthatthePersontablehasbeendropped,thecommandwill
notbeabletoretrievetheresults.Itishelpfulhowevertobecomeaccustomedto
theerrormessageindicatingthatthetabledoesnotexist.

SELECT *
FROM Person;

18. Captureascreenshotofthecommandtheresultofitsexecution.Belowisasample
screenshotofthecommandexecutioninOracleSQLDeveloper.

TheOracleerrormessageclearlystatesthatthetableorviewbeingreferencedinthe
commanddoesnotexist.Thereasonfortheadditionalclauseorviewintheerror
messageisthatwhereveratableisusedinacommand,aviewcanbeusedaswell.
Wewillstudyviewsinfutureweeks.

Todiagnosetheissue,theerrormessageandSQLcommandneedtobeanalyzed
together.Eitheralonedoesnotprovidesufficientinformation.Forexample,inthis
case,theerrormessagedoesnotstatethatitwasthereferencetoPersonthatwas
invalid.WemustdeducethatbyreviewingourSQLcommand.Theerrormessagehas
onemorepieceofinformationthatwillhelpusdoso,whichisalinenumberanda
columnnumber.Inthiscase,theerrormessageisstatingthatthesourceoftheerror
beginsatline2,column5.Ifwereviewourcommand,weseethatthewordPerson
beginsatline2,column5,andsothatisthesourceoftheerror.ThefactthatPerson
doesnotexistisexpected,sincewepreviouslydroppedthattable.

Page14of36

BelowisasamplescreenshotofthecommandexecutioninMicrosoftSQLServer
ManagementStudio.

TheerrormessagegeneratedbySQLServermaybesomewhatdifficulttointerpret
fromarelationalpointofview,becauseitdoesnotusethefamiliartermtablein
theerrormessage.SQLServerusesthegenerictermobjecttodenoteanydurable
entitythatitsupports,includingtablesandviews.Thereforewecanintepretthe
phraseInvalidobjectnamePersontomeanthatweattemptedtousethename
PersonasareferencetoadurableentityintheSQLcommand,butnodurable
entityexistsbythatname.

JustaswiththeOracleerrormessages,weneedtousetheSQLServererrormessage,
incombinationwiththeSQLcommand,todiagnosetheissue.Theerrormessage
doesprovidealinenumberindicatingthestartofthecommandwiththeissue.Since
inthiscaseweonlyhaveonecommand,itstatesthatitbeginsonline1.Ifwewere
tobeexecutingmultiplecommands,thelinenumberwouldbehelpful.

Whenweseethiserrormessage,weneedtothink,Somehwereinthecommand
thatbeginsonline1isareferencetoPersonthatdoesnotexist.Wecanthen
searchthroughthecommandandfindtheinvalidreference.Inoursimplecase,we
onlyhaveonereferencetoPerson,andweattemptedtoreferenceitasatable,
andsoweknowthatthePersontabledoesnotexist.Thisiswhatweexpected,since
wepreviouslydroppedthePersontable.

Page15of36

SECTIONTWO
OVERVIEW
ThegoalofSectionTwoistoapplywhatislearnedinSection1tocreateandpopulate
thefollowingtable:

ThisBooktablehasthreecolumnsbook_id,title,andsubtitlewithdatatypes
specifiedinthediagramabove.

STEPS

19. ExecutethecommandtocreatetheBooktable.Captureascreenshotofthe
commandandtheresultofitsexecution.
20. Executethecommandtoinsertarowwithvaluesbook_id=101,title=Art,and
subtitle=Modernized.Captureascreenshotofthecommandandtheresultofits
execution.
21. Toviewtherowjustinserted,executethecommandtoselectallrowsinthetable.
Captureascreenshotofthecommandandtheresultofitsexecution.
22. UpdatethesubtitlesothatithasavalueofRevisitedinsteadofModernized.
Captureascreenshotofthecommandandtheresultofitsexecution.
23. Toseetheresultsoftheupdate,selectallrowsinthetable.Captureascreenshotof
thecommandandtheresultofitsexecution.
24. Removeallrowsfromthetable.Captureascreenshotofthecommandandthe
resultofitsexecution.
25. Toseetheresultsofremoving,selectallrowsfromthetable.Captureascreenshot
ofthecommandandtheresultofitsexecution.
26. Dropthetable.Captureascreenshotofthecommandandtheresultofits
execution.
27. Attempttoselectallrowsfromthetable.Captureascreenshotofthecommandand
theresultofitsexecution.
28. ExplainhowyouwouldusetheerrormessageresultingfromStep27,inconjunction
withtheSQLcommand,todiagnosetheissue.

Page16of36

SECTIONTHREE
OVERVIEW
InSectionThree,wewillworkwiththeCameratableillustratedbelow.Notethatthe
boldedcolumnsrepresentthosewithaNOTNULLconstraint.

Camera
PK

camera_idDECIMAL(12)
modelVARCHAR(64)
descriptionVARCHAR(255)
date_manufacturedDATE

STEPS

29. ExecutethefollowingcommandtocreatetheCameratable.Makesuretotypethe
commandexactlyasillustrated,includingspaces,parentheses,andnewlines.

CREATE TABLE Camera (


camera_id DECIMAL(12) PRIMARY KEY,
model VARCHAR(64) NOT NULL,
description VARCHAR(255),
date_manufactured DATE NOT NULL
);

Thoughinthecommandaboveyouseesomefamiliarconstructs,letusfurther
explainthephrasesPRIMARYKEYandNOTNULL.BecausethephrasePRIMARY
KEYispartofthecamera_idcolumndefinition(recallthatthecommaseparates
columndefinitions),theRDBMSknowstoapplythePRIMARYKEYconstrainttothe
camera_idcolumn,andnottoanyothercolumn.Similarly,thephraseNOTNULL
appliestoboththemodelanddate_manufacturedcolumns,sincethephraseispart
ofthosecolumnsdefinitions.

Page17of36

Itisimportanttoremembertwopropertiesofconstraintsasdescribedinthelecture
andtextbook.Thefirstisthataconstraintdefinesaconditionthatthedatamust
satisfy.ThesecondisthatthattheRDBMScontinuallyenforcestheconditiondefined
byanactiveconstraintatalltimes.Whenweplaceaconstraintonasinglecolumnas
inthecommandabove,thenthevalueforthecolumnmustsatisfythecondition,for
everyrowinthetableatalltimes.Bydefault,theRDBMSwillrejectanySQL
statementthatwouldcauseaconstraintviolation.

LetusbrieflyreviewtheconceptofNULL.Whenweassignadatatypetoacolumn,
werestrictthelegalvaluesforthatcolumn.Forexample,aVARCHARdatatype
meansthatweallowsequencesofcharactersforthecolumn.ADATEdatatype
meansthatweallowdatevaluesforthecolumn.But,whatifwewanttoindicate
thatthecolumnhasnovalueatall?TheNULLkeywordisusedforthispurpose.
WhentheRDBMSseestheNULLkeyword,itknowsthatnovalueistobeplacedinto
thatcolumn.

RecallthataNOTNULLconstraintindicatesthateachrowinthetablemusthavea
valueforthecolumn(s)coveredbytheconstraint.Indicatingnovalueforthecovered
column(s)isillegal.FurtherrecallthataPRIMARYKEYconstraintisacombinationof
NOTNULLandUNIQUEconstraints.Thevalue(s)coveredbythePRIMARYKEYmust
alwaysbepresentandunique.Thebenefitofaprimarykeyvalueisthatitcanalways
beusedtouniquelyidentifyarowinatable.

Bydefaultcolumnsarenullable,meaningthatavalueforthatcolumnisoptional;any
particularrowmayomitavalueforthatcolumn.ThisdefaultiswhyaNOTNULL
constraintwasusedtoensurethatboththemodelanddate_manufacturedcolumns
alwayshavevalues.Thisdefaultmeansthatthedescriptioncolumnisnullable,since
theNOTNULLphraseisnotpartofthedescriptioncolumndefinition.

Youmayhavenoticedthatthedate_manufacturedcolumnhasaDATEdatatype.A
DATEdatatypeindicatesthatayear,month,anddaymaybestoredinthecolumn.
Somedatabasemanagementsystemsalsoallowadditionaltimeinformationtobe
storedinaDATEcolumn.Forexample,Oracleallowstheadditionalstorageofhours,
minutes,andsecondsinaDATEcolumn.However,thestandardsforSQLspecifythat
DATEcolumnsonlystoretheyear,month,andday,anditisabestpracticetouse
DATEcolumnstostoreonlythesefields,forportability.

Page18of36

30. Captureascreenshotofthecommandandtheresultofitsexecution.Belowisa
samplescreenshotofthecommandexecutioninOracleSQLDeveloper

BelowisasamplescreenshotofthecommandexecutioninMicrosoftSQLServer
ManagementStudio.

Page19of36

31. Executethefollowingcommandtoinsertarowwiththevalueslisted.
camera_id=51
model=ProShot5000
description=Usefulforportraits
date_manufactured=21FEB2008

INSERT INTO Camera (camera_id,


model,

description,

date_manufactured)
VALUES (51,

'ProShot 5000',

'Useful for portraits',

CAST('21-FEB-2008' AS DATE)

);

Youhavealreadyseenexamplesofinsertingnumbersandcharactersequences,but
insertingdatesmaybenewtoyouandisworthamoredetailedlook.Ifwewantto
insertanumber,wesimplytypethenumberintheformatweareusedto,andthe
RDBMSknowsthatwhatwetypedisaliteralnumber.Forexample,wesimplytyped
51asintheexampleabove.Ifwewanttotypeacharactersequence,wesimply
encloseitbetweenapostrophes('),andtheRDBMSknowsthatwhatwetypedisa
literalcharactersequence.Forexample,wetyped'ProShot5000'above.Indicating
literaldatevaluesinaportablewayisnotassimple.

Onecommon,portablewaytospecifyadateliteralistotypethedateasacharacter
sequence,thenusetheCASToperatortoconvertthecharactersequencetoadate.
TheCASToperatorisnecessarybecauseotherwisetheRDBMSmaynottreatthe
charactersequencevalueasadate.EachspecificRDBMShasnonportablemethods
ofspecifyingdateliteralsaswell.Forexample,OracleoffersaTO_DATEfunction,and
SQLServerimplicitlyconvertsstandalonecharactersequencesintodatesifadateis
expected.Thoughtherearemanyportableandnonportablemethodsofspecifying
dateliterals,onecommonalityformostofthesemethodsischaractersequence
representationofthedateinthecommand.Inourexample,weusedthecharacter
sequence21FEB2008toindicateFebruary21st,2008.

TheformatofthedatecharactersequencedeterminesportabilitybetweenRDBMS
usingdifferentdateconventions.Intheexampleabove,weusedthedateformat
ddmmmyyyy,whereddrepresentstwodigitsforthedayofmonth,mmm
representsthefirstthreelettersofthemonth,andyyyyrepresentsthefourdigits
oftheyear.Ifwehadused02/21/2008inthedateformattypicallyusedinthe
UnitedStates,EuropeanRDBMSwouldnothaveinterpretedthedateaswe
expected,sinceEuropeandatestandardsspecifythedayofmonthfirst,followedby

Page20of36

themonth,followingbytheyear(21/02/2008forthisexample).Ifwehadused
theEuropeandateformat,RDBMSintheUnitedStateswouldnothaveinterpreted
thedateasweexpect.Forthisreason,itisbesttousetheportablespecificationdd
mmmyyyy.

32. Captureascreenshotofthecommandandtheresultofitsexecution.Belowisa
samplescreenshotofthecommandexecutioninOracleSQLDeveloper

BelowisasamplescreenshotofthecommandexecutioninMicrosoftSQLServer
ManagementStudio.

Page21of36

33. Executethefollowingcommandtoinsertarowwiththevalueslisted.
camera_id=52
model=NaturalShot300x
description=NULL
date_manufactured=03APR2009

INSERT INTO Camera (camera_id,


model,
description,

date_manufactured)

VALUES (52,

'NaturalShot 300x',

NULL,

CAST('03-APR-2009' AS DATE)

);

NoticethatweusedtheNULLkeywordtoindicatethatthedescriptioncolumnhas
novalueforthisrow.Nowthatyouunderstandtheconceptofnull,andhowtoinsert
nullvalues,youcanseethatitisreallyquitesimpletoindicatethatacolumndoes
nothaveavalue.

34. Captureascreenshotofthecommandandtheresultofitsexecution.Belowisa
samplescreenshotofthecommandexecutioninOracleSQLDeveloper

Page22of36

BelowisasamplescreenshotofthecommandexecutioninMicrosoftSQLServer
ManagementStudio.

35. Thenextcommandwewillexecuteindicatesnovalueforthedescriptioncolumnin
adifferentway.
camera_id=53
model=StillShot2012
date_manufactured=05JUN2009

INSERT INTO Camera (camera_id,


model,
date_manufactured)

VALUES (53,

'StillShot 2012',

CAST('05-JUN-2009' AS DATE)

);

Noticethatweomittedthedescriptioncolumnfromcolumnidentificationlistand
thecolumnvaluelist.WhentheRDBMSseesthecolumnomitted,itknowsbydefault
togivethecolumnnovalue.Thiscommandillustratesanotherwaytoavoidinserting
avalueforacolumn.

Page23of36

36. Captureascreenshotofthecommandandtheresultofitsexecution.Belowisa
samplescreenshotofthecommandexecutioninOracleSQLDeveloper

BelowisasamplescreenshotofthecommandexecutioninMicrosoftSQLServer
ManagementStudio.

Page24of36

37. NowthatwehaveinsertedthreerowsintoourCameratable,letusseewhatwe
haveinourtable.

SELECT *
FROM CAMERA;

38. Captureascreenshotofthecommandandtheresultofitsexecution.Belowisa
samplescreenshotofthecommandexecutioninOracleSQLDeveloper

BelowisasamplescreenshotofthecommandexecutioninMicrosoftSQLServer
ManagementStudio.

Page25of36

Noticethatalthoughweusedtwodifferentmethodstoinsertthelasttworows,both
rowsdonothaveavaluefordescriptioncolumnjustthesame.TheRDBMSusesthe
NULLkeywordtoindicatealackofavalue.FurthernoticethatOracleandSQLServer
displaythedatesdifferentlywhenreturnedfromthequery.Howthedatesare
rendererdvarieswithdifferentRDBMSandwithdifferentSQLclients.

39. Sothatwecanfamiliarizeourselveswithanothercommonerrormessage,letus
attemptinsertarowwithoutavalueforthemodelcolumn.Theinsertionwillfail
becauseaNOTNULLconstraintispresentonthemodelcolumn.
camera_id=54
model=NULL
description=Multipurposecamera
date_manufactured=23SEP2009

INSERT INTO Camera (camera_id,


model,
description,
date_manufactured)
VALUES (54,
NULL,
'Multi-purpose camera',
CAST('23-SEP-2009' AS DATE)
);

Page26of36

40. Captureascreenshotofthecommandandtheresultofitsexecution.Belowisa
samplescreenshotofthecommandexecutioninOracleSQLDeveloper

OnceweunderstandtheconceptofNULL,theerrormessagefromOracleisfairly
straightforward,thoughsomepartsneedsomeinterpretation.Themessagestates
thatonecannotinsertNULLintothemodelcolumnfortheCameratable,thoughyou
maywonderwhythecharactersequence:

"ASSIGNMENTUSER1659"."CAMERA"."MODEL"

appearsinthescreenshotabove,sinceitissomewhatdifficulttoread.Youseethe
familiarCAMERAandMODELkeywords,whichrepresenttheCameratableand
modelcolumn,respectively.Theyareseparatedwithaperiod(.)becausethisisthe
conventionfordrillingdownintoatable.Weuse:

Page27of36

TableName.ColumnName

toreferenceaspecificcolumninatableinanRDBMS.

ThereasonwhyASSIGNMENTUSER1659appearsinthescreenshotaboveisbecause
thatistheschemathatwasusedwhenthisassignmentwascreated.Wehavenot
studiedtheconceptofaschemayet,butbriefly,aschemaisalogicalandphysical
storagelocationfordurableentities.ModernRDBMSsupportmultipleschemasso
thatmultipleusersandapplicationscankeeptheirdurableentitiesseparate,intheir
owncontainers.InOracle,eachuserisassigneditsownschemabydefault,sowhen
theauthorofthisassignmentloggedinwithuserASSIGNMENTUSER1659,thetables
werecreatedbydefaultintheASSIGNMENTUSER1659schema.Thatiswhywesee
theASSIGNMENTUSER1659schemaintheerrormessageabove.

Now,itisunlikelythatyouchosethesameusername,andsoyouwillseeyourown
usernameinthescreenshothere,insteadoftheauthorsusername.Whatis
importanttonote,however,isthatwecanalsospecifyaschemanameinfrontof
anytablename.Weuse:

SchemaName.TableName.ColumnName

toreferenceacolumn,ifwealsowanttospecifytheschema,inanRDBMS.

Thereasoneachentityisenclosedinquotesisbecauseinordertosupportall
durableentitynames,includingthosewhichhavespacesorotherspecialcharacters,
theRDBMSsurroundsallnameswithquotestoavoidanyambiguity.

BelowisasamplescreenshotofthecommandexecutioninMicrosoftSQLServer
ManagementStudio.

Page28of36

Partoftheerrormessagewastruncatedinthescreenshot,soletusshowithere:

Msg515,Level16,State2,Line1
CannotinsertthevalueNULLintocolumn'model',table'master.dbo.Camera';
columndoesnotallownulls.INSERTfails.
Thestatementhasbeenterminated.

TheSQLServererrormessageinthisinstancemaybeeasiertointerpretthanthe
correspondingOracleerrormessage.ItdirectlystatesthataNULLvaluecannotbe
insertedintothemodelcolumn.JustaswithOracle,weseethatthereisfurther
qualificationofthetable.Inthescreenshotabove,itismaster.dbo.Camera.In
generalform,itis:

DatabaseName.SchemaName.TableName

Inthescreenshotabove,itisindicatingthattheCameratableresidesindatabase
master,inschemadbo.Masteristhedefaultdatabase,anddboisthe
defaultschemaforadatabaseuser.Ifyoufollowedtheinstructionstouseadatabase
otherthanmaster,youwillseeadifferentdatabasenameinyourscreenshot.

NotethatdifferentversionsofOracleandSQLServermaygivedifferenterror
messagesthanthoseillustratedabove.

41. LetuspracticelimitingthenumberofrowsandcolumnsreturnedbyaSELECT
statement.

SELECT model, description


FROM CAMERA
WHERE camera_id = 51;

ByindicatingthenamesofthecolumnsthatwewouldliketoseenexttotheSELECT
keyword,whereeachcolumnnameisseparatedbyacomma,weareomittingany
columnsnotinthelist.Inthisexample,wehaveindicatedthatwewouldliketosee
themodelanddescriptioncolumns,butnoothercolumns.

ByintroducingaWHEREclauseattheendoftheSELECTstatement,andusinga
Booleanexpressionthatindicatesthatweonlywanttoseerowswherethe

Page29of36

camera_idvalueis51,wehavelimitedthenumberofrowsreturnedinourresultset.
Trythecommandandseewhathappens.

42. Captureascreenshotofthecommandandtheresultofitsexecution.Belowisa
samplescreenshotofthecommandexecutioninOracleSQLDeveloper

BelowisasamplescreenshotofthecommandexecutioninMicrosoftSQLServer
ManagementStudio.

Noticethatinbothscreenshots,onlytherowwherecamera_idis51isreturned,andonly
themodelanddescriptioncolumnsareshown.

Whynotalwaysselectallrowsandallcolumnsfromthetable?Whybotherrestricting
either?Theanswerisefficiency.Ifwehaveaproductiontablewithabillonrowsandthirty
columns,butonlyneedonecolumnsvalueforoneofthoserows,itwouldbetimeand
resourceineffecientforthedatabasetoobtainallcolumnsvaluefromallbillionrows.It
wouldalsobetimeandresourceinefficientfortheenduserorapplicationtosearchthrough

Page30of36

thebillionresultsforthematch.Ifproperlyconfigured,anRDBMSwillveryefficiently
retrievethelimitedresultsneeded,evenifthenumberofrowsandcolumnsinthetableis
large.

TheBooleanexpressioninaWHEREclauseneednotonlyindicateonerow.Itcanindicate
manyrows.Infact,thereareavarietyofBooleanandmathematicaloperatorsthatcanbe
presentintheseexpressions,invirtuallyendlesscombinations.Exploringalloperatorsand
combinationsisbeyondthescopeofthisassignment,butifyouarecurious,youcanexplore
theseinthelectureandtextbook,andinotherresources.

43. Thegoodnewsisthatwedonotneedtolearnthreedifferentwaystolimittherows
affectedintheSELECT,UPDATE,andDELETEFROMcommands.Weusethesame
generalWHEREclauseforallthreecommands.Imaginethatwewanttoaddthe
samedescriptiontobothrowsthathavenodescription(wherecamera_id=52and
53),butwanttoavoidupdatingtherowthatalreadyhasadescription.Wecandoso
withthefollowingcommand.

UPDATE Camera
SET description = 'Great for landscapes'
WHERE camera_id = 52 OR camera_id = 53;

NoticethatweusedtheORBooleanoperatortocombinetwoexpressions.The
UPDATEappliestotherowthatmatcheseitherexpression.

44. Captureascreenshotofthecommandandtheresultofitsexecution.Belowisa
samplescreenshotofthecommandexecutioninOracleSQLDeveloper

Page31of36

BelowisasamplescreenshotofthecommandexecutioninMicrosoftSQLServer
ManagementStudio.

Noticethatbothscreenshotsindicatetworowswereaffected,whichiswhatweexpect.We
didnotupdateallrowsinthetable,butonlythosethatmatchedtheconditionexpressedin
theWHEREclause.

45. WecanappendageneralWHEREclausetoaDELETEFROMcommandtodeletethe
rowwherecamera_id=53.WewilldosousingadifferentBooleanexpression.

DELETE FROM Camera


WHERE camera_id > 52;

Noticethatweusedthegreaterthan(>)operator,andwecantranslatethis
statementtoEnglishas,DeleteallrowsfromtheCameratablethathavea
camera_idvaluegreaterthan52.Inourcase,weonlyhadonerowwithacamera_id
valuegreaterthan52,andthatwastherowwherecamera_id=53.Iftherehadbeen
additionalrowswithhighercamera_idvalues,theywouldhavealsobeendeleted.

46. Captureascreenshotofthecommandandtheresultofitsexecution.Belowisa
samplescreenshotofthecommandexecutioninOracleSQLDeveloper

Page32of36

BelowisasamplescreenshotofthecommandexecutioninMicrosoftSQLServer
ManagementStudio.

Noticethatbothscreenshotsindicatetwoonerowwasaffected.

47. NowletusviewthecontentsoftheCameratable,sothatwecanseetheresultsof
boththeUPDATEandDELETEcommandsweexecutedpreviously.

SELECT *
FROM CAMERA;

48. Captureascreenshotofthecommandandtheresultofitsexecution.Belowisa
samplescreenshotofthecommandexecutioninOracleSQLDeveloper

Page33of36


BelowisasamplescreenshotofthecommandexecutioninMicrosoftSQLServer
ManagementStudio.

Noticethatinbothscreenshots,therowwherecamera_id=53hasbeendeleted,andthe
rowwherecamera_id=52nowhasthedescriptionofGreatforlandscapes.Thisiswhat
weexpected.

Page34of36

SECTIONFOUR
OVERVIEW
InSectionFour,youwillapplywhatyoulearnedinSectionThreetoanewtable,without
beinggiventhecommandsandscreenshots.Thiswillhelptosolidifyyourlearning.You
willworkwiththeOcean_resorttablediagrammedbelow.Notethatthebolded
columnsrepresentthosewithaNOTNULLconstraint.

Ocean_resort
PK

ocean_resort_idDECIMAL(12)
nameVARCHAR(64)
descriptionVARCHAR(255)
date_openedDATE

STEPS

49. CreatetheOcean_resorttablewithallofitscolumns,datatypes,andnotnull
constraints.Captureascreenshotofthecommandandtheresultofitsexecution.

50. Insertarowwiththefollowingvalues.
ocean_resort_id=151
name=LightoftheOceanResort
description=Gorgeoussetting
date_opened=05May2001

Captureascreenshotofthecommandandtheresultofitsexecution.

51. Insertanotherrowwiththefollowingvalues.Makesurethatthecommaseparated
listofcolumnnamescontainsthedescriptioncolumn.
ocean_resort_id=152
name=BreathtakingBahamasResort
description=NULL
date_opened=23Mar1979

Captureascreenshotofthecommandandtheresultofitsexecution.

Page35of36

52. Insertanotherrowwiththefollowingvalues.Makesurethatthecommaseparated
listofcolumnnamesdoesnotcontainthedescriptioncolumn.
ocean_resort_id=153
name=LuxuriousLondonResort
date_opened=07Sep1910

Captureascreenshotofthecommandandtheresultofitsexecution.

53. SelectallrowsfromtheOcean_resorttable.Captureascreenshotofthecommand
andtheresultofitsexecution.

54. Attempttoinsertarowwiththefollowingvalues.Theinsertcommandwillfail
becausethenamecolumnmusthaveavalue.Youcanuseeithermethodtoattempt
toinserttheNULLvalue.
ocean_resort_id=154
name=NULL
description=ExperienceTheNetherlandsNoOtherWay
date_opened=03Jan1999

Captureascreenshotofthecommandandtheresultofitsexecution.

55. ExplainhowyouwouldinterprettheerrormessageillustratedinStep54to
concludethatthenamecolumnismissingarequiredvalue.

56. Retrieveonlythenameanddescriptionvaluesfortheonerowwhere
ocean_resort_idis151.Captureascreenshotofthecommandandtheresultofits
execution.

57. Explainwhyitisusefultolimitthenumberofrowsandcolumnsreturnedfroma
SELECTstatement,suchasthestatementperformedinStep56.

58. Tworowshavenodescription.Withasinglecommand,updatethedescriptionfor
bothofthemsothatthenewvalueisTheMostRelaxingPlaceonEarth.Capturea
screenshotofthecommandandtheresultofitsexecution.

59. Withasinglecommand,deleteallrowsthathaveanocean_resort_idgreaterthan
152.Captureascreenshotofthecommandandtheresultofitsexecution.

60. RetrieveallrowsandcolumnsfromtheOcean_resorttable.Captureascreenshotof
thecommandandtheresultofitsexecution.

Page36of36

También podría gustarte