You are on page 1of 30

Microsoft Technology Associate Series

Database Administration
Fundamentals
EXAM 98364

Fo

rE

va
lu

at
io

On
ly

COURSEWARE 83641

io
n

lu
at

va

rE

Fo

On
ly

ManipulatingData
LessonObjectives
Bytheendofthislesson,youwillbeableto:
UnderstandthepurposeandfunctionofDataManipulationLanguage(DML).

PerformdataentrytasksusingtheSSMSGUI.

Createadatabasediagram.

InsertdatausingtheINSERTstatement.

InsertdatausingINSERTscripts.

SelectdatausingtheSELECTstatement.

UpdatedatausingtheUPDATEstatement.

DeletedatausingtheDELETEstatement.

On
ly

ExamObjectives

io
n

1.3 Understanddatamanipulationlanguage
(DML)
3.1
Selectdata

3.2 Insertdata
3.3 Updatedata
3.4 Deletedata

DMLcommandsmanipulatedataandperformtheCRUDoperations(Create,Read,UpdateandDelete).Thesecommands
include:
INSERT

Usedtoinsertnewrowsintoatable.AvariationoftheINSERTstatementallowsyoutoinserttheresultsofa
queryintoatable.

SELECT

Usedtoselectdatafromadatabase.

UPDATE

Usedtochangethevaluesinarecord.

DELETE

Usedtodeleterecordsfromatable.

rE

1.3
3.2

Asyoulearnedearlier,SQLcommandsaregenerallygroupedintofourcategories,eachofwhichisconsideredasubsetof
SQL.DataManipulationLanguage(DML)isthelanguagethatisusedtoinsertdata,andupdateandqueryadatabase.
DMLstatementsoftenperformmathematicalandstatisticalcalculations.

va

Objective

lu
at

DataManipulationLanguage(DML)

AllRDBMSprogramsuseDMLcommandstomanipulatedata.InsomeprogramsyoucanentertheSQLcodedirectly.In
others, such as Microsoft Access, you can work with the data in a GUI and the SQL code is generated and executed
behindthescenes.

Fo

WewillbrieflyexaminedatamanipulationtechniquesusingtheSQLServerManagementStudioGUI,thentherestofthe
lessonwillbedevotedtowritingandexecutingSQLstatementsintheQuerywindow.

DataentryusingtheSSMSGUI
Microsoft SQL Server allows you to work with the data in your tables using a variety of methods. When you need to
performsimpledataentrytoaddormodifyarelativelysmallnumberofrecordsoneatatime,itmaybeeasiesttouse
SSMSgraphicinterface.
PerformingdataentrytasksusingtheSSMSGUIissimilartoworkingwithrecordsinaspreadsheet.Yousimplyclickina
cellandstarttyping.YoucanmovethepointerfromcelltocellbypressingTABorusingthemouse.Whenyoureachthe
endofarecord,youcanpressTABtomovetothenextnewrecordorclickintherowforthenewrecord.Userswho
haveperformeddataentryusingthedatasheetviewinMicrosoftAccesswillfindtheinterfacefamiliar.

83641v1.00CCILearningSolutionsInc.

61

Exercise31:DataentryintheSSMSGUI
Inthisexercise,youwillusetheSSMSGUItoperformdataentrytasks.
First,youwilladdrecordstotables.
LogontoSQLServerManagementStudio.
IntheObjectExplorer,expandtheDatabasesfolder,expandtheHomeGrownfolder,thenexpandtheTablesfolder
fortheHomeGrowndatabase.

3.

IntheObjectExplorer,rightclickdbo.CUSTOMERS,thenselectEditTop200Rowstoopenthetableforediting.

4.

ClickintheCustomerIDfieldifnecessary,type1012,pressTAB,typeHelen,pressTAB,typeJohnson,pressTAB,
type123MapleStreet,pressTAB,typeWestHempstead,pressTAB,typeNY,pressTAB,type11552,press
TAB,thentype5165552323.

Notice that a pencil icon displays in the record selector box at the left edge of the new record. The pencil icon
indicatesthatarecordcontainschangesthathavenotbeensaved.

5.

PressTABtosavethechangestothefirstrecordandmovetherecordpointertothenextrow.

6.

Type 1022, press TAB, type Andrew, press TAB, type Willis, press TAB, type 425 Cyprus Street, press TAB, type
QueenCreek,pressTAB,typeAZ,pressTAB,type85242,pressTAB,type4805553333,thenpressTABoncemore
tosavethesecondrecordandmovethepointertothenextrow.

YourtableshouldappearasshowninFigure31.

lu
at

io
n

On
ly

1.
2.

Figure31:AddingrecordstotheCUSTOMERStable

IntheObjectExplorer,rightclickdbo.ORDERS,thenselectEditTop200Rowstoopenthetableforeditinginanew
tabinthecenterpane.

8.

ClickintheOrderIDfieldifnecessary,pressTABtoskipovertheOrderIDfield,type1012,pressTABtwice,type
09192011,thenpressTABtwicetoenterarecordforanorder.Noticethatavalueisautomaticallyenteredinto
theOrderIDfieldwhenyousavetherecord.TheOrderIDfieldissettoautoincrement,andyoucannotmanually
enteravalueintothefield.

9.

PressTAB,type1023,pressTABtwice,type10212011,thenpressTABtwicetomovetherecordpointtothe
next row. Notice that SQL Server generates the error message shown in Figure 32 because of the foreign key
constraintontheCustomerIDfield.

Fo

rE

va

7.

Figure32

The value 1023 specified for the foreign key does not exist in the CUSTOMERS table, and therefore violates the
foreignkeyconstraint.

10. ClickOKtoclosetheerrormessage,changethevalueintheCustomerIDfieldto1022,thensavetherecord.

62

83641v1.00CCILearningSolutionsInc.

Notice that the OrderID increments to 3 instead of 2. When you attempted to commit (save) the record the first
time,SQLserverenteredthevalue2intheOrderIDfield.Becausetherowwasnotcommitted(duetotheforeign
key field constraint), and a new commit was attempted after you changed the data in the CustomerID field, the
valueintheOrderIDfieldincrementedagain.

Next,youwillmodify(update)arecord.
11. ClickthetabfortheCUSTOMERStable.SelectthevalueintheLastNamefieldforthefirstrecordandchangethe
lastnamefromJohnsontoAndersonbecauseHelengotmarried.PressSHIFT+ENTERtosavethechanges.
NotethatpressingSHIFT+ENTERaccomplishesthesamethingastabbingthroughthefieldsofarecordtomovethe
recordpointertothenextrow.

On
ly

Finally,youwilldeleterecords.

Figure33:Confirmingadeletion

lu
at

io
n

12. ClickthetabfortheORDERStable,clicktherowselectorforthesecondrowtoselectthesecondrow,rightclick
anywhere in the selected row and select Delete. SQL Server displays the message box shown in Figure 33
promptingyoutoconfirmthedeletion.

13. ClickYestoconfirmandpermanentlydeletetherecord.NoticethattheoneremainingrecordreferstoCustomer
1012.

rE

va

14. ClicktheCUSTOMERStab,clickintherecordselectorforthefirstrow,rightclickintheselectedrow,selectDelete,
thenclickYestoconfirmthedeletion.SQLServerdisplaystheerrormessageshowninFigure34becausearecord
intheORDERStablereferstoRow1intheCUSTOMERStable.

MMM

Fo

