•
•
TableofContents
Index
SamsTeachYourselfSQLin10Minutes,
ThirdEdition
ByBenForta
Publisher :SamsPublishing
PubDate :March31,2004
ISBN :0-672-32567-5
Pages :256
Slots :0.5
SamsTeachYourselfSQLin10Minuteshas
establisheditselfasthegoldstandardfor
introductorySQLbooks,offeringafast-paced
accessibletutorialtothemajorthemesand
techniquesinvolvedinapplyingtheSQL
language.Forta'sexamplesareclearandhis
writingstyleiscrispandconcise.Aswith
earliereditions,thisrevisionincludes
coverageofcurrentversionsofallmajor
commercialSQLplatforms.Newthistime
aroundiscoverageofMySQL,and
PostgreSQL.Allexampleshavebeentested
againsteachSQLplatform,with
incompatibilitiesorplatformdistinctives
calledoutandexplained.
•
•
TableofContents
Index
SamsTeachYourselfSQLin10Minutes,
ThirdEdition
ByBenForta
Publisher :SamsPublishing
PubDate :March31,2004
ISBN :0-672-32567-5
Pages :256
Slots :0.5
Copyright
AbouttheAuthor
Acknowledgments
WeWanttoHearfromYou!
Introduction
WhoistheTeachYourselfSQLBookFor?
DBMSsCoveredinThisBook
ConventionsUsedinThisBook
Chapter1.UnderstandingSQL
DatabaseBasics
WhatIsSQL?
TryItYourself
Summary
Chapter2.RetrievingData
TheSELECTStatement
RetrievingIndividualColumns
RetrievingMultipleColumns
RetrievingAllColumns
Summary
Chapter3.SortingRetrievedData
SortingData
SortingbyMultipleColumns
SortingbyColumnPosition
Summary
SpecifyingSortDirection
Chapter4.FilteringData
UsingtheWHEREClause
TheWHEREClauseOperators
Summary
Chapter5.AdvancedDataFiltering
CombiningWHEREClauses
UsingtheINOperator
UsingtheNOTOperator
Summary
Chapter6.UsingWildcardFiltering
UsingtheLIKEOperator
TipsforUsingWildcards
Summary
Chapter7.CreatingCalculatedFields
UnderstandingCalculatedFields
ConcatenatingFields
PerformingMathematicalCalculations
Summary
Chapter8.UsingDataManipulationFunctions
UnderstandingFunctions
UsingFunctions
Summary
Chapter9.SummarizingData
UsingAggregateFunctions
AggregatesonDistinctValues
CombiningAggregateFunctions
Summary
Chapter10.GroupingData
UnderstandingDataGrouping
CreatingGroups
FilteringGroups
GroupingandSorting
SELECTClauseOrdering
Summary
Chapter11.WorkingwithSubqueries
UnderstandingSubqueries
FilteringbySubquery
UsingSubqueriesAsCalculatedFields
Summary
Chapter12.JoiningTables
UnderstandingJoins
CreatingaJoin
Summary
Chapter13.CreatingAdvancedJoins
UsingTableAliases
UsingDifferentJoinTypes
UsingJoinswithAggregateFunctions
Summary
UsingJoinsandJoinConditions
Chapter14.CombiningQueries
UnderstandingCombinedQueries
CreatingCombinedQueries
Summary
Chapter15.InsertingData
UnderstandingDataInsertion
CopyingfromOneTabletoAnother
Summary
Chapter16.UpdatingandDeletingData
UpdatingData
DeletingData
GuidelinesforUpdatingandDeletingData
Summary
Chapter17.CreatingandManipulatingTables
CreatingTables
UpdatingTables
DeletingTables
Summary
RenamingTables
Chapter18.UsingViews
UnderstandingViews
CreatingViews
Summary
Chapter19.WorkingwithStoredProcedures
UnderstandingStoredProcedures
WhytoUseStoredProcedures
ExecutingStoredProcedures
Summary
CreatingStoredProcedures
Chapter20.ManagingTransactionProcessing
UnderstandingTransactionProcessing
ControllingTransactions
Summary
Chapter21.UsingCursors
UnderstandingCursors
WorkingwithCursors
Summary
Chapter22.UnderstandingAdvancedSQLFeatures
UnderstandingConstraints
UnderstandingIndexes
UnderstandingTriggers
Summary
DatabaseSecurity
AppendixA.SampleTableScripts
UnderstandingtheSampleTables
ObtainingtheSampleTables
AppendixB.WorkinginPopularApplications
UsingAquaDataStudio
UsingDB2
UsingMacromediaColdFusion
UsingMicrosoftASP
UsingMicrosoftQuery
UsingMySQL
UsingPHP
UsingMicrosoftAccess
UsingMicrosoftASP.NET
UsingMicrosoftSQLServer
UsingOracle
UsingPostgreSQL
UsingQueryTool
ConfiguringODBCDataSources
UsingSybase
AppendixC.SQLStatementSyntax
ALTERTABLE
COMMIT
CREATEINDEX
CREATETABLE
DELETE
INSERT
ROLLBACK
UPDATE
CREATEPROCEDURE
CREATEVIEW
DROP
INSERTSELECT
SELECT
AppendixD.UsingSQLDatatypes
StringDatatypes
NumericDatatypes
DateandTimeDatatypes
BinaryDatatypes
AppendixE.SQLReservedWords
Index
Copyright
Copyright©2004bySamsPublishing
Allrightsreserved.Nopartofthisbookshallbereproduced,
storedinaretrievalsystem,ortransmittedbyanymeans,
electronic,mechanical,photocopying,recording,orotherwise,
withoutwrittenpermissionfromthepublisher.Nopatent
liabilityisassumedwithrespecttotheuseoftheinformation
containedherein.Althougheveryprecautionhasbeentakenin
thepreparationofthisbook,thepublisherandauthorassume
noresponsibilityforerrorsoromissions.Norisanyliability
assumedfordamagesresultingfromtheuseoftheinformation
containedherein.
LibraryofCongressCatalogCardNumber:2003093137
PrintedintheUnitedStatesofAmerica
FirstPrinting:April2004
070605044321
Trademarks
Alltermsmentionedinthisbookthatareknowntobe
trademarksorservicemarkshavebeenappropriately
capitalized.SamsPublishingcannotattesttotheaccuracyof
thisinformation.Useofaterminthisbookshouldnotbe
regardedasaffectingthevalidityofanytrademarkorservice
mark.
WarningandDisclaimer
Everyefforthasbeenmadetomakethisbookascompleteand
asaccurateaspossible,butnowarrantyorfitnessisimplied.
Theinformationprovidedisonan"asis"basis.Theauthorand
thepublishershallhaveneitherliabilitynorresponsibilitytoany
personorentitywithrespecttoanylossordamagesarising
fromtheinformationcontainedinthisbook.
BulkSales
SamsPublishingoffersexcellentdiscountsonthisbookwhen
orderedinquantityforbulkpurchasesorspecialsales.For
moreinformation,pleasecontact
U.S.CorporateandGovernmentSales1-800-382-3419
ForsalesoutsideoftheU.S.,pleasecontact
InternationalSales1-317-428-3341
Credits
AssociatePublisher
MichaelStephens
DevelopmentEditor
MarkRenfrow
ManagingEditor
CharlotteClapp
ProjectEditor
DanKnott
Indexer
TomDinse
Proofreader
LeslieJoseph
TechnicalEditor
ChristopherMcGee
PublishingCoordinator
CindyTeeters
InteriorDesigner
GaryAdair
CoverDesigner
GaryAdair
AbouttheAuthor
BenFortaisMacromedia'sSeniorTechnicalEvangelistandhas
almost20yearsofexperienceinthecomputerindustryin
productdevelopment,support,training,andproductmarketing.
Benistheauthorofthebest-sellingColdFusionWebApplication
ConstructionKitandAdvancedColdFusionDevelopment(both
publishedbyQue),SamsTeachYourselfRegularExpressionsin
10Minutes(inthissameseries),andalsobooksonFlash,Java,
WAP,Windows2000,andothersubjects.Hehasextensive
experienceindatabasedesignanddevelopment,has
implementeddatabasesforseveralhighlysuccessful
commercialsoftwareprograms,andisafrequentlecturerand
columnistonInternetanddatabasetechnologies.Bornin
London,England,andeducatedinLondon,NewYork,andLos
Angeles,BennowlivesinOakPark,Michigan,withhiswife
Marcyandtheirsevenchildren.Benwelcomesyouremailat
,andinvitesyoutovisithisWebsiteat
.
Acknowledgments
ThankstotheteamatSamsforalltheseyearsofsupport,
dedication,andencouragement.AspecialthankyoutoMike
StephensandMarkRenfrowforshepherdingthisnewedition
fromconcepttoreality(aprocessthatrequiredthemto
occasionallyshepherdme,too).
Thankstothemanyhundredsofyouwhoprovidedfeedbackon
thefirsttwoeditionsofthisbook.Fortunately,mostofitwas
positive,andallofitwasappreciated.Theenhancementsand
changesinthiseditionareadirectresponsetoyourfeedback.
Andfinally,thankstothemanythousandsofyouwhobought
thepreviouseditionsofthisbook(inEnglish,andinanyofthe
manytranslations),makingitnotjustmybest-sellingtitle,but
alsooneofthebest-sellingbooksonthesubject.Your
continuedsupportisthehighestcomplimentanauthorcanever
bepaid.
WeWanttoHearfromYou!
Asthereaderofthisbook,youareourmostimportantcritic
andcommentator.Wevalueyouropinionandwanttoknow
whatwe'redoingright,whatwecoulddobetter,whatareas
you'dliketoseeuspublishin,andanyotherwordsofwisdom
you'rewillingtopassourway.
AsanassociatepublisherforSamsPublishing,Iwelcomeyour
comments.Youcanemailorwritemedirectlytoletmeknow
whatyoudidordidn'tlikeaboutthisbookaswellaswhatwe
candotomakeourbooksbetter.
PleasenotethatIcannothelpyouwithtechnicalproblems
relatedtothetopicofthisbook.WedohaveaUserServices
group,however,whereIwillforwardspecifictechnical
questionsrelatedtothebook.
Whenyouwrite,pleasebesuretoincludethisbook'stitleand
authoraswellasyourname,emailaddress,andphonenumber.
Iwillcarefullyreviewyourcommentsandsharethemwiththe
authorandeditorswhoworkedonthebook.
Email:
Mail:
MichaelStephens
AssociatePublisher
SamsPublishing
800East96thStreet
Indianapolis,IN46240USA
FormoreinformationaboutthisbookoranotherSams
Publishingtitle,visitourWebsiteatwww.samspublishing.com.
TypetheISBN(0672325675)orthetitleofthisbookinthe
Searchfieldtofindthepageyou'relookingfor.
Introduction
SQListhemostwidelyuseddatabaselanguage.Whetheryou
areanapplicationdeveloper,databaseadministrator,Web
applicationdesigner,orMicrosoftOfficeuser,agoodworking
knowledgeofSQLisanimportantpartofinteractingwith
databases.
Thisbookwasbornoutofnecessity.IhadbeenteachingWeb
applicationdevelopmentforseveralyears,andstudentswere
constantlyaskingforSQLbookrecommendations.Thereare
lotsofSQLbooksoutthere.Someareactuallyverygood.But
theyallhaveonethingincommon:formostuserstheyteach
justtoomuchinformation.InsteadofteachingSQLitselfmost
booksteacheverythingfromdatabasedesignandnormalization
torelationaldatabasetheoryandadministrativeconcerns.And
whilethoseareallimportanttopics,theyarenotofinterestto
mostofuswhojustneedtolearnSQL.
Andso,notfindingasinglebookthatIfeltcomfortable
recommending,Iturnedthatclassroomexperienceintothe
bookyouareholding.SamsTeachYourselfSQLin10Minutes
willteachyouSQLyouneedtoknow,startingwithsimpledata
retrievalandworkingontomorecomplextopicsincludingthe
useofjoins,subqueries,storedprocedures,cursors,triggers,
andtableconstraints.You'lllearnmethodically,systematically,
andsimplyinlessonsthatwilleachtake10minutesorlessto
complete.
Nowinitsthirdedition,thisbookhastaughtSQLtohundreds
ofthousandsofusers,andnowitisyourturn.Soturnto
Lesson1,andgettowork.You'llbewritingworldclassSQLin
notimeatall.
WhoistheTeachYourselfSQLBookFor?
Thisbookisforyouif
YouarenewtoSQL.
YouwanttoquicklylearnhowtogetthemostoutofSQL.
YouwanttolearnhowtouseSQLinyourownapplication
development.
YouwanttobeproductivequicklyandeasilyinSQLwithout
havingtocallsomeoneforhelp.
DBMSsCoveredinThisBook
Forthemostpart,theSQLtaughtinthisbookwillapplytoany
DatabaseManagementSystem(DBMS).However,asallSQL
implementationsarenotcreatedequal,thefollowingDBMSsare
explicitlycovered(andspecificinstructionsornotesare
includedwhereneeded):
IBMDB2
MicrosoftAccess
MicrosoftSQLServer
MySQL
Oracle
PostgreSQL
SybaseAdaptiveServer
ExampledatabasesandSQLscriptsarealsoavailableforallof
theseDBMSs.
ConventionsUsedinThisBook
Thisbookusesdifferenttypefacestodifferentiatebetweencode
andregularEnglish,andalsotohelpyouidentifyimportant
concepts.
Textthatyoutypeandtextthatshouldappearonyourscreen
ispresentedinmonospacetype.
Itwilllooklikethistomimicthewaytextlooksonyourscre
Placeholdersforvariablesandexpressionsappearinmonospace
italicfont.Youshouldreplacetheplaceholderwiththe
specificvalueitrepresents.
Thisarrow( )atthebeginningofalineofcodemeansthata
singlelineofcodeistoolongtofitontheprintedpage.
Continuetypingallthecharactersafterthe asthoughthey
werepartoftheprecedingline.
ANotepresentsinterestingpiecesofinformationrelatedtothe
surroundingdiscussion.
ATipoffersadviceorteachesaneasierwaytodosomething.
ACautionadvisesyouaboutpotentialproblemsandhelpsyousteer
clearofdisaster.
NewTermiconsprovidecleardefinitionsofnew,essentialterms.
TheInputiconidentifiescodethatyoucantypein
yourself.
TheOutputiconhighlightstheoutputproducedby
runningaprogram.
TheAnalysisiconalertsyoutotheauthor'slineby-lineanalysisofaprogram.
Lesson1.UnderstandingSQL
Inthislesson,you'lllearnexactlywhatSQLisandwhatitwill
doforyou.
DatabaseBasics
ThefactthatyouarereadingabookonSQLindicatesthatyou,
somehow,needtointeractwithdatabases.SQLisalanguage
usedtodojustthis,sobeforelookingatSQLitself,itis
importantthatyouunderstandsomebasicconceptsabout
databasesanddatabasetechnologies.
Whetheryouareawareofitornot,youusedatabasesallthe
time.Eachtimeyouselectanamefromyouremailaddress
book,youareusingadatabase.Ifyouconductasearchonan
Internetsearchsite,youareusingadatabase.Whenyoulog
intoyournetworkatwork,youarevalidatingyournameand
passwordagainstadatabase.EvenwhenyouuseyourATM
cardatacashmachine,youareusingdatabasesforPIN
numberverificationandbalancechecking.
Buteventhoughweallusedatabasesallthetime,there
remainsmuchconfusionoverwhatexactlyadatabaseis.Thisis
especiallytruebecausedifferentpeopleusethesamedatabase
termstomeandifferentthings.Therefore,agoodplacetostart
ourstudyiswithalistandexplanationofthemostimportant
databaseterms.
ReviewingBasicConceptsWhatfollowsisaverybriefoverviewof
somebasicdatabaseconcepts.Itisintendedtoeitherjoltyourmemory
ifyoualreadyhavesomedatabaseexperience,ortoprovideyouwith
theabsolutebasics,ifyouarenewtodatabases.Understanding
databasesisanimportantpartofmasteringSQL,andyoumightwantto
findagoodbookondatabasefundamentalstobrushuponthesubjectif
needed.
WhatIsaDatabase?
Thetermdatabaseisusedinmanydifferentways,butforour
purposes(andindeed,fromSQL'sperspective)adatabaseisa
collectionofdatastoredinsomeorganizedfashion.The
simplestwaytothinkofitistoimagineadatabaseasafiling
cabinet.Thefilingcabinetissimplyaphysicallocationtostore
data,regardlessofwhatthatdataisorhowitisorganized.
DatabaseAcontainer(usuallyafileorsetoffiles)tostoreorganized
data.
MisuseCausesConfusionPeopleoftenusethetermdatabasetorefer
tothedatabasesoftwaretheyarerunning.Thisisincorrect,anditisa
sourceofmuchconfusion.Databasesoftwareisactuallycalledthe
DatabaseManagementSystem(orDBMS).Thedatabaseisthe
containercreatedandmanipulatedviatheDBMS.Adatabasemightbea
filestoredonaharddrive,butitmightnot.Andforthemostpartthisis
notevensignificantasyouneveraccessadatabasedirectlyanyway;
youalwaysusetheDBMSanditaccessesthedatabaseforyou.
Tables
Whenyoustoreinformationinyourfilingcabinetyoudon'tjust
tossitinadrawer.Rather,youcreatefileswithinthefiling
cabinet,andthenyoufilerelateddatainspecificfiles.
Inthedatabaseworld,thatfileiscalledatable.Atableisa
structuredfilethatcanstoredataofaspecifictype.Atable
mightcontainalistofcustomers,aproductcatalog,orany
otherlistofinformation.
TableAstructuredlistofdataofaspecifictype.
Thekeyhereisthatthedatastoredinthetableisonetypeof
dataoronelist.Youwouldneverstorealistofcustomersanda
listofordersinthesamedatabasetable.Doingsowouldmake
subsequentretrievalandaccessdifficult.Rather,you'dcreate
twotables,oneforeachlist.
Everytableinadatabasehasanamethatidentifiesit.That
nameisalwaysuniquemeaningnoothertableinthatdatabase
canhavethesamename.
TableNamesWhatmakesatablenameuniqueisactuallya
combinationofseveralthingsincludingthedatabasenameandtable
name.Somedatabasesalsousethenameofthedatabaseowneras
partoftheuniquename.Thismeansthatwhileyoucannotusethe
sametablenametwiceinthesamedatabase,youdefinitelycanreuse
tablenamesindifferentdatabases.
Tableshavecharacteristicsandpropertiesthatdefinehowdata
isstoredinthem.Theseincludeinformationaboutwhatdata
maybestored,howitisbrokenup,howindividualpiecesof
informationarenamed,andmuchmore.Thissetofinformation
thatdescribesatableisknownasaschema,andschemaare
usedtodescribespecifictableswithinadatabase,aswellas
entiredatabases(andtherelationshipbetweentablesinthem,
ifany).
SchemaInformationaboutdatabaseandtablelayoutandproperties.
ColumnsandDatatypes
Tablesaremadeupofcolumns.Acolumncontainsaparticular
pieceofinformationwithinatable.
ColumnAsinglefieldinatable.Alltablesaremadeupofoneormore
columns.
Thebestwaytounderstandthisistoenvisiondatabasetables
asgrids,somewhatlikespreadsheets.Eachcolumninthegrid
containsaparticularpieceofinformation.Inacustomertable,
forexample,onecolumncontainsthecustomernumber,
anothercontainsthecustomername,andtheaddress,city,
state,andzipareallstoredintheirowncolumns.
BreakingUpDataItisextremelyimportanttobreakdataintomultiple
columnscorrectly.Forexample,city,state,andzipshouldalwaysbe
separatecolumns.Bybreakingtheseout,itbecomespossibletosortor
filterdatabyspecificcolumns(forexample,tofindallcustomersina
particularstateorinaparticularcity).Ifcityandstatearecombined
intoonecolumn,itwouldbeextremelydifficulttosortorfilterbystate.
Eachcolumninadatabasehasanassociateddatatype.A
datatypedefineswhattypeofdatathecolumncancontain.For
example,ifthecolumnistocontainanumber(perhapsthe
numberofitemsinanorder),thedatatypewouldbeanumeric
datatype.Ifthecolumnweretocontaindates,text,notes,
currencyamounts,andsoon,theappropriatedatatypewould
beusedtospecifythis.
DatatypeAtypeofalloweddata.Everytablecolumnhasanassociated
datatypethatrestricts(orallows)specificdatainthatcolumn.
Datatypesrestrictthetypeofdatathatcanbestoredina
column(forexample,preventingtheentryofalphabetical
charactersintoanumericfield).Datatypesalsohelpsortdata
correctly,andplayanimportantroleinoptimizingdiskusage.
Assuch,specialattentionmustbegiventopickingtheright
datatypewhentablesarecreated.
DatatypeCompatibilityDatatypesandtheirnamesareoneofthe
primarysourcesofSQLincompatibility.Whilemostbasicdatatypesare
supportedconsistently,manymoreadvanceddatatypesarenot.And
worse,occasionallyyou'llfindthatthesamedatatypeisreferredtoby
differentnamesindifferentDBMSs.Thereisnotmuchyoucandoabout
this,butitisimportanttokeepinmindwhenyoucreatetableschemas.
Rows
Datainatableisstoredinrows;eachrecordsavedisstoredin
itsownrow.Again,envisioningatableasaspreadsheetstyle
grid,theverticalcolumnsinthegridarethetablecolumns,and
thehorizontalrowsarethetablerows.
Forexample,acustomerstablemightstoreonecustomerper
row.Thenumberofrowsinthetableisthenumberofrecords
init.
RowArecordinatable.
RecordsorRows?Youmayhearusersrefertodatabaserecordswhen
referringtorows.Forthemostpart,thetwotermsareused
interchangeably,butrowistechnicallythecorrectterm.
PrimaryKeys
Everyrowinatableshouldhavesomecolumn(orsetof
columns)thatuniquelyidentifiesit.Atablecontaining
customersmightuseacustomernumbercolumnforthis
purpose,whereasatablecontainingordersmightusetheorder
ID.AnemployeelisttablemightuseanemployeeIDorthe
employeesocialsecuritynumbercolumn.