TheProgrammer'sGuidetoSQL
ISBN:1590592182
byChristianDarieandKarli
Watson
Apress©2003(400pages)
ThebookcoversthelatestversionoftheSQL
standard,SQL-99,andincludestwocomplete
casestudies,showinghowtocreateandquery
theunderlyingdatabaseforafullyfeatured
website,andhowtoimplementrole-based
securityinyourapplications.
TableofContents
TheProgrammer'sGuidetoSQL
Introduction
UnderstandingSQLandRelational
Chapter1 Databases
Chapter2 - RetrievingDatawithSQL
Chapter3 - ModifyingData
Chapter4 - SummarizingandGroupingData
PerformingCalculationsandusing
Chapter5 Functions
Chapter6 - CombiningSQLQueries
Chapter7 - QueryingMultipleTables
Chapter8 - HidingComplexSQLwithViews
Chapter9 - UsingStoredProcedures
Chapter10 - Transactions
Chapter11 - UsersandSecurity
Chapter12 - WorkingwithDatabaseObjects
Chapter13 - Triggers
Chapter14 - CaseStudy:BuildingaProductCatalog
CaseStudy:ImplementingRole-Based
Chapter15 Security
AppendixA - ExecutingSQLStatements
SettinguptheInstantUniversity
AppendixB Database
AppendixC - DataTypes
Index
ListofFigures
ListofTables
ListofExamples
ListofSidebars
BackCover
DoyouspeakSQL?Wedo,andinthisbookweprovide
youwithanin-depthyetconcisetutorialonusing
StructuredQueryLanguage(SQL),thestandardthat
defineshowtocreateandmanipulatedatabasesand
thedatatheystore.SQLisasimpleyetpowerful
language,andyou’llbeamazedathowmanythings
youcandowithjustafewlinesofcode.
Weteachyouallthebasicconceptsandprovide
practicalexamplesrelevanttoyourdailyprogramming
tasks.Onceyou’vemasteredthefundamentals,this
bookwillserveyouwellasahandyreferenceonSQL
usage.ItcoversallthemajorSQLstatementsyou’re
likelytoneedwhenprogrammingdatabasesand
providesexamplecodeforfivemajordatabase
systems:SQLServer,Oracle,DB2,MySQL,andAccess.
Ineachcase,wedemonstratehowthedatabase
systemvendorimplements,andoftenextends,the
SQLstandard.
Wefinishoffwithtwocomplete,real-worldcase
studiesthatpulltogethermanyoftheconcepts
presentedthroughoutthebook.Weshowhowto
createandquerytheunderlyingdatabaseforanecommerceapplication,aswellashowtoimplement
role-basedsecurityinyourapplications.
Whetheryou’rejuststartingoutwithSQL,working
withanunfamiliardatabase,orinneedofadesktop
reference,thisbookwillprovideyouwiththehelpand
informationyouneedtobuildeffectivedatabase
applications.
AbouttheAuthors
ChristianDarieisanindependentITconsultant
specializinginMicrosofttechnologies.Havingworked
withcomputerssincehewasachild,hewonhisfirst
prizeattheageof12inthefirstprogrammingcontest
heeverentered.Hewasactivelyinvolvedwiththe
formerWroxPressasatechnicalreviewerandauthor,
havingcontributedtheOOPpartsofVisualC#.NET:
ASP.NETE-CommercewithVisualBasic.NETand
VisualStudio.NET.HehasauthoredMCADpreparation
materialandvariousSkillDrilltests,suchasC#
programming,MicrosoftCOM+,andDB2Development.
KarliWatsonisafreelanceauthorandITspecialistwith
apenchantformulticoloredclothing.Hestartedout
withtheintentionofbecomingaworld-famous
nanotechnologist,soperhapsonedayyoumight
recognizehisnameashereceivesaNobelPrize.For
now,though,Karli’scomputinginterestsincludeall
thingsmobileandeverything.NET.Karliisalsoa
snowboardingenthusiastandwisheshehadacat.
TheProgrammer'sGuidetoSQL
CRISTIANDARIE,
KARLIWATSON
WITHCHRISHART,
KEVINHOFFMAN,
JULIANSKINNER
Copyright©2003byCristianDarie,KarliWatsonwithChrisHart,Kevin
Hoffman,JulianSkinner
Allrightsreserved.Nopartofthisworkmaybereproducedortransmitted
inanyformorbyanymeans,electronicormechanical,including
photocopying,recording,orbyanyinformationstorageorretrieval
system,withoutthepriorwrittenpermissionofthecopyrightownerand
thepublisher.
ISBN(pbk):1-59059-218-2
PrintedandboundintheUnitedStatesofAmerica10987654321
Trademarkednamesmayappearinthisbook.Ratherthanusea
trademarksymbolwitheveryoccurrenceofatrademarkedname,weuse
thenamesonlyinaneditorialfashionandtothebenefitofthetrademark
owner,withnointentionofinfringementofthetrademark.
TechnicalReviewers:CristofFalk,SlavomirFurman,BradMaiani,
JudithM.Myerson,JohanNormén,DavidSchultz
EditorialBoard:DanAppleman,CraigBerry,GaryCornell,Steven
Rycroft,JulianSkinner,MartinStreicher,JimSumser,KarenWatterson,
GavinWray,JohnZukowski
LeadEditor:TonyDavis
AssistantPublisher:GraceWong
ProjectManager:DarrenMurphy
CopyEditor:KimWimpsett
ProductionManager:KariBrooks
ProductionEditor:KellyWinquist
Proofreader:ThistleHillPublishingServices
Compositor:KineticPublishingServices,LLC
Indexer:JohnCollin
Artist:KineticPublishingServices,LLC
CoverDesigner:KurtKrames
ManufacturingManager:TomDebolski
DistributedtothebooktradeintheUnitedStatesbySpringer-VerlagNew
York,Inc.,175FifthAvenue,NewYork,NY,10010andoutsidetheUnited
StatesbySpringer-VerlagGmbH&Co.KG,Tiergartenstr.17,69112
Heidelberg,Germany.
IntheUnitedStates:phone1-800-SPRINGER,email
<>,orvisit.OutsidetheUnitedStates:fax+496221345229,email
<>,orvisit.
Forinformationontranslations,pleasecontactApressdirectlyat2560
NinthStreet,Suite219,Berkeley,CA94710.Phone510-549-5930,fax
510-549-5939,email<>,orvisit
.
Theinformationinthisbookisdistributedonan"asis"basis,without
warranty.Althougheveryprecautionhasbeentakeninthepreparationof
thiswork,neithertheauthor(s)norApressshallhaveanyliabilitytoany
personorentitywithrespecttoanylossordamagecausedorallegedto
becauseddirectlyorindirectlybytheinformationcontainedinthiswork.
Thesourcecodeforthisbookisavailabletoreadersat
intheDownloadssection.
AbouttheAuthors
CRISTIANDARIEisanindependentITconsultantspecializingin
Microsofttechnologies.Havingworkedwithcomputerssincehewasa
child,hewonhisfirstprizeattheageof12inthefirstprogramming
contestheeverentered.HewasactivelyinvolvedwiththeformerWrox
Pressasatechnicalreviewerandauthor,havingcontributedtheOOP
partsofVisualC#.NET:AGuideforVB6Developersandcoauthored
BeginningASP.NETE-CommercewithVisualBasic.NETandVisual
Studio.NET.HehasauthoredMCADpreparationmaterialandvarious
SkillDrilltests,suchasC#Programming,MicrosoftCOM+,andDB2
Development,whichcanbetakenat.
CristianisatPolitehnicaUniversityofBucharest,studyingautomatic
controlandindustrialinformatics.Hecanbecontactedthrough
.
MybigthanksgotoDave,Julian,andChrisforbeingsuchgreatpeople
toworkwith.
KARLIWATSONisafreelanceauthorandITspecialistwithapenchant
formulticoloredclothing.Hestartedoutwiththeintentionofbecominga
world-famousnanotechnologist,soperhapsonedayyoumightrecognize
hisnameashereceivesaNobelPrize.Fornow,though,Karli's
computinginterestsincludeallthingsmobileandeverything.NET.Karliis
alsoasnowboardingenthusiastandwisheshehadacat.
JULIANSKINNERstudiedGermanicetymologybeforejoiningtheformer
WroxPress.Hehasconsequentlyspentmostofthelastfour-and-a-half
yearsreading,editing,andwritingbooksaboutprogramming,focusingon
Microsofttechnologiesand,inparticular,onC#andthe.NETFramework.
Hecontributedmanysectionsandcodesamples,andoftenentire
chapters,forthebooksheworkedonatWrox,mostlyhidingbehindthe
relativeanonymityofan"additionalmaterial"credit,butheiscreditedas
acoauthorof,amongothertitles,ProfessionalADO.NET.
CHRISHARTisadeveloperandauthorbasedinBirmingham(inthe
UnitedKingdom,notAlabama).Chrisspentmostofthelastfouryearsas
amemberofthetechnicaleditorialteamattheformerWroxPressand
hasbeenprogrammingonavarietyofsystemssincetheageof10.She
spendsmostofhertimeworkingwithMicrosofttechnologiesandhas
beenheavilyinvolvedwith.NETsinceitwasfirstreleasedasanearly
alphapreview.She'scurrentlyworkingforBusinessPostandis
developing.NETCompactFramework/SQLCEapplicationsand2D
barcodescanningcomponentsinDelphi.
KEVINHOFFMANstartedprogrammingattheageof10whenhis
grandfathergavehimaCommodoreVIC-20thatherefurbished,andhe's
beenaddictedtoprogrammingeversince.Hehasworkedoneverything
fromwritinginterfacesforscientificinstrumentstobuildinge-commerce
Websitestoprovidingsecond-tiertechnicalsupportforUnix.Hegothold
of.NETwhenitwasfirsthandedoutinearlypre-betaformandhasbeen
codingwithiteversince.He'scurrentlyemployedinHouston,Texas,
wherehecreatesenterpriseapplicationswiththe.NETFrameworkfora
financialservicescompany.
Introduction
Structuredquerylanguage(SQL)isthelanguageofthedatabase.It'sa
standardthatdefineshowtomanipulatealmosteveryaspectof
database,fromcreatingthedatabaseandtablesthemselvestocreating,
reading,inserting,updating,anddeletingdatainthedatabase.This
standardisthenimplementedandextendeddifferentlybyeachdatabase
systemvendor.
ThecurrentversionoftheSQLstandardisSQL-99.Mostmajordatabase
platformsnowadherefairlycloselytothisstandardwithacoupleof
exceptions.MicrosoftAccess,forexample,hasonlyrecently(with
AccessXP)adoptedtheSQL-92standard.PreviouseditionsofAccess
supportedonlySQL-89.
Inthisbook,we'llwalkthroughallthemajorSQLstatementsyou'relikely
toneedwhenprogrammingdatabases.We'llhighlightdifferences
betweenthestandardandimplementationsusedinfivemajordatabase
systems:
SQLServer
Oracle
DB2
MySQL
Access
WhoisthisBookFor?
ThisbookisdesignedtomeettheneedsofboththenoviceSQL
programmerwhoneedsabitofsyntacticalhelpandthedeveloperusing
SQLdaytodaywhoneedsahandydesktopSQLreference.Youdon't
needtohavedonemuchdatabaseprogrammingbefore,butsome
experiencewithdatabaseswillbeuseful.Youshouldalsohaveoneof
thefivedatabasesystemsmentionedearliertogainthemostbenefits
fromthisbook.
WhatDoesthisBookCover?
Thisbookcoversthefollowingtopics:
Chapter1,"UnderstandingSQLandRelationalDatabases":
Introducesandclarifieskeyconceptsyou'llusethroughoutthe
book.Thischapteralsolooksatrelationaldatabasedesign
theory.
Chapter2,"RetrievingDatawithSQL":Discussestheuseof
simpleSELECTstatementstoretrievedatafromatable.
Chapter3,"ModifyingData":Coversmodifyingdatainatable
usingINSERTandUPDATEstatements.
Chapter4,"SummarizingandGroupingData":Showshowto
usesomebuilt-infunctionsforcountingrowsandaveraging
columnsandthenmovesontolookattheGROUPBYand
HAVINGstatements.Thischapteralsohighlightsdifferences
betweenplatformswhenitcomestodisplayingselectedrows.
Chapter5,"PerformingCalculationsandUsingFunctions":
Describesmanymoreavailablefunctionsthatcanbeusedfor
performingcalculations,manipulatingstrings,workingwithdates
andtimes,andsoon.Italsocoverscreatingyourownfunctions.
Chapter6,"CombiningSQLQueries":Talksaboutsubqueries
andhowtorefinequeriesbycombiningdatafromdifferent
queries.
Chapter7,"QueryingMultipleTables":Introducesjoins
betweentablesandusingthebuilt-inrelationshipsdefinedinthe
databasetopresentthecorrectresultswhenbuildingupaquery.
Chapter8,"HidingComplexSQLwithViews":Discusses
creatingviewsforstoringqueries.Italsodiscusseshowyoucan
useviewstograntrestrictedaccesstodatatouserswithout
havingtoworryaboutthemharmingtheunderlyingdata.
Chapter9,"UsingStoredProcedures":Showshowtocreate
andworkwithstoredproceduresoneachofthesupporting
databaseplatforms.Italsoshowshowtouseconditional
execution,loops,andcursors,andhowtohandleerrors.
Chapter10,"Transactions":Coversthetopicoftransactions
andhowthey'reimplementedondifferentplatformstohandle
updatestoadatabase.Thischapteralsocoversdifferentlocking
methodsthatcanbeappliedtodatawhileatransactionis
processed.
Chapter11,"UsersandSecurity":Discussesthekeyconcepts
ofuserauthenticationandauthorization,focusingontheuseof
rolesandpermissionstorestrictorenablecertaindatabase
functionality.
Chapter12,"WorkingwithDatabaseObjects":Discusseshow
tocreate(anddelete)databases,tables,temporarytables,
sequences,andindexesandhowtoapplyconstraintstocolumns
inatable.
Chapter13,"Triggers":Discusseshowtocreateanduse
triggerstoreacttoeventsindatabases;forexample,theinsertion
ofaroworthedeletionofatable.
Chapter14,"CaseStudy:BuildingaProductCatalog":
Drawingonmuchoftheknowledgegainedthroughouttherestof
thebook,thiscasestudydemonstrateshowtocreateandquery
theunderlyingdatabaseforareale-commerceapplication
Chapter15,"CaseStudy:ImplementingRole-Based
Security":ExamineshowtouseSQLandstoredproceduresto
implementarole-basedsecuritysystem.
Alsointhisbookarethreeappendixesthatcoverthefollowing:
AppendixA,"ExecutingSQLStatements":Providesan
overviewofhowtogetupandrunningsothatyou'rereadyto
startexecutingSQLstatementsagainsteachofthedatabase
platforms.
AppendixB,"SettingUptheInstantUniversityDatabase":
DescribeshowtocreateandpopulatetheInstantUniversity
sampledatabasethat'susedthroughouttheexamplesinthis
book.
AppendixC,"DataTypes":Liststhedifferentdatatypes
availabletoSQLprogrammersoneachofthedifferentdatabase
platforms.
WhatYouNeedtoUsethisBook
Torunthecodeinthisbook,you'llneedtohaveoneofthefollowing
databaseplatformsinstalledonacompatibleoperatingsystem:
SQLServer
Oracle
DB2UDB
MySQL
Access
AlltheSQLcodeinthebookhasbeentestedagainsteachofthese
systems.Specifically,theversionsweusedtotestthecodewereas
follows:
SQLServer2000
Oracle9iR2
DB28.1beta
MySQL4.0gamma
Access2000
CustomerSupportandFeedback
Wealwaysvaluehearingfromourreaders,andwewanttoknowwhat
youthinkaboutthisbook:whatyouliked,whatyoudidn'tlike,andwhat
youthinkwecandobetternexttime.
HowtoTellusExactlyWhatYouThink
Youmightjustwanttotellushowmuchyoulikedorloathedthebookin
question.Oryoumighthaveideasabouthowthiswholeprocesscould
beimproved.Ineithercase,youshoulde-mail
<>.Pleasebesuretomentionthebook'sISBN
andtitleinyourmessage.You'llalwaysfindasympatheticear,nomatter
whattheproblemis.Aboveallyoushouldrememberthatwedocare
aboutwhatyouhavetosay,andwewilldoourutmosttoactuponit.
WhatWeCan'tAnswer
Obviouslywithanever-growingrangeofbooksandanever-changing
technologybase,there'sanincreasingvolumeofdatarequiringsupport.
Althoughweendeavortoanswerallquestionsaboutthebook,wecan't
solvebugsinyourownprogramsthatyou'veadaptedfromourcode.
However,dotellusifyou'reespeciallypleasedwiththeroutineyou
developedwithourhelp.
DownloadingtheSourceCodefortheBook
Thesourcecodeforthisbookisavailabletoreadersat
intheDownloadssection.
FindingSupportandErrataonwww.apress.com
Weunderstandthaterrorscandestroytheenjoymentofabookandcan
causemanywastedandfrustratedhours,soweseektominimizethe
distresstheycancause.Thefollowingsectionswillexplainhowtofind
andposterrataonourWebsitetogetbook-specifichelp.
FindingErrata
Beforeyousendinaquery,youmightbeabletosavetimebyfindingthe
answertoyourproblemonourWebsiteat.
Locatethisbookintheonlinecatalogorwithinthebook'scategoryand
gotothebook'sWebpage.ChecktoseeifthereisaCorrectionslink.If
thereis,clickthelinktoseethepostederrata.
AddinganErratumtotheWebSite
Ifyouwanttopointoutanerratumordirectlyqueryaprobleminthe
book,thenclicktheSubmitErratalinkonthebook'sWebpage.Please
besuretoincludeyournameande-mailandthechapternumber,page
number,andabriefdescriptionoftheproblem,asrequested.
Wewon'tsendyoujunkmail.Weneedthedetailstosaveyourtimeand
ours.
Querieswillbeforwardedtothebook'sauthorsandeditor.Youmay
receiveadirecte-mailreply,and/ortheerratumwillbepostedtotheWeb
sitesoallreaderscanbenefit.
ParticipatinginPeer-to-PeerForums
Forauthorandpeerdiscussion,jointheApressdiscussiongroups.Ifyou
postaquerytoourforums,youcanbeconfidentthatmanyApress
authors,editors,andindustryexpertsareexaminingit.At
forums.apress.comyou'llfindanumberofdifferentliststhatwillhelp
you,notonlywhileyoureadthisbookbutalsoasyoudevelopyourown
applications.TosignupfortheApressforums,goto
forums.apress.comandselecttheNewUserlink.
Chapter1:UnderstandingSQLandRelational
Databases
Attheheartofalmosteverylarge-scaleapplication,whetheritbeaWeb
applicationoracorporateintranet,isthedatabase.Themodern
databasehasmovedonalongwayfromtheflat-fileaddress-cardstyleof
databasestorage,andyounowhavetheabilitytostoreterabytesof
informationaboutcustomers,products,contacts,andsoon.It'sallvery
wellstoringallofthisdatainacentraldatabase,butsimplystoringdata
doesn'tgiveyoumuchinreturnifyoucan'tfindsomewaytoorganize,
access,andworkwiththisdata.StructuredQueryLanguage(SQL)isa
standardizedlanguagedesignedtoaccessandmanipulatedatastoredin
relationaldatabasesandtoworkwiththedatabasesthemselves.
ThischapterexplainswhatSQLisandhowitworks.You'llalsobe
lookingatsomerelationaldatabasetheorybecausetobeabletowork
confidentlywithSQL,youneedtounderstandsomeofthesecore
concepts.
WhatisSQL?
SQLisalanguagethat'susedforaccessingandmanipulatingdatabases
and,moreimportantlyfortheprogrammer,thedatathat'scontainedin
databases.SQLstatementsgiveyouthepowertomanipulateallaspects
ofyourdatabaseusingcodeinsteadofvisualtools.
Note SQLispronouncedeither"ess-kue-ell"or"see-kwell"
dependingonyourpreference.Wegoforthelatter,sono
complaintsaboutuswriting"aSQLstatement"ratherthan"an
SQLstatement,"please!
Inessence,whatyouhaveisa"frontend"thatsendsaSQLstatement
(orasetofSQLstatements)toa"back-end"datastore.Fora
programmer,thisSQLstatementwillmostcommonlycontaincoded
instructionstoperformoneormoreofthefollowingoperations:
Extractingspecificdatafromthedatabase
Insertingnewdataintothedatabase
Modifyingexistingdata
Deletingdata
Manycommercialvendorssupplyrelationaldatabases,including
Microsoft(SQLServerandAccess),OracleCorporation(Oracle),and
IBM(DB2).Therearealsoseveralfreelyavailableopen-sourceproducts
suchasMySQLandPostgresSQL.Nomatterwhatplatformyou'reusing,
severalfeaturesarecommontoallrelationaldatabases,whateverthey
contain.Alldatainthesedatabasesisheldinrows(alsoknownas
records)thatspanthecolumns(fields)ofatablewithinthedatabase,and
thevaluesforeachcolumnareofaspecifieddatatype.Becausethe
dataisstoredinasimilarstructureondifferentplatforms,youcanuse
similartechniquestoaccessandmanipulatethedata.Furthermore,each
oftheseplatformsusesSQLastheuniversallanguagetoimplement
thesetechniques.Inotherwords,SQListhelanguagethatevery
relationaldatabaseunderstands.
Whataboutyour"frontend"?Well,youhaveavarietyofoptionshere,
too.Forexample,yourfrontendmightbeoneofthefollowing:
AWebpagethatallowsacustomertoenterinformationintoa
Searchbox.Basedonthedataentered,aSQLstatementwillbe
constructed,senttotheback-enddatastore,andexecuted,and
thespecificdatathatthecustomerrequestedwillbereturnedand
displayedontheWebpage.
Abusinessapplicationthatallowsemployeestoqueryadata
storeforinformationaboutemployees,productsales,orany
numberofthings.
AsimpleSQLeditingtool,asprovidedbyeveryrelational
databaseproduct,thatallowsyoutoexecuteSQLstatements
againstadatabaseonyourowncomputeroracomputertowhich
you'renetworked.
AndhereyouhavetherealbeautyofSQL:Regardlessofthelanguage
usedtocreatethefrontend—beitASP.NET,Java,VisualBasic,C#,or
virtuallyanyotherlanguage—SQListhelanguagethatallofthesefront
endswillusetocommunicatewitharelationaldatabase.
Inadditiontoallthis,youcanalsouseSQLtoadministertherelational
databaseitself—forexample,tocreateorremovenewdatabasestorage
structuresortoaccessandmodifythesecuritysettingsforthatdatabase.
Thebottomlineisthatregardlessofthelanguageinwhichyouprogram
ortheparticulardatabaseinwhichyoustoreyourdata,knowledgeof
SQLisanessentialskill.
IntroducingtheSQLStandard
SQLhasquitealonghistory.ItwasfirstinventedatIBMin1974–75and
wasusedtocommunicatewithmainframedatabases.Later,in1979,the
firstcommercialrelationaldatabaseproductthatsupportedSQLwas
releasedbyOracle,andin1986–87theANSIandISOstandards
organizationsworkedonaSQLstandardthatwasreleasedtwoyears
later,knownasSQL-89.Thisstandardwasupdatedin1991toanew
version,SQL-92,andsubsequentlytoanotherversion,SQL-99(also
referredtoasSQL:1999andSQL3).Thisbookconcentratesonthis
SQL-99standard.
Thestandarddefinestechniquesforavarietyofoperationsonrelational
databasesandthedatathattheycontain.Essentially,theSQLstandard
splitsdownintothreekeycomponents:
DataManipulationLanguage(DML):Thisisthecomponentof
thelanguagewithwhichthisbookismostconcerned.Itprovides
fourbasicSQLstatements:
SELECTstatementsthatareusedtoreadandextract
datafromthedatabase.Thisportionofthelanguageis
oftengivenasubheadingallitsown,namelyDataQuery
Language(DQL);theseSQLstatementscancorrectlybe
referredtoasSQLqueries.
INSERTstatementsthatareusedtoinsertnewrowsof
dataintothedatabase.
UPDATEstatementsthatareusedtomodifyexistingrows
ofdata.
DELETEstatementsthatareusedtoremoverowsofdata
fromthedatabase.
DataDefinitionLanguage(DDL):Thisisusedtocreate,modify,
orremovetablesandotherdatabaseobjects.Itincludessuch
statementsasCREATETABLE,ALTERTABLE,DROPTABLE,
CREATEINDEX,andsoon.You'llinvestigatethiscomponentof
thelanguageinChapter12,"WorkingwithDatabaseObjects."
DataControlLanguage(DCL):Thisisusedtomanage
databasesecurity,managewhichusershaveaccesstowhich
tablesandwhatdata,andsoon.You'llinvestigatethisinChapter
11,"UsersandSecurity."
ThemajorityofthisbookisdevotedtotheDMLcomponentofSQLand
morespecificallytowritingSQLqueries.
HowSQLWorks
Asitsnamesuggests,alargepartoftheStructuredQueryLanguageis
dedicatedtotheprocessofqueryingarelationaldatabase.Thatis,you
canuseSQLtoaskcertain"questions"ofthedatabaseandhavethe
"answer"(aroworrowsofdata)returned.Forexample,sayyouhavea
databasethatstoresinformationaboutaparticularuniversityandthe
coursesitruns,thepeoplewhoteachthosecourses,andsoon.You
mightaskthequestion"Whichcoursesareofferedbytheuniversity?"A
SQLquerysuchasthefollowingmightdothetrick:
SELECT*FROMCourses
Whatthisqueryisbasicallysayingindatabase-speakis"Givemealistof
alloftheinformationstoredforallofthecoursesintheCoursestable."
Thisquerywouldworkagainstanyrelationaldatabaseaslongasit
containedaCoursestable.Now,theCoursestablemightholda
varietyofdifferentinformation,andperhapsyou'reonlyinterestedinthe
nameofthecoursesoffered.ThenyoumightmodifyyourSQLqueryas
follows:
SELECTCourseNameFROMCourses
Now,thisquerywouldworkagainstanyrelationaldatabaseaslongasit
hadaCoursestablethatcontainedacolumncalledCourseName.
Whatit'ssayingis"Givemeonlythenamesofallthecoursesinthe
Coursestable."Inotherwords,giveyoualltherowsstoredinthe
databasebutonlyreturnthevaluesstoredintheCourseNamecolumn.
Anyotherinformationstoredinthetable,suchasthenumberofcredits
requiredtopasseachcourse(perhapsstoredinaCreditscolumn)
wouldbeignored.Finally,supposeyouwantedtoseedatafromallofthe
columnsintheCoursestablebutonlyforChemistrycourses:
SELECT*FROMCoursesWHERECourseName='Chemistry'
Wewon'tgoanyfurthernow,butwehopeyoucanseethat,insome
circumstances,alineofSQLcanoftenlookmuchthesameasalineof
English.Ofcourse,there'sabitmoretoitthanthat,andcomplex
operationswillrequirefarmorecomplexSQLcode!Likeanylanguage,
youhavealotofsyntaxandusageinformationtolearn,butSQLdoes
haveoneimportantadvantage:Onceyougetusedtoit,thesyntaxis
simpleindeedandcanoftenbeinterpretedevenbypeoplewhohave
neverseenitbefore.
OneimportantpointtotakehomefromthisdiscussionisthatyourSQL
statementsmerelydefinewhichdatayouwanttoretrieve.Youdon't
specifyhowyourdatabaseshouldgoaboutretrievingthem.SQLisa
declarativelanguage,notaprocedurallanguage(suchasJava,Visual
Basic,andsoon).YoujustspecifywhatyouwanttodoinSQLandlet
yourRelationalDatabaseManagementSystem(RDBMS)decidethe
bestwaytoactuallydoit.
IntroducingRelationalDatabaseManagementSystems
Thetermdatabaseisoftenconfusedwith"thesoftwarethatmakesdata
storagepossible."Forexample,you'veprobablyheardSQLServer,
Access,andOraclereferredtoasdatabases.Moreaccurately,they
shouldbereferredtoasRelationalDatabaseManagementSystems
(RDBMSs).They'reapplicationsthatareresponsibleforthestorageof
dataaswellasprovidinganinterfacethatcanbeusedtoaccessthe
database(s)theycontain.Typically,aswellassomekindofuser
interface,RDBMSsincludeanApplicationProgrammingInterface(API)
thatcanbeusedbyotherapplicationstoaccessdata.
EachRDBMSwillbecapableofmaintainingalargenumberofindividual
databases(inotherwords,thedatastorageconstructsandtheactual
data).
OnecrucialpartofRDBMSsisthedatabaseengine.Thispartofan
RDBMSisresponsibleforaccessingdata,asopposedtootherpartsthat
mayrelatetomanipulatingdatabasemanipulationmoreabstractly,
dealingwithuserinput,displayingresults,andsoon.Assuch,whenyou
programmaticallyaccessdatabasesstoredbyRDBMSs,you'rereally