Application
Project31:
AScripted
Approach

Figure34:Deletionerror

15. ClickOKtoclosetheerrormessage.

16. Click the ORDERS tab, delete the remaining record, then click the close button to close the tab for the ORDERS
table.
17. IntheCUSTOMERStable,deletethefirstrecord.
18. DeletetheremainingrecordintheCUSTOMERStable,thenclosethetabfortheCUSTOMERStable.
19. InthemenubaratthetopoftheSSMSwindow,selectFile,ExittoclosetheSQLServerwindow.Ifprompted,do
notsaveanychanges.

In this exercise, you performed basic data entry tasks in the SSMS GUI, and you observed the effects of foreign key
constraints.

83641v1.00CCILearningSolutionsInc.

63

RecreatingtheHomeGrownDatabase
Although you created several tables for the HomeGrown database in Lesson 2, you will drop and then recreate the
entiredatabaseusingSQLcodeprovidedintheStudentDatafolder.Recreatingthedatabaseanditsobjectswillensure
thatallexercisestepsinthislessonwillproducetheexpectedresults.
SQLcodecanbestoredintextdocumentsandpastedintotheQuerywindowforexecution.Althoughcodecanbestored
inaWorddocument,itiscustomarytosavethecodetoatextdocument,witha.sqlfilenameextension.Codestoredin
thismannerisreferredtoasaSQLscript.

On
ly

Aspartoftherecreationofthedatabase,youwillalsocreateadatabasediagram.Adatabasediagramindicateshow
tablesinadatabasearerelatedtoeachother.Becausetheserelationshipsaredeterminedbytheforeignkeyconstraints,
creatingadatabasediagramcanallowyoutocheckandensurethatyourtablesarerelatedinthewayyouintended.

Exercise32:RebuildingtheHomeGrowndatabase

Inthisexercise,youwilldroptheHomeGrowndatabaseandthenrecreateitusingaSQLscriptinthe
StudentDatafolder.Youwillalsocreateadatabasediagram.
LogontoSQLServerManagementStudio.

2.

ExpandtheDatabasesfolder,rightclicktheHomeGrownfolder,thenselectDelete.

3.

WhentheDeleteObjectwindowopens,clickOKtoconfirmthatyouwanttodeletetheHomeGrowndatabaseand
allitsobjects.

4.

In the menu bar at the top of the SSMS window, select File, Open, File, then in the Student Data folder on the
desktop, navigate to the Lesson_3 folder and doubleclick theHomeGrown Creation Code.sql file to open it in a
newQuerywindow.ThissimpletextdocumentcontainstheSQLcodenecessarytorecreatethedatabase.

5.

Examinethecodecarefully,notingtheforeignkeyconstraintsandthefieldsthatcannotcontainnullvalues.

lu
at

io
n

1.

ThesettingsusedintheHomeGrowndatabasearefairlypermissiveinthatmostfieldsareallowedtocontainnullvalues,
and these settings have been chosen to speed data entry. In most realworld applications, the constraints would be
tighter. Note however, that the ON DELETE and ON UPDATE clauses specify NO ACTION, which is the most restrictive
setting.Thesesettingshavebeenchosentoillustratecertainpointsabouthowconstraintsaffectdataentry.
ClicktheExecutebuttonintheSQLEditortoolbartorunthecodeandrecreatethedatabaseanditstables.

7.

ClosetheQuerywindowwithoutsavingthechanges.

8.

IntheObjectExplorer,rightclicktheDatabasesfolder,thenselectRefreshtoshowthenewlycreatedHomeGrown
databaseinthefolderlist.

9.

ExpandtheHomeGrownfolder,thenexpanditsTablesfoldertoviewtheobjectsandverifythatallsixtableswere
created.

rE

va

6.

Fo

10. In the Object Explorer, rightclick the HomeGrown Database Diagram folder and select New Database Diagram.
SQLServerdisplaysthemessageshowninFigure35.

Figure35

11. ClickYestospecifythatyouwanttocreatethesupportobjects.SQLServeropensadatabasediagramwindowand
theAddTabledialogbox,showninFigure36.

64

83641v1.00CCILearningSolutionsInc.

On
ly

Figure36:AddTabledialogbox

12. IntheAddTabledialogbox,clicktheAddbuttonsixtimes(onceforeachtable),thenclicktheClosebutton.

io
n

Note:YoucanalsoclickthefirsttableintheAddTabledialogbox,pressandholdSHIFT,andthenclickthelasttablein
thedialogboxtoselectallsixtables.ClickingtheAddbuttonwouldthenaddallselectedtablestothediagramwindow
atonce.
13. Maximize the SQL Server window, then click the close button in the Object Explorer window and the Properties
windowtoexpandtheworkspaceforthedatabasediagram.

YourdatabasediagramshouldresembletheoneshowninFigure37.

Fo

rE

va

lu
at

14. Youcanmoveatableinthediagramwindowbyclickingthetableoncetoselectit,thendraggingitintothedesired
position.Rearrangethetablesinthediagramwindowuntilyoucanseehowtheyareallrelated.

Figure37:DatabasediagramforHomeGrown

Noticethatdatabasediagramshowstheprimarykeys,andtheonetomanyrelationshipsinthedatabase.

15. IntheStandardtoolbar,clicktheSavebuttonandacceptthedefaultname,Diagram_0,byclickingOK.
16. Inthemenubar,selectView,ObjectExplorertoreopentheObjectExplorerwindow.

83641v1.00CCILearningSolutionsInc.

65


17. Inthemenubar,selectView,PropertiesWindowtoreopenthePropertieswindow.
18. Closethedatabasediagram.
19. MinimizetheSQLServerwindow.

Inthisexercise,yourecreatedtheHomeGrowndatabaseandyoucreatedadatabasediagram.

MMM
Optional
Exercise31:
SameResults
EveryTime

TheINSERTStatement
3.2

ThesimplestformoftheINSERTstatementusesthefollowingsyntax:
INSERTINTOtable_name
VALUES(value1,value2,)

On
ly

TheSQLINSERTstatementaddsdatatoatableinadatabase,andthecommandhasseveralvariations.
Objective

ThisformofthestatementliststhevaluestobeinsertedintoanewrecordaftertheVALUESkeyword.Thevaluesmust
havethecorrectdatatypesandmustbelistedinthesameorderasthefieldsinthetable.

lu
at

io
n

ConsidertheCUSTOMERStableandSQLcreationcodeshowninFigure38:

Figure38:CUSTOMERStablelayoutandSQLcreationcode

va

YoucouldusethefollowingcommandtoaddarecordtotheCUSTOMERStable:
INSERTINTOCUSTOMERS
VALUES(1012,'Helen','Anderson','123MapleStreet','WestHempstead','NY','11552','5165552323')
In SQL, all nonnumeric data values must be enclosed in single quotation marks, as shown in the sample command
above.Numericdatatypesdonotrequirethesinglequotationmarks,andinfactwillbetreatedasaCHARdatatypeif
singlequotationmarksareused.

Fo

rE

Noticethatinthesamplecommand,dataisindicatedforeveryfield.Youcannotskipfieldswhenusingthisformofthe
INSERTstatement,unlessthefieldissettoautoincrement.Youcan,however,usetheNULLkeywordifthevalueofa
particularcolumnisunknownatthetimeofaninsertoperation.Forexample,youcouldusethefollowingstatementto
enterdataforacustomerwhodoesnothaveaphonenumber:
INSERTINTOCUSTOMERS
VALUES(1022,'Andrew','Willis','425CyprusStreet','QueenCreek','AZ','85242',NULL)
NotethattheNULLkeyworddoesnotrequiresinglequotationmarks.
IfyoudefinedacolumnusingtheNOTNULLconstraint,however,youmustenteravalidvalueforthecolumn.Inthe
CUSTOMERStable,forexample,youcouldusetheNULLkeywordfortheStreet,City,State,ZIPandPhonefieldsonly.

WhenyouexecuteanINSERTstatementintheQuerywindow,theonlyvisibleresultisamessageatthebottomofthe
windowindicatingthattheoperationwassuccessfullycompleted.Toviewthenewlyinsertedrecord,youwouldneedto
executeaSELECTstatement.
Ifanerroroccurs,anerrormessage(ormessages)displaysatthebottomofthewindow,andtheoperationisaborted.

66

83641v1.00CCILearningSolutionsInc.

SpecifyingcolumnsforanINSERTstatement

MMM

TheINSERTstatementcanalsodesignatethecolumnsintowhichvaluesaretobeinserted.Consider
thefollowingexample.
INSERTINTOCUSTOMERS(CustomerID,FirstName,LastName,Phone)
VALUES(1080,'Jill','Jackson','7145556767')

Application
Project32:
InsertTabA
intoSlotB

On
ly

The columns that were not named (Street, City, State and ZIP) will be given their default values for this record. The
default value is any designated default for the columns or a NULL. If the column has no designated default value and
doesnotacceptnulls,youmustsupplyavalueforthatcolumnorthestatementwillgenerateanerror.
ManySQLprogrammersprefertoalwaysincludecolumnnamesinINSERTstatementsbecauseitmakesthestatements
clearerandeasiertomaintain.

Activity31:ReadingINSERTstatements

io
n

Inthisactivity,youwillexaminethestructureoftheCUSTOMERStableshowninFigure38,andactas
ifyouarethecomputerbyexecutingthefollowingfournumberedINSERTstatementsonpaperonly.
Writetheresultsofeachinsertstatementintothegrid,orwritetheword"ERROR"intothegridifa
particularstatementwillgenerateanerror.Thefirstonehasbeencompletedforyou:
1. INSERTINTOCUSTOMERS
VALUES(1030,'Alice','Goldman',NULL,'Mesa','AZ',NULL,NULL)

2. INSERTINTOCUSTOMERS
VALUES(1034,'Robert','Meyers','29RiverStreet','Mesa','AZ','85202','4805557777')

lu
at

3. INSERTINTOCUSTOMERS
VALUES(1035,'Anna','Billings','Mesa','AZ','85203','4805558888')

Whenyouarefinished,compareyourresultswiththerestoftheclass.

rE

va

4. INSERTINTOCUSTOMERS(CustomerID,FirstName,LastName,City,ZIP)
VALUES(1044,'Melissa','Sharon',NULL,'Flagstaff','86002')

INSERTstatementsandautoincrementfields

Fo

OftentablesincludeIDfieldsthataresettoautoincrement.Justasyoucannottypeavalueintoanautoincrementfield
in the SSMS GUI, you cannot insert a value into an autoincrement field with an INSERT statement. Skip the auto
incrementfieldwhenlistingvaluesorwhennamingthecolumnsintheINSERTstatement.
Forexample,considertheVENDORStableandSQLcreationcodeshowninFigure39:

Figure39:VENDORStablelayoutandSQLcreationcode

83641v1.00CCILearningSolutionsInc.

67


YoucanaddarecordtotheVENDORStablewitheitherofthefollowingstatements:
INSERTINTOVENDORSVALUES('GoodEarthSupplies','21GreenWay','Ajo','AZ','85321','5205559997')
INSERTINTOVENDORS(Name,Street,City,State,ZIP,Phone)
VALUES('GeoGiant','1441Scirocco','Woodstock','NY','12498','8455557997')

Exercise33:AddingrecordsusingINSERTstatements
Inthisexercise,youwillwriteandexecuteINSERTstatementstoadddatatotheHomeGrowndatabase.

On
ly

YouenterandexecuteSQLstatementsintheQuerywindow.
RestoretheSQLServerwindow.

2.

IntheStandardtoolbar,clicktheNewQuerybuttontoopenaQuerywindow.

3.

TypeUSEHomeGrown.

4.

PressENTERtwoorthreetimestoaddsomewhitespace.

5.

TypeINSERTINTOCUSTOMERS
VALUES(1012,'Helen','Anderson','123MapleStreet','WestHempstead','NY',
'11552','5165552323')

6.

PressENTERtwice.

7.

TypeINSERTINTOCUSTOMERS
VALUES(1022,'Andrew','Willis','425CyprusStreet','QueenCreek','AZ',
'85242',NULL)

8.

PressENTERtwice.

9.

TypeINSERTINTOCUSTOMERS(CustomerID,FirstName,LastName,Phone)
VALUES(1080,'Jill','Jackson','7145556767')

YourscreenshouldresembletheoneshowninFigure310.

rE

va

lu
at

io
n

1.

Figure310:WritingINSERTStatements

Fo

10. EnsurethattheCustomerIDvaluesyouenteredmatchtheonesshowninFigure310,asthesewillbeimportant
throughouttheremainderofthislesson,thenclicktheExecutebuttontoinsertthethreenewrecords.

Becauseyouexecutedthreestatements,theSQLServermessagewindowliststhreeresponses,eachofwhichreads
"(1row(s)affected)."

11. IntheObjectExplorer,expandthenecessaryfolderstoviewthetablesintheHomeGrowndatabase.

12. IntheObjectExplorer,rightclicktheCUSTOMERStable,thenselectEditTop200Rowstoviewthenewlyinserted
records.
13. ClosethetabfortheCUSTOMERStable.
14. ClosetheQuerywindowwithoutsavinganychanges.

68

15. MinimizetheSQLServerwindow.

83641v1.00CCILearningSolutionsInc.

UsingINSERTScripts
Asyoumayhavealreadyguessed,anINSERTscriptissimplyatextdocumentthatcontainsaseriesofINSERTstatements
thatyoucancopyandpasteintotheQuerywindowforexecution.Writingscriptsallowsyoutocarefullyreviewthedata
beforeaddingittoyourtables.

On
ly

WhenyouexecuteINSERTscripts,youmustkeepforeignkeyconstraintsinmindsoyouadddatatoyourtablesinthe
correct order. For example, in the HomeGrown database, you could not enter data into the ORDERS table until you
entered data into the CUSTOMERS and ORDERSTATUSES tables because the ORDERS table includes two foreign key
constraints.OnethatreferstotheCustomerIDfieldintheCUSTOMERStableandonethatreferstotheOrderStatusfield
intheORDERSTATUSEStable.
ToadddatatotheHomeGrowndatabase,youcanexecutethelistedINSERTscripts(whichareincludedintheStudent
Datafolder)inthefollowingorder:
CUSTOMERSInserts.sql
VENDORSInserts.sql
ORDERSTATUSESInserts.sql
INVENTORYITEMSInserts.sql
ORDERSInserts.sql
ORDERITEMSInserts.sql

MMM

Optional
Exercise32:
LookMa,No
Hands

io
n

1.
2.
3.
4.
5.
6.

Theorderofthefirstthreescriptsdoesnotmatter,becausethesetablesdonotincludeforeignkeys.However,allthree
ofthesescriptsmustbeexecutedbeforeyouexecutethelastthree.
Oftheremainingthreescripts,youmustexecuteORDERITEMSInsert.sqllast.

lu
at

Youcancopy,pasteandexecuteeachscriptindividually,oryoucanpastethecontentsofallthescriptsintotheQuery
windowandexecutethestatementsallatonce.YoucanalsopasteallofthescriptsintotheQuerywindow,butexecute
eachstatementoneatatimebyhighlightingastatement;whenyouclicktheExecutebuttonSQLServerwillonlyrunthe
highlightedstatement.

Exercise34:AddingrecordsusingINSERTscripts
Inthisexercise,youwilladddatatotheHomeGrowndatabaseusingINSERTscripts.

va

Note:Forthesakeofexpediency,ascriptnamedTableInserts.sqlcanbeusedtopopulateallthetablesin
the database at once. If you opt to use this method for adding records, use TableInserts.sql instead of
CUSTOMERSInserts.sqlinSteps17ofthisexercise,anddonotperformStep8.
First,youwillexamineanINSERTscript.

NavigatetotheLesson_3folderintheStudentDatafolder.

2.

RightclickCUSTOMERSInserts.sql,selectOpenWith,thendoubleclickNotepadintheOpenWithdialogbox.This
stepopensthefileintheNotepadwindow.Althoughyoucanopena.sqlfiledirectlyinSSMS(asyoudidinExercise
32),filesofthistypecanalsobeopened(andcreated)inasimpletexteditor.ThefilecontainsaseriesofINSERT
statements,asshowninFigure311.

Fo

rE

1.

83641v1.00CCILearningSolutionsInc.

69

Figure311:CUSTOMERSInserts.sqlfile

ClosetheINSERTscript.

4.

RestoretheSQLServerwindow.

5.

In the menu bar at the top of the SSMS window, select File, Open, File, then in the Student Data folder on the
desktop,navigatetotheLesson_3folderanddoubleclicktheCUSTOMERSInserts.sqlfiletoopenitinanewQuery
window.YourQuerywindowshouldappearasshowninFigure312.

lu
at

3.

Fo

rE

va

io
n

On
ly

70

Figure312:INSERTscriptforCUSTOMERStableinQuerywindow

83641v1.00CCILearningSolutionsInc.


6.

ClicktheExecutebutton.

7.

ClosetheQuerywindowwithoutsavingthechanges.

8.

Repeat Steps 5 through 7 for the remaining scripts in the following order: VENDORSInserts.sql,
ORDERSTATUSESInserts.sql,INVENTORYITEMSInserts.sql,ORDERSInserts.sql,ORDERITEMSInserts.sql.

9.

IntheObjectExplorer,rightclicktheCUSTOMERStable,thenselectEditTop200Rowstoviewthenewlyinserted
records.Thetableshouldinclude14records.

10. ClosethetabfortheCUSTOMERStable.

12. MinimizetheSQLServerwindow.

On
ly

11. Checktherecordcountfortheremainingtables.Theyshouldbeasfollows:
INVENTORYITEMS41records
ORDERITEMS51records
ORDERS15records
ORDERSTATUSES4records
VENDORS6records
Inthisexercise,youusedSQLINSERTscriptstoadddatatotablesinadatabase.

io
n

CaseScenario31:Yes,WeHaveThat!

Now that you have created a database and tables for the Illuminated Manuscript book shop,
writeandexecuteINSERTstatementstoaddtheindicatedrecordstothefollowingtables:
Records
Romance
Adventure
Horror
Humor
ScienceFiction
SelfHelp

Table

AUTHORS

lu
at

Table

CATEGORIES

Records
KennethKozakis
StephanieBrendenhall
RonBartlow
JulianHarrolds
LindaCentini
LyndelGeorges
AndrewSilver
PatrickKelley

va

YoumayexecuteyourstatementsindividuallyintheQuerywindow,orsavethemtoatextfileandthencopy,pasteand
executethemintheQuerywindow.
Afteryouhaveaddedyourrecords,editthetwotablestoviewthenewlyaddedrecords.

After you have tried creating and entering data, delete your version of the Illuminated database. Recreate the
Illuminated database, then recreate the necessary tables for the database by executing the statements in the
Lesson_3\Illuminated CreationCode.sql file. Insert data into the tables by executing the statements in the Lesson_3\
IlluminatedInserts.sqlfile.

Fo

rE

Whenyouaredoneinsertingthelisteddata,createdatafortheremainingtablesintheIlluminateddatabase.Studythe
relationalmodelcloselytodetermineinwhichorderyoushouldaddrecords.Theforeignkeyconstraintsshouldprevent
youfromenteringmismatcheddata.

SelectingData

Objective

3.1

TheSQLSELECTstatementisaDMLstatementusedtochoose(select)orretrievedatafromadatabase.Informalterms,
selectingdataiscalledexecutingaquery.Therecordsreturnedasaresultofaqueryarecalledaresultset,orarecord
set.

Initssimplestformat,theSELECTstatementtakesthefollowingsyntax:
SELECT*FROMtable_name
Inthisform,thestatementreturnsalltherecordsfromthenamedtable.Theasterisk(*)representsallthefieldsinthe
table.Forexample,ifyouexecutedthestatementSELECT*FROMCUSTOMERSintheHomeGrowndatabase,SQLServer
wouldreturntheresultsshowninFigure313.

83641v1.00CCILearningSolutionsInc.

71

On
ly

Figure313:ResultsofSELECT*FROMCUSTOMERSstatement

Note that queries may not always return the records in the same order. SQL provides mechanisms for ordering data.
Thesemechanismswillbeexploredlaterinthislesson.

io
n

Youcanalsolistthefieldsyouwanttoretrieve.Forexample,thefollowingstatementwouldreturnthesameresultas
thefirstSELECTexample:
SELECTCustomerID,FirstName,LastName,Street,City,State,ZIP,Phone
FROMCUSTOMERS

lu
at

EveryquerymustincludetheSELECTkeywordindicatingthecolumnsthataretoberetrieved(ortheasterisktoindicate
thatallcolumnsaretoberetrieved)andaFROMkeywordindicatingthetablesthatareinvolvedinthequery.Youcan,of
course,specifyonlyspecificcolumns.ForexamplethefollowingcommandwillreturntheresultsshowninFigure314.

Fo

rE

va

SELECTLastName,FirstName,ZIP
FROMCUSTOMERS

Figure314:Selectingspecificcolumns

SELECTDISTINCT
TheDISTINCTkeywordisusedtoensurethataqueryreturnsonlyunique(thatis,distinct)values.

SupposeyouneededalistofthestatesinwhichHomeGrownGardenSupplieshascustomers.Thenumberofcustomers
isnotneeded,justthestateswherethecompanyhascustomers.Thequerycouldbewrittenasfollows.
SELECTStateFROMCUSTOMERS

72

83641v1.00CCILearningSolutionsInc.

On
ly

Thequerywouldreturnthefollowingoutput:
NY
AZ
AZ
AZ
NY
NY
AZ
IL
IL
CA
WA
NE
AL

NotethatthevaluesNY,AZandILarerepeatedbecauseseveralcustomersliveinthesestates.Toretrievenonduplicate
data,youcanusetheDISTINCTkeyword,asinthefollowingexample.

lu
at

Thequerywouldreturnthefollowingoutput:
AL
AZ
CA
IL
NE
NY
WA

io
n

SELECTDISTINCTStateFROMCUSTOMERS

Noticethattherecordsarenotnecessarilyreturnedintheorderinwhichtheyareenteredinthetable.

SELECTWHERE

va

AWHEREclauseisfrequentlyaddedtoaSELECTstatementinordertoapplyafiltertothereturnedrecordset.Informal
terms, a WHERE clause is used to add a predicate to a SQL statement When you use a WHERE clause in a SELECT
statement, each row in the table is evaluated against the condition(s) in the predicate. Only the rows that meet the
condition(s)inthepredicateareincludedintheresultset.

rE

ThefollowingexampleillustratesaWHEREclause.
SELECTCustomerID,LastName,FirstName
FROMCUSTOMERS
WHERECustomerID=1012
ThequerywouldreturnthefollowingoutputintheHomeGrowndatabase:
1012
Anderson
Helen

Fo

WiththedatacurrentlyinthisspecificCUSTOMERStable,thefollowingSELECTstatementwouldreturnthesameresults:
SELECTCustomerID,LastName,FirstName
FROMCUSTOMERS
WHERELastName='Anderson'

Equalityoperators
Equalityoperatorsareusedtocomparetwovalues.Youhavealreadyseentheequalsign(=)operatorusedinaSQL
predicate.SQLsupportsthefollowingequalityoperators:
In some versions of

= equalto
SQL, the not equal

> greaterthan
to operator is

< lessthan
written as (!=)

>= greaterthanorequalto
instead of (<>).

<= lessthanorequalto

<> notequalto

83641v1.00CCILearningSolutionsInc.

73


As you have seen, you must enclose nonnumeric values in single quotation marks when comparing them. Numeric
valuesarenotenclosedinsinglequotationmarks.
ReviewthefollowingSELECTstatements(executedagainsttheCUSTOMERStableintheHomeGrowndatabase)andtheir
accompanyingresultsetstoseehowtheoperatorsareused:
SELECTLastName,FirstName,ZIP
FROMCUSTOMERS
WHEREZIP='60451'

On
ly

SELECTLastName,FirstName,ZIP
FROMCUSTOMERS
WHEREZIP>'60451'

lu
at

SELECTLastName,FirstName,ZIP
FROMCUSTOMERS
WHEREZIP>='60451'

io
n

SELECTLastName,FirstName,ZIP
FROMCUSTOMERS
WHEREZIP<'60451'

rE

va

SELECTLastName,FirstName,ZIP
FROMCUSTOMERS
WHEREZIP<='60451'

Fo

SELECTLastName,FirstName,ZIP
FROMCUSTOMERS
WHEREZIP<>'60451'

IfanyoftheseoperatorsisusedtocompareaparticularvaluetoaNULLvalue,anUNKNOWNisreturnedandtherecord
isnotincludedintheresultset.Inthepreviousexamples,noticethatrecord#14forJillJacksonisnotreturnedinanyof
theresultsetsbecauseherZIPcodeiscurrentlysettoNULL.NotealsothataNULLvalueisnottreatedasifitisthesame
asthevalueof0(zero).

74

83641v1.00CCILearningSolutionsInc.

TheANDoperator
SQLsupportsthelogicaloperatorsANDandOR.
TheANDoperatorlinkstogethertwoormoreconditionalstatements,andprovidesforincreasedfiltering.Whenyouuse
theANDoperator,bothexpressionsoneithersideoftheANDmustbeevaluatedtotrueforanygivenrecordtoappear
intheresultset.

On
ly

ConsidertheCUSTOMERStableagainandtheseriesofSQLstatementsandresultsets.Inthefirstexample,ninerecords
satisfytheconditionoftheexpressionintheWHEREclause:EachrecordmustincludeaZIPcodegreaterthan6000.
SELECTFirstName,LastName,State,ZIP
FROMCUSTOMERS
WHEREZIP>'60000'

lu
at

io
n

SELECTFirstName,LastName,State,ZIP
FROMCUSTOMERS
WHEREZIP>'60000'
ANDState<>'IL'

Noticethatinthisresultset,therecordsmustmeetthecriteriaspecifiedinbothexpressionsintheWHEREclause.Each
recordmustincludeaZIPcodegreaterthan60000andtheStatecannotbeequaltoIL.

va

SELECTFirstName,LastName,State,ZIP
FROMCUSTOMERS
WHEREZIP>'60000'
ANDState<>'IL'
ANDLastName>='H'

In this result set, the records must meet all three conditions specified by the expressions in the WHERE clause. Each
recordmustincludeaZIPcodegreaterthan60000,theStatecannotbeequaltoIL,andtheLastNamemustbeginwith
theletterHorhigher.NotethatyoucanfinetunearesultsetbyaddingexpressionstotheWHEREclause.

rE

TheORoperator

TheORoperatorisalsousedtohelpfilterresultsets.Insteadoflinkingtogetherconditionalstatements,theORoperator
causes SQL to look for two separate conditions within the same query and return any rows meeting either of the
conditions.

Fo

Considerthefollowingstatementandresultset:
SELECTFirstName,LastName,State,ZIP
FROMCUSTOMERS
WHEREZIP>'60000'
ORState<>'IL'

Notice that the records in this result set meet either the first condition (ZIP > '60000') or the second condition
(State<>'IL').
83641v1.00CCILearningSolutionsInc.

75

TheAND/ORcombination
Conditional statements can be grouped together using parentheses (). Just as in other programming languages and
mathematics, the parentheses are meant to group expressions that should be resolved as a group, and the result is
treatedasasingleexpression.Byusingparentheses,youcanlinkconditionstogethertocreaterobustqueries.
Forexample,considerthefollowingSELECTstatementthatemploysanAND/ORcombination.

On
ly

SELECTFirstName,LastName,State,ZIP
FROMCUSTOMERS
WHERE(ZIP>'60000'ANDState<>'IL')
ORState='AL'

io
n

Noticethattheresultsetincludesrecordsthatmeetbothoftheconditionsinthefirstclause,andtheonerecordthat
meetstheconditioninthesecondclause.Inthisexample,ZIP>'60000'ANDState<>'IL'isevaluatedfirst.
SQLlooksateachrecordanddetermineswhetherZIP>'60000'andwhetherState<>'IL'.Ifbothexpressionsaretrue,
theentirestatementwithintheparenthesesreturnsatrue.
Groupeddifferently,thesameexpressionscanretrievedifferentresults,asshowninthefollowingexample.

lu
at

SELECTFirstName,LastName,State,ZIP
FROMCUSTOMERS
WHEREZIP>'60000'
AND(State<>'IL'ORState='AL')

Truthtables

va

AtruthtableisatablethatillustratestherelationshipsofthelogicaloperatorsANDandOR.Atruthtableismadeupof
twocolumnswith1sand0sorTsandFsforTrueandFalse.Asyoulearnedintheprevioussection:
InalogicalAND,allitemsmustbetruetogeta"True"result.

InalogicalOR,onlyoneoftheitemsmustbetruetogetaTrue"result.

Theorderoftheitemshasnotinfluenceontheresultofatruthtable.

rE

Fo

ThetruthtablesforlogicalANDandORareshowninFigure315.

Figure315:TruthtablesforLogicalANDandLogicalOR

TheNOTkeyword
TheNOTkeywordisusedtoreverseanexpression'svalue.Forexample,considerthefollowingstatementanditsresult
set.
SELECTFirstName,LastName,State,ZIP
FROMCUSTOMERS
WHERENOTZIP>'60000'

76

83641v1.00CCILearningSolutionsInc.


TheNOTkeywordisplacedbeforethecolumn'sname,notafterit.InEnglish,itwouldbenaturaltosay"ZIPcodeisnot
greaterthan60000."However,usingthissyntaxwouldgenerateanerror.

TheISNULLstatement
You can use the IS NULL statement to test for null values. The statement will return either true (a NULL value is
present)orfalse.
Considerthefollowingstatementanditsresultset.
SELECTFirstName,LastName,State,ZIP
FROMCUSTOMERS
WHEREStateISNULL

On
ly

Conversely,usingtheNOTkeywordwiththeISNULLstatementcanreturnallrowsthatdonotcontainaNULLvaluefor
thespecifiedfield.Thesyntaxforsuchastatementwouldbe:
SELECTFirstName,LastName,State,ZIP
FROMCUSTOMERS
WHEREStateISNOTNULL

TheINoperator

io
n

TheSQLINoperatorisusedtoselectdatathatmatchesalistofvalues.Forexample,ifyouwantedtoretrievecustomer
datafortwoormorecustomers,youcouldusetheINoperatortospecifyalistofcustomernames,andthequerywould
retrieverowsreflectingeverycustomernameincludedinthelist.
Considerthefollowingstatementanditsresultset.

lu
at

SELECTFirstName,LastName,State,ZIP
FROMCUSTOMERS
WHERELastNameIN('Anderson','Armstrong','Keller',
'Jackson')

Note:TheWHEREclauseinthisstatement(WHERELastNameIN('Anderson','Armstrong','Keller','Jackson')isequivalent
to(WHERELastName='Anderson'ORLastName='Armstrong'ORLastName='Keller'ORLastName='Jackson').TheIN
operatorispreferredbecauseitismoreefficient,andforlargedatabasesthismakeabigdifferenceinperformance.

va

Conversely,theNOTINoperatorcanbeusedtoeliminaterecordsfromaresultset,asshownbythefollowingstatement
anditsresultset.

Fo

rE

SELECTFirstName,LastName,State,ZIP
FROMCUSTOMERS
WHERELastNameNOTIN('Anderson','Armstrong','Keller',
'Jackson')

TheBETWEENoperator
YoucanusetheBETWEENoperatortoqueryatableforrowsthatmeetaconditionfallingbetweenaspecifiedrangeof
values.Thevaluescanbenumbers,textordates.TheANDkeywordisusedwiththeBETWEENoperatortodefinethe
range.Thevaluesthatestablishtheupperandlowerlimitsoftherangearecalledtestvalues.Thefirsttestvalueinthe
BETWEEN clause must be either alphabetically or numerically before the second test value. Consider the following
statementsandtheirresultsets:

83641v1.00CCILearningSolutionsInc.

77


SELECTFirstName,LastName,State,ZIP
FROMCUSTOMERS
WHERECustomerIDBETWEEN1012AND1034

On
ly

SELECTCustomerID,FirstName,LastName,State,ZIP
FROMCUSTOMERS
WHEREstateBETWEEN'C'AND'J'
The BETWEEN operator is handled differently by different DBMSs. In some databases, the BETWEEN operator is
exclusive; selects only the rows that are between the test values and excludes records matching the test values
themselves.
In most DBMSs, the BETWEEN operator is inclusive; selects rows that are between the test values, and includes rows
matchingthetestvalues.
In still other DBMSs, the BETWEEN operator selects rows between the test values, including the first test value, but
excludingthelasttestvalue.
ItisimportanttocheckyourdatabasedocumentationtoseehowtheBETWEENoperatorishandled.

io
n

In SQL Server, the BETWEEN operator is inclusive, meaning that it selects rows that are between the test values and
includesrowsmatchingthetestvalues.

TheLIKEoperator

lu
at

TheLIKEoperatorisusedtotestforaspecifiedpatterninacolumncontainingcharacterdata.Wildcardcharactersare
usedwiththeLIKEoperator.Thewildcardcharactersaretheunderscore(_)andthepercentsign(%).
Theunderscorecharacterisusedtorepresentindividualcharacters.Forinstance,thestringf__twouldmatchfoot,fact,
fortandfast,butwouldnotmatchfatorfirst.
Thepercentsignisusedtorepresentastringofzeroormorecharacters.Forinstance,thestringf%twouldmatchfoot,
fact,fort,fast,fat,first,furthestandthestringft,butwouldnotmatchfactsorfits.

va

Considerthefollowingselectstatementsandtheirresultsets.Thefirstoneselectsrecordswherethecitybeginswiththe
letterO.ThesecondoneselectsrecordswherethecityincludestheletterOanywhereinthecityname.Thethird
oneselectsrecordswherethecitydoesnotincludetheletterOanywhereinthecityname,andthefourthoneselects
recordsforcitiesthatendintheletterD.

rE

SELECT*
FROMCUSTOMERS
WHERECityLIKE'o%'

Fo

SELECT*
FROMCUSTOMERS
WHERECityLIKE'%o%'

SELECT*
FROMCUSTOMERS
WHERECityNOTLIKE'%o%'

SELECT*
FROMCUSTOMERS
WHERECityLIKE'%d'

78

83641v1.00CCILearningSolutionsInc.


In every one of these examples, SQL is caseinsensitive when comparing the data. That is, an upper case letter O is
equivalenttoalowercaselettero.Thisbehavioriscontrolledbythecollationsettingforthedatabase.Ifyouchoosea
different collation setting, then SQL could treat the letters O and o as nonequivalent, and sort them into different
groups.

TheORDERBYclause
SQLalsoprovidestheORDERBYclausetoallowoutputtobesortedbasedonacolumnorgroupofcolumns.Theorder
ofoutputcanbedesignatedasascending(ASC)whichisthedefault,ordescending(DESC).

On
ly

SupposeyouwanttosendoutabulkmailingtoyourcustomersandyouneedtosortyourlistbyZIPcodeindescending
order.Youcouldaccomplishthatwiththefollowingstatement.

lu
at

io
n

SELECT*
FROMCUSTOMERS
ORDERBYZIPDESC

TheORDERBYclausecanalsousemultiplecolumnstoordertheoutput.Forexample,supposeyouwanttoseealistof
inventoryitemsforaparticularvendor,listedindescendingorderbypriceandquantityinstock.Considerthefollowing
statementanditsresultset.

MMM
Application
Scenario31:
Making
Predictions

rE

va

SELECT*
FROMINVENTORYITEMS
WHEREVendorID=3
ORDERBYPriceDESC,QuantityInStockDESC

Exercise35:Selectingdata

Fo

Inthisexercise,youwillexecutequeriesagainstthetablesintheHomeGrowndatabase.

1.

RestoretheSQLServerwindow.

2.

OpenanewQuerywindow.

3.

Type:USEHomeGrown,pressENTERtomovethecursortothenextline,typeGO,then
pressENTERthreetimes.

4.

ToviewallthefieldsofalltherecordsintheVENDORStable,enterthefollowingcommand,
thenclicktheExecutebutton:

SELECT*FROMVENDORS

5.

ToviewonlytheName,StateandZIPfields,deletethepreviousSELECTstatementand
typeandexecutethefollowingstatement:

SELECTName,State,ZIP

FROMVENDORS

83641v1.00CCILearningSolutionsInc.

You can also click


the drop-down arrow
in the Available
Databases box in the
SQL Editor toolbar
to specify which
database to use.

79


TofiltertheresultsettoshowonlythisinformationforvendorsinNYstate,addthefollowingWHEREclausetothe
SELECTstatement:

WHEREState='NY'

7.

ToviewvendorswhosecompanynamebeginswiththeletterG,changetheWHEREclausetothefollowing:

WHERENameLIKE'G%'

8.

Tolistthedistinctstateswherethevendorsreside,replacetheSELECTstatementwiththefollowing:

SELECTDISTINCTState

FROMVENDORS

9.

ToselectallthefieldsoftherecordsforwhichtheZIPcodebeginswiththenumber8orhigher,replacetheSELECT
statementwiththefollowing:

SELECT*

FROMVENDORS

WHEREZIP>'8'

On
ly

6.

10. SelecttherecordswithZIPcodeshigherthan98000orlowerthan86000.
11. UsetheNOTkeywordtolistalltherecordsexcepttheoneinCA.
12. DisplaytherecordsinascendingorderbyZIPcode.

io
n

13. Displaytherecordsthatincludetheword"Way"inthestreetaddress.
14. DisplaytherecordsforvendorsinNY,CAorOR.

15. ClosetheQuerywindowwithoutsavingthechanges,thenminimizetheSQLServerwindow.

lu
at

CaseScenario32:NowWhereDidIPutthatRecord?
YourIlluminateddatabaseshouldnowcontaindatainallitstablesandyoucannowretrievespecific
records.
WriteandtestSELECTstatementsthatwillaccomplishthefollowing:
1.

ListbookTitle,PublisherIDandMSRPindescendingorderbyMSRP.

2.

ListtheFirstNameandLastNameofallauthorswhosefirstnamebeginswiththeletterS.
ListbookTitleandMSRPforbooksthatcostmorethan$30.00andlessthan$50.00.
Listallbooksthathavethelettersingsomewhereinthetitle.

5.

ListallpublishersthatresideinastatewheretheZIPcodeislowerthan45000.

6.

Listallbookspublishedafter01/01/2011.

rE

va

3.
4.

UpdatingData
The SQL UPDATE command is used to update existing table rows with new data values. An UPDATE statement can
updateonlyonetable;however,youcanusea singlestatementtoupdatemultiplecolumns.Initssimplestform,the
syntaxfortheUPDATEcommandis:

Fo

Objective

3.3

UPDATEtable_name
SETcolumn1=value,column2=value,
WHEREcondition
TheSETclauseoftenmakesuseofmathematicaloperators.ThemathematicaloperatorssupportedbySQLinclude:

+ addition

subtraction

* multiplication

/ division

% modulus
IfaWHEREclauseisnotincluded,allrowsinthetablewillbeupdated.

80

83641v1.00CCILearningSolutionsInc.


Consider the following select statement and result set shown for the INVENTORYITEMS table. The query selects the
Description,PriceandVendorIDfieldsforallitemswheretheVendorID=1.

io
n

On
ly

SELECTDescription,Price,VendorID
FROMINVENTORYITEMS
WHEREVendorID=1

Suppose this vendor has increased the prices for their products by 5% and you need to pass that cost along to your
customers.YoucanusethefollowingUPDATEstatementtoaccomplishthetask.

lu
at

UPDATEINVENTORYITEMS
SETPrice=Price+(Price*0.05)
WHEREVendorID=1

TochecktheresultsofanUPDATEstatement,executeaSELECTstatement.

Fo

rE

va

After the UPDATE statement above is executed, the statement SELECT Description, Price, VendorID FROM
INVENTORYITEMSWHEREVendorID=1returnsthefollowingresultset.

YoucanupdatemultiplecolumnssimultaneouslywiththeUPDATEcommand.Forexample,thefollowingcommandwill
increasethepriceforselectedinventoryitemsby10%andreducetheQuantityInStockby1:

UPDATEINVENTORYITEMS
SETPrice=Price+(Price*0.10),QuantityInStock=QuantityInStock1
WHEREVendorID=2
IfafieldallowsNULLvalues,youcanusetheUPDATEstatementtosetthevalueforthatfieldtoNULL.
BecarefulwiththeUPDATEcommand;itisverypowerful,enablingyoutoupdatehundredsorthousandsofrowswitha
singlecommand.BecertainthatyourSETandWHEREclausesareaccurateandwillproducetheresultsyouanticipate.It
is also highly recommended that you back up your data and test the UPDATE statement on a separate copy of the
databasebeforeyouactuallyexecuteitontherealone.

83641v1.00CCILearningSolutionsInc.

81

UPDATEwithCASE
In SQL, CASE is a unique conditional clause that provides ifthenelse logic for a SELECT or UPDATE command. CASE
provideswhenthenelsefunctionality(asinWHENthisconditionistrue,THENdothis).TherearetwoformsoftheCASE
clause.Theseare:
CASE
WHENtrueorfalseexpressionTHENresult_1
ELSEresult_2
END

On
ly

CASEtheexpression
WHENtheconditionTHENresult_1
ELSEresult_2
END
TheCASEexpressioncanhavemultipleWHENclauses.

TheELSEclausemaybeomitted.

ThevalueoftheCASEexpressionisthevalueofthefirstWHENclausethatistrue.Ifnonearetrue,theresultisthe
ELSE.

IfthereisnoELSEclause,theresultisNULL.

Allexpressionsmustbecompatibledatatypes.

io
n

lu
at

Considerthefollowingdata:

MMM
Application
Scenario32:
StateYourCase

Fo

rE

va

NowconsiderthefollowingUPDATEwithCASEstatementanditsresultset:
UPDATEINVENTORYITEMS
SETPrice=CASE
WHEN(Price<10)THENPrice*1.10
WHEN(PriceBETWEEN10AND25)THENPrice*1.05
ELSEPrice*1.02
END
WHEREVendorID=6

DeletingData

Objective

3.4

82

The DELETE command is used to remove records from a table. When the DELETE command is used, the entire row is
removed. DELETE cannot be used to remove values from individual columns. Once a DELETE statement has been
executedsuccessfullyagainstatable,thedeleteddatacannotberecovered.Forthisreasonitishighlyrecommended
that you back up your data and test the DELETE statement on a separate copy of the database before you actually
executeitontherealone.

83641v1.00CCILearningSolutionsInc.


Toremoveaspecificrecord,usetheprimarykeyforthetableintheWHEREclause.Forexample,thefollowingcommand
wouldremoveCustomer1088fromtheCUSTOMERStable:
DELETEFROMCUSTOMERS
WHERECustomerID=1088
Noticethatyoucannotnamefields,becauseallfieldsforthegivenrecordwillberemoved.

On
ly

You can also remove multiple records with one statement. For example, the following statement would remove all
recordsforcustomerswholiveinArizonafromtheCUSTOMERStable:
DELETEFROMCUSTOMERS
WHEREState='AZ'
Todeleteallthedatafromatable,donotspecifyaWHEREclause.Forexample,followingstatementwouldremoveall
recordsfromtheCUSTOMERStable:
DELETEFROMCUSTOMERS
Thiscommanddeletesalltherecords,butleavesthetablestructureintact.TheTRUNCATEstatementperformsthesame
function.ThesyntaxfortheTRUNCATEcommandis:TRUNCATETABLEtable_name.

io
n

TheSQLDELETEstatementremovesrecordsfromasingletable.Ifyouneedtodeleterecordsfrommultipletables,such
asinasituationwhereyoudeleteaparentkey,acommonsolutionistohandletheissueprogrammatically.However,if
youhavespecifiedtocascadedeletions,thenSQLwilldeleterecordsfrommultipletableswhenyoudeleteaparentkey.
(SeeLesson2,Specifyingactionsforforeignkeyconstraintsforinformationoncascadingdeletions.)

Exercise36:Updatinganddeletingdata
Inthisexercise,youwillupdateanddeletedata.
RestoretheSQLServerwindow.

2.

OpenanewQuerywindow.

lu
at

1.
3.

ExecutethefollowingcodeintheQuerywindow:

UseHomeGrown

GO

4.

Checkthepriceofallitemssuppliedbyvendor1withthefollowingstatement:

SELECT*

FROMVENDORS

WHEREVendorID=1

5.

Increasethepriceby5%forallitemssuppliedbyvendor1,byexecutingthefollowingcodeintheQuerywindow:

UPDATEINVENTORYITEMS

SETPrice=Price+(Price*0.05)

WHEREVendorID=1

rE

va

ExecuteaSELECTstatementtoviewtheitemsagainnowthattheupdateshavebeencompleted.

ExecuteaSELECTstatementtoviewthepricesofallinventoryitemsindescendingorder.

8.

ExecuteaDELETEstatementtodeletetheoneitemthatcostsmorethan$200USD.

9.

Execute a SELECT statement to view the prices of all inventory items in descending order to view the remaining
items.

Fo

6.
7.

10. ClosetheQuerywindowwithoutsavinganychanges.

11. LogoffSQLServerandclosethewindow.

83641v1.00CCILearningSolutionsInc.

83

LessonSummary
Youarenowableto:
UnderstandthepurposeandfunctionofDataManipulationLanguage(DML).

PerformdataentrytasksusingtheSSMSGUI.

Createadatabasediagram.

InsertdatausingtheINSERTstatement.

InsertdatausingINSERTscripts.

SelectdatausingtheSELECTstatement.

UpdatedatausingtheUPDATEstatement.

DeletedatausingtheDELETEstatement.

On
ly

ReviewQuestions

WhichofthefollowingSQLstatementswouldyouusetochangethedatainarecord?
a. SELECT.
b. UPDATE.
c. INSERT.
d. DELETE.

2.

IntheSSMSGUI,whichtoolcanyouusetoviewandchecktherelationshipsbetweentablesinadatabase?
a. ThePropertieswindow.
b. TheObjectExplorer.
c. ADatabaseDiagram.
d. AnINSERTfile.

3.

WhencanyouskipfieldswheninsertingvalueswithanINSERTstatement?
a. WhenyouspecifycolumnsfortheINSERTstatement.
b. WhenthefieldsacceptNULLvalues.
c. Whenthefieldsaretextfields.
d. Whenthefieldshaveadefaultvalueassigned.

4.

WhenyouincludecolumnnamesinanINSERTstatementandyoudonotlistacolumn,whathappenstothatcolumnwhen
arecordisinserted?
a. Thatcolumnisdroppedfromthetable.
b. Thatcolumnreceivesa0ifitisanumericcolumn.
c. Thatcolumnreceivesthesamevalueasthecolumnthatprecedesitinthetablestructure.
d. ThatcolumnreceivesitsdefaultvalueoraNULLvalueifthecolumncanacceptnulls.

Fo

rE

va

lu
at

io
n

1.

5.

84

WhenyouincludecolumnnamesinanINSERTstatementhowdoyouhandlecolumnsthatautoincrement?
a. Nametheninthestatement,butdonotsupplyanyvalueforthem.
b. SkipautoincrementcolumnswhennamingcolumnsintheINSERTstatement.
c. Inserta1intothesecolumns,andSQLwillincrementthemaccordingly.
d. Inserta0intothesecolumns,andSQLwillincrementthemaccordingly.

83641v1.00CCILearningSolutionsInc.


WhatisanINSERTscript?
a. AnINSERTscriptisaspecialpieceofprogrammingcodethatincludescharactersyoucannotenterintotheQuery
window.
b. AnINSERTscriptisabuiltinSQLobjectthatyoumustinitializebeforeyoucanaddrecordstoatable.
c. AnINSERTscriptisatextfilethatincludesaseriesofINSERTstatements.
d. AnINSERTscriptisabuiltinSQLobjectthatyoumustdeactivatewhenyouwanttoaddrecordstoatable.

7.

WhichofthefollowingistrueofINSERTscripts?
a. TheymustbewritteninPERL.
b. TheymustberunoutsidetheSQLServerGUI.
c. Theycanalwaysbeexecutedinanyorder.
d. Theymayneedtobeexecutedinaparticularordertomaintainrelational(referential)integrity.

8.

Therecordsreturnedastheresultofaqueryarecalleda(n):
a. resultset.
b. queryset.
c. selection.
d. datasheet.

9.

Toensurethataqueryreturnsonlyuniquevalues,youcanusethe:
a. UNIQUEONLYclause.
b. SETUNIQUEONphrase.
c. DISTINCTkeyword.
d. NOTLIKEoperator.

io
n

On
ly

6.

Fo

rE

va

lu
at

10. Whichofthefollowingcanyouusetoselectdatathatmatchesalistofvalues?
a. TheBETWEENoperator.
b. TheINoperator.
c. TheLIKEoperator.
d. TheTruthtable.

83641v1.00CCILearningSolutionsInc.

85

Fo

rE

va

lu
at

io
n

On
ly

86

83641v1.00CCILearningSolutionsInc.

io
n

lu
at

va

rE

Fo

On
ly

IT Starts Here.

Microsoft Technology Associate


Preparing Tomorrows Technology Workforce
Technology plays a role in virtually every business around the world. Possessing the fundamental
knowledge of how technology works and understanding its impact on todays academic and workplace
environment is increasingly importantparticularly for students interested in exploring professions involving
technology. Thats why Microsoft and Certiport are pleased to offer you the Microsoft Technology Associate (MTA)
certificationMicrosofts new entry-level credential that validates fundamental technology knowledge
among students seeking to build a career in technology.

va

lu
at

io
n

On
ly

The Microsoft Technology Associate (MTA) certification is the ideal and preferred path to Microsofts
world-renowned advanced technology certification programs, such as Microsoft Certified Technology
Specialist (MCTS) and Microsoft Certified IT Professional (MCITP). MTA is sure to become the premier
credential for individuals seeking to explore and pursue a career in technology, or augment related pursuits
such as business or any other field where technology is pervasive.

rE

Why Get Certified?

Fo

MTA validates students understanding of the key IT building blocks essential for intermediate study, while
more advanced certifications such as Microsoft Certified Technology Specialist (MCTS) and Microsoft
Certified IT Professional (MCITP) validate skills and experience with Microsoft products and IT solutions
developed using Microsoft technologies. Microsoft Certifications recognize and reward your abilities and
expertise as your career develops.
Whether you are new to technology, changing jobs, or a seasoned IT professional, becoming certified
demonstrates to customers, peers, and employers that you are committed to advancing your skills and
taking on greater challenges. In addition, certification provides you with access to exclusive Microsoft
Certified IT Professional (MCITP) resources and benefits, including opportunities to connect with a vast, global
network of MCPs.

www.ccilearning.com

You might also like