31,ç 4HEç#OMPLETEç2EFERENCE çç 4HIRDç%DITION
This page intentionally left blank
31,ç 4HEç#OMPLETEç2EFERENCE ç 4HIRDç%DITION 0AUL7EINBERG *AMES'ROFF !NDREW/PPEL
.EW9ORK#HICAGO3AN&RANCISCO ,ISBON,ONDON-ADRID-EXICO#ITY -ILAN.EW$ELHI3AN*UAN 3EOUL3INGAPORE3YDNEY4ORONTO
Copyright © 2010 by The McGraw-Hill Companies. All rights reserved. Except as permitted under the United States Copyright Act of 1976, no part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written permission of the publisher. ISBN: 978-0-07-159256-7 MHID: 0-07-159256-3 The material in this eBook also appears in the print version of this title: ISBN: 978-0-07-159255-0, MHID: 0-07-159255-5. All trademarks are trademarks of their respective owners. Rather than put a trademark symbol after every occurrence of a trademarked name, we use names in an editorial fashion only, and to the benefit of the trademark owner, with no intention of infringement of the trademark. Where such designations appear in this book, they have been printed with initial caps. McGraw-Hill eBooks are available at special quantity discounts to use as premiums and sales promotions, or for use in corporate training programs. To contact a representative please e-mail us at
[email protected]. Information has been obtained by McGraw-Hill from sources believed to be reliable. However, because of the possibility of human or mechanical error by our sources, McGraw-Hill, or others, McGraw-Hill does not guarantee the accuracy, adequacy, or completeness of any information and is not responsible for any errors or omissions or the results obtained from the use of such information. TERMS OF USE This is a copyrighted work and The McGraw-Hill Companies, Inc. (“McGraw-Hill”) and its licensors reserve all rights in and to the work. Use of this work is subject to these terms. Except as permitted under the Copyright Act of 1976 and the right to store and retrieve one copy of the work, you may not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works based upon, transmit, distribute, disseminate, sell, publish or sublicense the work or any part of it without McGraw-Hill’s prior consent. You may use the work for your own noncommercial and personal use; any other use of the work is strictly prohibited. Your right to use the work may be terminated if you fail to comply with these terms. THE WORK IS PROVIDED “AS IS.” McGRAW-HILL AND ITS LICENSORS MAKE NO GUARANTEES OR WARRANTIES AS TO THE ACCURACY, ADEQUACY OR COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING THE WORK, INCLUDING ANY INFORMATION THAT CAN BE ACCESSED THROUGH THE WORK VIA HYPERLINK OR OTHERWISE, AND EXPRESSLY DISCLAIM ANY WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. McGraw-Hill and its licensors do not warrant or guarantee that the functions contained in the work will meet your requirements or that its operation will be uninterrupted or error free. Neither McGraw-Hill nor its licensors shall be liable to you or anyone else for any inaccuracy, error or omission, regardless of cause, in the work or for any damages resulting therefrom. McGraw-Hill has no responsibility for the content of any information accessed through the work. Under no circumstances shall McGraw-Hill and/or its licensors be liable for any indirect, incidental, special, punitive, consequential or similar damages that result from the use of or inability to use the work, even if any of them has been advised of the possibility of such damages. This limitation of liability shall apply to any claim or cause whatsoever whether such claim or cause arises in contract, tort or otherwise.
!BOUTõTHEõ!UTHORS *AMES2'ROFFIS#%/OF0"WORKS WHOSEHOSTEDCOLLABORATIONSOFTWAREHELPSTEAMSOFPEOPLE WORKTOGETHERMOREEFFECTIVELYANDEFFICIENTLY%ARLIER 'ROFFWAS#%/OF4IMES4EN THELEADING PROVIDEROFIN MEMORY31,DATABASES(ELED4IMES4ENFROMITSEARLYDAYSTHROUGHEIGHTYEARSOF GROWTHANDASUCCESSFULACQUISITIONBY/RACLEIN WHEREHESERVEDASASENIORVICEPRESIDENT AND/RACLE4IMES4ENBECAME/RACLESFLAGSHIPREAL TIMEDATABASEPRODUCT'ROFFWASTHE COFOUNDER WITH0AUL7EINBERG OF.ETWORK)NNOVATIONS#ORPORATION ADEVELOPEROF31, BASED NETWORKINGSOFTWARE ANDCOAUTHORWITHHIMOF5NDERSTANDING5.)8!#ONCEPTUAL'UIDEASWELL ASTHISBOOK'ROFFHASALSOHELDSENIORDIVISIONMANAGEMENTANDMARKETINGPOSITIONSAT!PPLE #OMPUTERAND(EWLETT 0ACKARD(EHOLDSA"3IN-ATHEMATICSFROMTHE-ASSACHUSETTS)NSTITUTE OF4ECHNOLOGYANDAN-"!FROM(ARVARD5NIVERSITY 0AUL.7EINBERGISASENIORVICEPRESIDENTAT3!0 WHEREHERUNSCORE-$--ASTER$ATA -ANAGEMENT DEVELOPMENT0RIORTOWORKINGAT3!0 7EINBERGWASPRESIDENTOF!I )NC WHICH WASACQUIREDBY3!0INFORITSENTERPRISEWIDEPLATFORMFORPRODUCTCONTENTMANAGEMENTAND CATALOGPUBLISHING7EINBERGWASTHECOFOUNDER WITH*AMES'ROFF OF.ETWORK)NNOVATIONS #ORPORATION APIONEERINCLIENTSERVERDATABASEACCESSTHATWASACQUIREDBY!PPLE#OMPUTERIN ANDCOAUTHORWITHHIMOF5NDERSTANDING5.)8 !#ONCEPTUAL'UIDEASWELLASTHISBOOK(EHASALSOHELDSOFTWAREDEVELOPMENTANDMARKETING POSITIONSAT"ELL,ABORATORIES (EWLETT 0ACKARD AND0LEXUS#OMPUTERS)N HECOLLABORATED ON4HE3IMPLE3OLUTIONTO2UBIKS#UBE THENUMBER ONEBEST SELLINGBOOKOFTHATYEAR WITHOVER MILLIONCOPIESSOLD(EHOLDSA"3FROMTHE5NIVERSITYOF-ICHIGANANDAN-3FROM3TANFORD 5NIVERSITY BOTHIN#OMPUTER3CIENCE !NDREW*!NDY /PPELISLEADDATAMODELERAT"LUE3HIELDOF#ALIFORNIA)NADDITION HEHAS SERVEDASAPART TIMEINSTRUCTORINDATABASETECHNOLOGYWITHTHE5NIVERSITYOF#ALIFORNIAAT "ERKELEY %XTENSIONFORMORETHANYEARS!NDYHASDESIGNEDANDIMPLEMENTEDHUNDREDSOF DATABASESFORAWIDERANGEOFAPPLICATIONS INCLUDINGHEATHCARE BANKING INSURANCE APPAREL MANUFACTURING TELECOMMUNICATIONS WIRELESSCOMMUNICATIONS ANDHUMANRESOURCES(EISTHE AUTHOROF$ATABASES$EMYSTIFIED 31,$EMYSTIFIED AND$ATABASES!"EGINNERS'UIDEANDISCOAUTHOR OF31,!"EGINNERS'UIDE(EHOLDSA"!IN#OMPUTER3CIENCEFROM4RANSYLVANIA5NIVERSITY ,EXINGTON +9
!BOUTõTHEõ4ECHNICALõ%DITOR !ARON$AVENPORTHASBEENWORKINGWITH31, BASED2$"-3TECHNOLOGIESFOROVERTENYEARS(E ISCURRENTLYAPRINCIPALAT,#34ECHNOLOGIES )NC A3ACRAMENTOAND3AN&RANCISCO"AY!REA DATABASECONSULTINGFIRMSPECIALIZINGINPERFORMANCETUNING APPLICATIONDEVELOPMENT AND DATABASEARCHITECTURE0RIORTOJOINING,#3 !ARONHADTENURESAT9AHOO 'AP)NC AND"LUE3HIELD OF#ALIFORNIA
This page intentionally left blank
#ONTENTSçATçAç'LANCE õ
0ARTõ)õ !Nõ/VERVIEWõOFõ31,
)NTRODUCTION
!1UICK4OUROF31,
31,IN0ERSPECTIVE
2ELATIONAL$ATABASES
õ 0ARTõ))õ 2ETRIEVINGõ$ATA
31,"ASICS
3IMPLE1UERIES
-ULTITABLE1UERIES*OINS
3UMMARY1UERIES
3UBQUERIESAND1UERY%XPRESSIONS
õ 0ARTõ)))õ 5PDATINGõ$ATA
$ATABASE5PDATES
$ATA)NTEGRITY
4RANSACTION0ROCESSING
õ 0ARTõ)6õ $ATABASEõ3TRUCTURE
#REATINGA$ATABASE
6IEWS
31,3ECURITY
4HE3YSTEM#ATALOG
VII
VIIIç õ
31,ç4HEç#OMPLETEç2EFERENCE
0ARTõ6õ 0ROGRAMMINGõWITHõ31,
%MBEDDED31,
$YNAMIC31,
31,!0)S
õ 0ARTõ6)õ 31,õ4ODAYõANDõ4OMORROW
$ATABASE0ROCESSINGAND3TORED0ROCEDURAL31,
31,AND$ATA7AREHOUSING
31,AND!PPLICATION3ERVERS
31,.ETWORKINGAND$ISTRIBUTED$ATABASES
31,AND/BJECTS
31,AND8-,
3PECIALTY$ATABASES
4HE&UTUREOF31,
õ 0ARTõ6))õ !PPENDIXES
! 4HE3AMPLE$ATABASE
" $"-36ENDOR0ROlLES
# 31,3YNTAX2EFERENCE
)NDEX
#ONTENTSç
#ONTENTS !CKNOWLEDGMENTS XXIII )NTRODUCTION XXV
õ
0ARTõ)õ !Nõ/VERVIEWõOFõ31,
)NTRODUCTION 4HE31,,ANGUAGE 4HE2OLEOF31, 31,3UCCESS&ACTORS 6ENDOR)NDEPENDENCE 0ORTABILITY!CROSS#OMPUTER3YSTEMS /FlCIAL31,3TANDARDS %ARLY)"-#OMMITMENT -ICROSOFT3UPPORT 2ELATIONAL&OUNDATION (IGH ,EVEL %NGLISH ,IKE3TRUCTURE )NTERACTIVE !D(OC1UERIES 0ROGRAMMATIC$ATABASE!CCESS -ULTIPLE6IEWSOF$ATA #OMPLETE$ATABASE,ANGUAGE $YNAMIC$ATA$ElNITION #LIENT3ERVER!RCHITECTURE %NTERPRISE!PPLICATION3UPPORT %XTENSIBILITYAND/BJECT4ECHNOLOGY )NTERNET$ATABASE!CCESS *AVA)NTEGRATION*$"# /PEN3OURCE3UPPORT )NDUSTRY)NFRASTRUCTURE
!1UICK4OUROF31, !3IMPLE$ATABASE 2ETRIEVING$ATA 3UMMARIZING$ATA !DDING$ATATOTHE$ATABASE $ELETING$ATA 5PDATINGTHE$ATABASE 0ROTECTING$ATA #REATINGA$ATABASE 3UMMARY
IX
IX
Xç
31,ç4HEç#OMPLETEç2EFERENCE
31,IN0ERSPECTIVE 31,ANDTHE%VOLUTIONOF$ATABASE-ANAGEMENT !"RIEF(ISTORYOF31, 4HE%ARLY9EARS %ARLY2ELATIONAL0RODUCTS )"-0RODUCTS #OMMERCIAL!CCEPTANCE 31,3TANDARDS 4HE!.3))3/3TANDARDS /THER%ARLY31,3TANDARDS /$"#ANDTHE31,!CCESS'ROUP *$"#AND!PPLICATION3ERVERS 31,AND0ORTABILITY 31,AND.ETWORKING #ENTRALIZED!RCHITECTURE &ILE3ERVER!RCHITECTURE #LIENT3ERVER!RCHITECTURE -ULTITIER!RCHITECTURE 4HE0ROLIFERATIONOF31, 31,ON-AINFRAMES 31,ON-INICOMPUTERS 31,ON5.)8 "ASED3YSTEMS 31,ON0ERSONAL#OMPUTERS 31,AND4RANSACTION0ROCESSING 31,AND7ORKGROUP$ATABASES 31, $ATA7AREHOUSING AND"USINESS)NTELLIGENCE 31,AND)NTERNET!PPLICATIONS 3UMMARY
2ELATIONAL$ATABASES %ARLY$ATA-ODELS &ILE-ANAGEMENT3YSTEMS (IERARCHICAL$ATABASES .ETWORK$ATABASES 4HE2ELATIONAL$ATA-ODEL 4HE3AMPLE$ATABASE 4ABLES 0RIMARY+EYS 2ELATIONSHIPS &OREIGN+EYS #ODDS2ULESFOR2ELATIONAL$ATABASES 3UMMARY
#ONTENTSç
õ 0ARTõ))õ 2ETRIEVINGõ$ATA
31,"ASICS 3TATEMENTS .AMES 4ABLE.AMES #OLUMN.AMES $ATA4YPES #ONSTANTS .UMERIC#ONSTANTS 3TRING#ONSTANTS $ATEAND4IME#ONSTANTS 3YMBOLIC#ONSTANTS %XPRESSIONS "UILT )N&UNCTIONS -ISSING$ATA.5,,6ALUES 3UMMARY
3IMPLE1UERIES 4HE3%,%#43TATEMENT 4HE3%,%#4#LAUSE 4HE&2/-#LAUSE 1UERY2ESULTS 3IMPLE1UERIES #ALCULATED#OLUMNS 3ELECTING!LL#OLUMNS3%,%#4 $UPLICATE2OWS$)34).#4 2OW3ELECTION7(%2%#LAUSE 3EARCH#ONDITIONS 4HE#OMPARISON4EST 4HE2ANGE4EST"%47%%. 4HE3ET-EMBERSHIP4EST). 4HE0ATTERN-ATCHING4EST,)+% 4HE.ULL6ALUE4EST)3.5,, #OMPOUND3EARCH#ONDITIONS!.$ /2 AND./4 3ORTING1UERY2ESULTS/2$%2"9#LAUSE 2ULESFOR3INGLE 4ABLE1UERY0ROCESSING #OMBINING1UERY2ESULTS5.)/. 5NIONSAND$UPLICATE2OWS 5NIONSAND3ORTING -ULTIPLE5.)/.S 3UMMARY
XI
XIIç
31,ç4HEç#OMPLETEç2EFERENCE
-ULTITABLE1UERIES*OINS !4WO 4ABLE1UERY%XAMPLE 3IMPLE*OINS%QUI *OINS 0ARENT#HILD1UERIES !N!LTERNATIVE7AYTO3PECIFY*OINS *OINSWITH2OW3ELECTION#RITERIA -ULTIPLE-ATCHING#OLUMNS .ATURAL*OINS 1UERIESWITH4HREEOR-ORE4ABLES /THER%QUI *OINS .ON %QUI *OINS 31,#ONSIDERATIONSFOR-ULTITABLE1UERIES 1UALIlED#OLUMN.AMES !LL #OLUMN3ELECTIONS 3ELF *OINS 4ABLE!LIASES -ULTITABLE1UERY0ERFORMANCE 4HE3TRUCTUREOFA*OIN 4ABLE-ULTIPLICATION 2ULESFOR-ULTITABLE1UERY0ROCESSING /UTER*OINS ,EFTAND2IGHT/UTER*OINS /LDER/UTER*OIN.OTATION *OINSANDTHE31,3TANDARD )NNER*OINSIN3TANDARD31, /UTER*OINSIN3TANDARD31, #ROSS*OINSIN3TANDARD31, -ULTITABLE*OINSIN3TANDARD31, 3UMMARY
3UMMARY1UERIES #OLUMN&UNCTIONS #OMPUTINGA#OLUMN4OTAL35- #OMPUTINGA#OLUMN!VERAGE!6' &INDING%XTREME6ALUES-).AND-!8 #OUNTING$ATA6ALUES#/5.4 #OLUMN&UNCTIONSINTHE3ELECT,IST .5,,6ALUESAND#OLUMN&UNCTIONS $UPLICATE2OW%LIMINATION$)34).#4 'ROUPED1UERIES'2/50"9#LAUSE -ULTIPLE'ROUPING#OLUMNS 2ESTRICTIONSON'ROUPED1UERIES .5,,6ALUESIN'ROUPING#OLUMNS
#ONTENTSç
'ROUP3EARCH#ONDITIONS(!6).'#LAUSE 2ESTRICTIONSON'ROUP3EARCH#ONDITIONS .5,,6ALUESAND'ROUP3EARCH#ONDITIONS (!6).'7ITHOUT'2/50"9 3UMMARY
3UBQUERIESAND1UERY%XPRESSIONS 5SING3UBQUERIES 7HAT)SA3UBQUERY 3UBQUERIESINTHE7(%2%#LAUSE /UTER2EFERENCES 3UBQUERY3EARCH#ONDITIONS 4HE3UBQUERY#OMPARISON4EST 4HE3ET-EMBERSHIP4EST). 4HE%XISTENCE4EST%8)343 1UANTIlED4ESTS!.9AND!,, 3UBQUERIESAND*OINS .ESTED3UBQUERIES #ORRELATED3UBQUERIES 3UBQUERIESINTHE(!6).'#LAUSE 3UBQUERY3UMMARY !DVANCED1UERIES 3CALAR 6ALUED%XPRESSIONS 2OW 6ALUED%XPRESSIONS 4ABLE 6ALUED%XPRESSIONS 1UERY%XPRESSIONS 31,1UERIES!&INAL3UMMARY
õ 0ARTõ)))õ 5PDATINGõ$ATA
$ATABASE5PDATES !DDING$ATATOTHE$ATABASE 4HE3INGLE 2OW).3%243TATEMENT 4HE-ULTIROW).3%243TATEMENT "ULK,OAD5TILITIES $ELETING$ATAFROMTHE$ATABASE 4HE$%,%4%3TATEMENT $ELETING!LL2OWS $%,%4%WITH3UBQUERY -ODIFYING$ATAINTHE$ATABASE 4HE50$!4%3TATEMENT 5PDATING!LL2OWS 50$!4%WITH3UBQUERY 3UMMARY
XIII
XIVç
31,ç4HEç#OMPLETEç2EFERENCE
$ATA)NTEGRITY 7HAT)S$ATA)NTEGRITY 2EQUIRED$ATA 3IMPLE6ALIDITY#HECKING #OLUMN#HECK#ONSTRAINTS $OMAINS %NTITY)NTEGRITY /THER5NIQUENESS#ONSTRAINTS 5NIQUENESSAND.5,,6ALUES 2EFERENTIAL)NTEGRITY 2EFERENTIAL)NTEGRITY0ROBLEMS $ELETEAND5PDATE2ULES #ASCADED$ELETESAND5PDATES 2EFERENTIAL#YCLES &OREIGN+EYSAND.5,,6ALUES !DVANCED#ONSTRAINT#APABILITIES !SSERTIONS 31,#ONSTRAINT4YPES $EFERRED#ONSTRAINT#HECKING "USINESS2ULES 7HAT)SA4RIGGER 4RIGGERSAND2EFERENTIAL)NTEGRITY 4RIGGER!DVANTAGESAND$ISADVANTAGES 4RIGGERSANDTHE31,3TANDARD 3UMMARY
4RANSACTION0ROCESSING 7HAT)SA4RANSACTION 4HE!.3))3/31,4RANSACTION-ODEL 4HE34!2442!.3!#4)/.AND3%442!.3!#4)/.3TATEMENTS 4HE3!6%0/).4AND2%,%!3%3!6%0/).43TATEMENTS 4HE#/--)4AND2/,,"!#+3TATEMENTS 4RANSACTIONS"EHINDTHE3CENES 4RANSACTIONSAND-ULTIUSER0ROCESSING 4HE,OST5PDATE0ROBLEM 4HE5NCOMMITTED$ATA0ROBLEM 4HE)NCONSISTENT$ATA0ROBLEM 4HE0HANTOM)NSERT0ROBLEM #ONCURRENT4RANSACTIONS ,OCKING ,OCKING,EVELS 3HAREDAND%XCLUSIVE,OCKS $EADLOCKS !DVANCED,OCKING4ECHNIQUES
#ONTENTSç
6ERSIONING 6ERSIONINGIN/PERATION 6ERSIONING!DVANTAGESAND$ISADVANTAGES 3UMMARY
õ 0ARTõ)6õ $ATABASEõ3TRUCTURE
#REATINGA$ATABASE 4HE$ATA$ElNITION,ANGUAGE #REATINGA$ATABASE 4ABLE$ElNITIONS #REATINGA4ABLE#2%!4%4!",% 2EMOVINGA4ABLE$2/04!",% #HANGINGA4ABLE$ElNITION!,4%24!",% #ONSTRAINT$ElNITIONS !SSERTIONS $OMAINS !LIASESAND3YNONYMS#2%!4%$2/0!,)!3 )NDEXES#2%!4%$2/0).$%8 -ANAGING/THER$ATABASE/BJECTS $ATABASE3TRUCTURE 3INGLE $ATABASE!RCHITECTURE -ULTIDATABASE!RCHITECTURE -ULTILOCATION!RCHITECTURE $ATABASESON-ULTIPLE3ERVERS $ATABASE3TRUCTUREANDTHE!.3))3/3TANDARD #ATALOGS 3CHEMAS 3UMMARY
6IEW 7HAT)SA6IEW (OWTHE$"-3(ANDLES6IEWS !DVANTAGESOF6IEWS $ISADVANTAGESOF6IEWS #REATINGA6IEW#2%!4%6)%7 (ORIZONTAL6IEWS 6ERTICAL6IEWS 2OW#OLUMN3UBSET6IEWS 'ROUPED6IEWS *OINED6IEWS 5PDATINGA6IEW 6IEW5PDATESANDTHE!.3))3/3TANDARD 6IEW5PDATESIN#OMMERCIAL31,0RODUCTS #HECKING6IEW5PDATES#(%#+/04)/.
XV
XVIç
31,ç4HEç#OMPLETEç2EFERENCE
$ROPPINGA6IEW$2/06)%7 -ATERIALIZED6IEWS 3UMMARY
31,3ECURITY 31,3ECURITY#ONCEPTS 5SER )DS 3ECURITY/BJECTS 0RIVILEGES 6IEWSAND31,3ECURITY 'RANTING0RIVILEGES'2!.4 #OLUMN0RIVILEGES 0ASSING0RIVILEGES'2!.4/04)/. 2EVOKING0RIVILEGES2%6/+% 2%6/+%ANDTHE'2!.4/04)/. 2%6/+%ANDTHE!.3))3/3TANDARD 2OLE "ASED3ECURITY 3UMMARY
4HE3YSTEM#ATALOG 7HAT)STHE3YSTEM#ATALOG 4HE#ATALOGAND1UERY4OOLS 4HE#ATALOGANDTHE!.3))3/3TANDARD #ATALOG#ONTENTS 4ABLE)NFORMATION #OLUMN)NFORMATION 6IEW)NFORMATION 2EMARKS 2ELATIONSHIP)NFORMATION 5SER)NFORMATION 0RIVILEGES)NFORMATION 4HE31,)NFORMATION3CHEMA /THER#ATALOG)NFORMATION 3UMMARY
õ
0ARTõ6õ 0ROGRAMMINGõWITHõ31, %MBEDDED31, 0ROGRAMMATIC31,4ECHNIQUES $"-33TATEMENT0ROCESSING %MBEDDED31,#ONCEPTS $EVELOPINGAN%MBEDDED31,0ROGRAM 2UNNINGAN%MBEDDED31,0ROGRAM
#ONTENTSç
3IMPLE%MBEDDED31,3TATEMENTS $ECLARING4ABLES %RROR(ANDLING 5SING(OST6ARIABLES $ATA2ETRIEVALIN%MBEDDED31, 3INGLE 2OW1UERIES -ULTIROW1UERIES #URSOR "ASED$ELETESAND5PDATES #URSORSAND4RANSACTION0ROCESSING 3UMMARY
$YNAMIC31, ,IMITATIONSOF3TATIC31, $YNAMIC31,#ONCEPTS $YNAMIC3TATEMENT%XECUTION%8%#54%)--%$)!4% 4WO 3TEP$YNAMIC%XECUTION 4HE02%0!2%3TATEMENT 4HE%8%#54%3TATEMENT $YNAMIC1UERIES 4HE$%3#2)"%3TATEMENT 4HE$%#,!2%#523/23TATEMENT 4HE$YNAMIC/0%.3TATEMENT 4HE$YNAMIC&%4#(3TATEMENT 4HE$YNAMIC#,/3%3TATEMENT $YNAMIC31,$IALECTS $YNAMIC31,IN/RACLE $YNAMIC31,ANDTHE31,3TANDARD "ASIC$YNAMIC31,3TATEMENTS 4HE3TANDARD31,$! 4HE31,3TANDARDAND$YNAMIC31,1UERIES 3UMMARY
31,!0)S !0)#ONCEPTS 4HEDBLIB!0)31,3ERVER "ASIC31,3ERVER4ECHNIQUES 31,3ERVER1UERIES 0OSITIONED5PDATES $YNAMIC1UERIES /$"#ANDTHE31,#,)3TANDARD 4HE#ALL ,EVEL)NTERFACE3TANDARDIZATION #,)3TRUCTURES #,)3TATEMENT0ROCESSING #,)%RRORSAND$IAGNOSTIC)NFORMATION #,)!TTRIBUTES #,))NFORMATION#ALLS
XVII
XVIIIç
31,ç4HEç#OMPLETEç2EFERENCE
4HE/$"#!0) 4HE3TRUCTUREOF/$"# /$"#AND$"-3)NDEPENDENCE /$"##ATALOG&UNCTIONS %XTENDED/$"##APABILITIES 4HE/RACLE#ALL)NTERFACE/#) /#)(ANDLES /RACLE3ERVER#ONNECTION 3TATEMENT%XECUTION 1UERY2ESULTS0ROCESSING $ESCRIPTOR(ANDLING 4RANSACTION-ANAGEMENT *AVA$ATABASE#ONNECTIVITY*$"# *$"#(ISTORYAND6ERSIONS *$"#)MPLEMENTATIONSAND$RIVER4YPES 4HE*$"#!0) 3UMMARY
õ 0ARTõ6)õ 31,õ4ODAYõANDõ4OMORROW
$ATABASE0ROCESSINGAND3TORED0ROCEDURAL31, 0ROCEDURAL31,#ONCEPTS !"ASIC%XAMPLE 5SING3TORED0ROCEDURES #REATINGA3TORED0ROCEDURE #ALLINGA3TORED0ROCEDURE 3TORED0ROCEDURE6ARIABLES 3TATEMENT"LOCKS &UNCTIONS 2ETURNING6ALUESVIA0ARAMETERS #ONDITIONAL%XECUTION 2EPEATED%XECUTION /THER&LOW OF #ONTROL#ONSTRUCTS #URSOR "ASED2EPETITION (ANDLING%RROR#ONDITIONS !DVANTAGESOF3TORED0ROCEDURES 3TORED0ROCEDURE0ERFORMANCE 3YSTEM $ElNED3TORED0ROCEDURES %XTERNAL3TORED0ROCEDURES 4RIGGERS !DVANTAGESAND$ISADVANTAGESOF4RIGGERS 4RIGGERSIN4RANSACT 31, 4RIGGERSIN)NFORMIX30, 4RIGGERSIN/RACLE0,31, /THER4RIGGER#ONSIDERATIONS
#ONTENTSç
3TORED0ROCEDURES &UNCTIONS 4RIGGERS ANDTHE31,3TANDARD 4HE31,03-3TORED0ROCEDURES3TANDARD 4HE31,03-4RIGGERS3TANDARD 3UMMARY
31,AND$ATA7AREHOUSING $ATA7AREHOUSING#ONCEPTS #OMPONENTSOFA$ATA7AREHOUSE 4HE%VOLUTIONOF$ATA7AREHOUSING $ATABASE!RCHITECTUREFOR7AREHOUSING &ACT#UBES 3TAR3CHEMAS -ULTILEVEL$IMENSIONS 31,%XTENSIONSFOR$ATA7AREHOUSING 7AREHOUSE0ERFORMANCE ,OAD0ERFORMANCE 1UERY0ERFORMANCE 3UMMARY
31,AND!PPLICATION3ERVERS 31,AND7EB3ITES%ARLY)MPLEMENTATIONS !PPLICATION3ERVERSAND4HREE 4IER7EB3ITE!RCHITECTURES $ATABASE!CCESSFROM!PPLICATION3ERVERS %*"4YPES 3ESSION"EAN$ATABASE!CCESS %NTITY"EAN$ATABASE!CCESS %*"%NHANCEMENTS %*"%NHANCEMENTS /PEN3OURCE!PPLICATION$EVELOPMENT !PPLICATION3ERVER#ACHING 3UMMARY
31,.ETWORKINGAND$ISTRIBUTED$ATABASES 4HE#HALLENGEOF$ISTRIBUTED$ATA-ANAGEMENT $ISTRIBUTING$ATA0RACTICAL!PPROACHES 2EMOTE$ATABASE!CCESS 2EMOTE$ATA4RANSPARENCY 4ABLE%XTRACTS 4ABLE2EPLICATION 5PDATEABLE2EPLICAS 2EPLICATION4RADE /FFS 4YPICAL2EPLICATION!RCHITECTURES $ISTRIBUTED$ATABASE!CCESS 2EMOTE2EQUESTS 2EMOTE4RANSACTIONS $ISTRIBUTED4RANSACTIONS $ISTRIBUTED2EQUESTS
XIX
XXç
31,ç4HEç#OMPLETEç2EFERENCE
4HE4WO 0HASE#OMMIT0ROTOCOL .ETWORK!PPLICATIONSAND$ATABASE!RCHITECTURE #LIENT3ERVER!PPLICATIONSAND$ATABASE!RCHITECTURE #LIENT3ERVER!PPLICATIONSWITH3TORED0ROCEDURES %NTERPRISE!PPLICATIONSAND$ATA#ACHING (IGH 6OLUME)NTERNET$ATA-ANAGEMENT 3UMMARY
31,AND/BJECTS /BJECT /RIENTED$ATABASES /BJECT /RIENTED$ATABASE#HARACTERISTICS 0ROSAND#ONSOF/BJECT /RIENTED$ATABASES /BJECTSANDTHE$ATABASE-ARKET /BJECT 2ELATIONAL$ATABASES ,ARGE/BJECT3UPPORT ,/"SINTHE2ELATIONAL-ODEL 3PECIALIZED,/"0ROCESSING !BSTRACT3TRUCTURED $ATA4YPES $ElNING!BSTRACT$ATA4YPES -ANIPULATING!BSTRACT$ATA4YPES )NHERITANCE 4ABLE)NHERITANCE)MPLEMENTING/BJECT#LASSES 3ETS !RRAYS AND#OLLECTIONS $ElNING#OLLECTIONS 1UERYING#OLLECTION$ATA -ANIPULATING#OLLECTION$ATA #OLLECTIONSAND3TORED0ROCEDURES 5SER $ElNED$ATA4YPES -ETHODSAND3TORED0ROCEDURES /BJECT3UPPORTINTHE31,3TANDARD 3UMMARY
31,AND8-, 7HAT)S8-, 8-,"ASICS 8-,FOR$ATA 8-,AND31, %LEMENTSVS!TTRIBUTES 5SING8-,WITH$ATABASES 8-,/UTPUT 8-,)NPUT 8-,$ATA%XCHANGE 8-,3TORAGEAND)NTEGRATION
#ONTENTSç
8-,AND-ETADATA $OCUMENT4YPE$ElNITIONS$4$S 8-,3CHEMA 8-,AND1UERIES 81UERY#ONCEPTS 1UERY0ROCESSINGIN81UERY 8-,$ATABASES 3UMMARY
3PECIALTY$ATABASES 6ERY,OW,ATENCYAND)N -EMORY$ATABASES !NATOMYOFAN)N -EMORY$ATABASE )N -EMORY$ATABASE)MPLEMENTATIONS #ACHINGWITH)N -EMORY$ATABASES #OMPLEX%VENT 0ROCESSINGAND3TREAM$ATABASES #ONTINUOUS1UERIESIN3TREAM$ATABASES 3TREAM$ATABASE)MPLEMENTATIONS 3TREAM$ATABASE#OMPONENTS %MBEDDED$ATABASES %MBEDDED$ATABASE#HARACTERISTICS %MBEDDED$ATABASE)MPLEMENTATIONS -OBILE$ATABASES -OBILE$ATABASE2OLES -OBILE$ATABASE)MPLEMENTATIONS 3UMMARY
4HE&UTUREOF31, $ATABASE-ARKET4RENDS %NTERPRISE$ATABASE-ARKET-ATURITY -ARKET$IVERSITYAND3EGMENTATION 0ACKAGED%NTERPRISE!PPLICATIONS 3OFTWARE AS A 3ERVICE3AA3 (ARDWARE0ERFORMANCE'AINS $ATABASE3ERVER!PPLIANCES 31,3TANDARDIZATION 31,INTHE.EXT$ECADE $ISTRIBUTED$ATABASES -ASSIVE$ATA7AREHOUSINGFOR"USINESS/PTIMIZATION 5LTRAHIGH 0ERFORMANCE$ATABASES )NTERNETAND.ETWORK3ERVICES)NTEGRATION %MBEDDED$ATABASES /BJECT)NTEGRATION #LOUD "ASEDAND(ORIZONTALLY3CALABLE$ATABASES 3UMMARY
XXI
XXIIç
31,ç4HEç#OMPLETEç2EFERENCE
õ 0ARTõ6))õ !PPENDIXES
! 4HE3AMPLE$ATABASE
" $"-36ENDOR0ROlLES
# 31,3YNTAX2EFERENCE $ATA$ElNITION3TATEMENTS !CCESS#ONTROL3TATEMENTS "ASIC$ATA-ANIPULATION3TATEMENTS 4RANSACTION 0ROCESSING3TATEMENTS #URSOR "ASED3TATEMENTS 1UERY%XPRESSIONS 3EARCH#ONDITIONS %XPRESSIONS 3TATEMENT%LEMENTS 3IMPLE%LEMENTS
)NDEX
)NTRODUCTIONç
!CKNOWLEDGMENTS
3
PECIALTHANKSTO!NDY/PPEL OURNEWCOAUTHORFORTHISTHIRDEDITIONOF31,4HE #OMPLETE2EFERENCE(ISIMPRESSIVEHIGH LEVELMASTERYOFTHESUBJECTMATTERCOUPLED WITHHISMETICULOUSATTENTIONTODETAILMADETHISABETTERBOOK ANDWEAREFORTUNATE TOHAVEHADHISINVOLVEMENT *IMAND0AUL
)TSANHONORTOJOINSUCHANACCOMPLISHEDTEAMOFAUTHORSFORTHISEDITIONOF31,4HE #OMPLETE2EFERENCE-YTHANKSFORTHEEXCELLENTSUPPORTOFTHEENTIRE-C'RAW (ILLTEAMFOR THEIRTIRELESSSUPPORTINTHISEFFORT)NPARTICULAR)WISHTOTHANKTECHNICALEDITOR!ARON $AVENPORTANDCOPYEDITOR*AN*UEFORTHEIRPERSISTENCEANDATTENTIONTODETAIL WHICH CONTRIBUTEDSOMUCHTOTHEOVERALLQUALITYOFTHISBOOK !NDY
XXIII
XXIII
This page intentionally left blank
)NTRODUCTION
3
1,4HE#OMPLETE2EFERENCE 4HIRD%DITIONPROVIDESACOMPREHENSIVE IN DEPTH TREATMENTOFTHE31,LANGUAGEFORBOTHTECHNICALANDNONTECHNICALUSERS PROGRAMMERS DATAPROCESSINGPROFESSIONALS ANDMANAGERSWHOWANTTOUNDERSTAND THEIMPACTOF31,INTODAYSCOMPUTERINDUSTRY4HISBOOKOFFERSACONCEPTUALFRAMEWORK FORUNDERSTANDINGANDUSING31, DESCRIBESTHEHISTORYOF31,AND31,STANDARDS AND EXPLAINSTHEROLEOF31,INVARIOUSCOMPUTERINDUSTRYSEGMENTS FROMENTERPRISEDATA PROCESSINGTODATAWAREHOUSINGTOWEBSITEARCHITECTURES4HISNEWEDITIONCONTAINSNEW CHAPTERSSPECIALLYFOCUSEDONTHEROLEOF31,INAPPLICATIONSERVERARCHITECTURES ANDTHE INTEGRATIONOF31,WITH8-,ANDOTHEROBJECT BASEDTECHNOLOGIES 4HISBOOKWILLSHOWYOU STEP BY STEP HOWTOUSE31,FEATURES WITHMANYILLUSTRATIONS ANDREALISTICEXAMPLESTOCLARIFY31,CONCEPTS4HEBOOKALSOCOMPARES31,PRODUCTSFROM LEADING$"-3VENDORSDESCRIBINGTHEIRADVANTAGES BENEFITS ANDTRADE OFFSTOHELP YOUSELECTTHERIGHTPRODUCTFORYOURAPPLICATION-OSTOFTHEEXAMPLESINTHISBOOKARE BASEDONTHESAMPLEDATABASEDESCRIBEDIN!PPENDIX!4HESAMPLEDATABASECONTAINS DATATHATSUPPORTSASIMPLEORDER PROCESSINGAPPLICATIONFORASMALLDISTRIBUTIONCOMPANY !PPENDIX!ALSOCONTAINSINSTRUCTIONSFORDOWNLOADINGTHE31,STATEMENTSREQUIREDTO CREATEANDPOPULATETHESAMPLEDATABASETABLESINA$"-3OFYOUCHOICE SUCHAS/RACLE 31,3ERVER -Y31, AND$"4HISALLOWSYOUTOTRYTHEEXAMPLESINTHEBOOKYOURSELF ANDGAINACTUALEXPERIENCEWRITINGANDRUNNING31,STATEMENTS )NSOMEOFTHECHAPTERS THESUBJECTMATTERISEXPLOREDATTWODIFFERENTLEVELSA FUNDAMENTALDESCRIPTIONOFTHETOPIC ANDANADVANCEDDISCUSSIONINTENDEDFORCOMPUTER PROFESSIONALSWHONEEDTOUNDERSTANDSOMEOFTHEINTERNALSBEHIND31,4HEMORE ADVANCEDINFORMATIONISCOVEREDINSECTIONSMARKEDWITHANASTERISK 9OUDONOTNEED TOREADTHESESECTIONSTOOBTAINANUNDERSTANDINGOFWHAT31,ISANDWHATITDOES
XXV
XXVIç
31,ç4HEç#OMPLETEç2EFERENCE
(OWõ4HISõ"OOKõ)Sõ/RGANIZED 4HEBOOKISDIVIDEDINTOSIXPARTSTHATCOVERVARIOUSASPECTSOFTHE31,LANGUAGE s 0ART) h!N/VERVIEWOF31, vPROVIDESANINTRODUCTIONTO31,ANDAMARKET PERSPECTIVEOFITSROLEASADATABASELANGUAGE)TSFOURCHAPTERSDESCRIBETHEHISTORY OF31, THEEVOLUTIONOF31,STANDARDS ANDHOW31,RELATESTOTHERELATIONALDATA MODELANDTOEARLIERDATABASETECHNOLOGIES0ART)ALSOCONTAINSAQUICKTOUROF31, THATBRIEFLYILLUSTRATESITSMOSTIMPORTANTFEATURESANDPROVIDESYOUWITHAN OVERVIEWOFTHEENTIRELANGUAGEEARLYINTHEBOOK s 0ART)) h2ETRIEVING$ATA vDESCRIBESTHEFEATURESOF31,THATALLOWYOUTOPERFORM DATABASEQUERIES4HEFIRSTCHAPTERINTHISPARTDESCRIBESTHEBASICSTRUCTUREOFTHE 31,LANGUAGE4HENEXTFOURCHAPTERSSTARTWITHTHESIMPLEST31,QUERIESAND PROGRESSIVELYBUILDTOMORECOMPLEXQUERIES INCLUDINGMULTITABLEQUERIES SUMMARYQUERIES ANDQUERIESTHATUSESUBQUERIES s 0ART))) h5PDATING$ATA vSHOWSHOWYOUCANUSE31,TOADDNEWDATATOA DATABASE DELETEDATAFROMADATABASE ANDMODIFYEXISTINGDATABASEDATA)TALSO DESCRIBESTHEDATABASEINTEGRITYISSUESTHATARISEWHENDATAISUPDATED ANDHOW 31,ADDRESSESTHESEISSUES4HELASTOFTHETHREECHAPTERSINTHISPARTDISCUSSESTHE 31,TRANSACTIONCONCEPTAND31,SUPPORTFORMULTIUSERTRANSACTIONPROCESSING s 0ART)6 h$ATABASE3TRUCTURE vDEALSWITHCREATINGANDADMINISTERINGA31, BASED DATABASE)TSFOURCHAPTERSTELLYOUHOWTOCREATETHETABLES VIEWS ANDINDEXESTHAT FORMTHESTRUCTUREOFARELATIONALDATABASE)TALSODESCRIBESTHE31,SECURITYSCHEME THATPREVENTSUNAUTHORIZEDACCESSTODATA ANDTHE31,SYSTEMCATALOGTHAT DESCRIBESTHESTRUCTUREOFADATABASE4HISPARTALSODISCUSSESTHESIGNIFICANT DIFFERENCESBETWEENTHEDATABASESTRUCTURESSUPPORTEDBYVARIOUS31, BASED$"-3 PRODUCTS s 0ART6 h0ROGRAMMINGWITH31, vDESCRIBESHOWAPPLICATIONPROGRAMSUSE31,FOR DATABASEACCESS)TDISCUSSESTHEEMBEDDED31,SPECIFIEDBYTHE!.3)STANDARDAND USEDBY)"- /RACLE )NGRES )NFORMIX ANDMANYOTHER31, BASED$"-3PRODUCTS )TALSODESCRIBESTHEDYNAMIC31,INTERFACETHATISUSEDTOBUILDGENERAL PURPOSE DATABASETABLES SUCHASREPORTWRITERSANDDATABASEBROWSINGPROGRAMS&INALLY THISPARTDESCRIBESTHEPOPULAR31,!0)S INCLUDING/$"# THE)3/ STANDARD#ALL ,EVEL)NTERFACE AND*$"# THESTANDARDCALL LEVELINTERFACEFOR*AVA ASWELLAS PROPRIETARYCALL LEVELINTERFACESSUCHAS/RACLES/#)!0) s 0ART6) h31,4ODAYAND4OMORROW vEXAMINESTHEUSEOF31,INSEVERALOFTODAYS hHOTTESTvAPPLICATIONAREAS ANDTHECURRENTSTATEOF31, BASED$"-3PRODUCTS4WO CHAPTERSDESCRIBETHEUSEOF31,STOREDPROCEDURESANDTRIGGERSFORONLINE TRANSACTIONPROCESSING ANDTHECONTRASTINGUSEOF31,FORDATAWAREHOUSING&OUR ADDITIONALCHAPTERSDESCRIBE31, BASEDDISTRIBUTEDDATABASES THEINFLUENCEOF OBJECTTECHNOLOGIESON31, SPECIALTYDATABASES ANDTHEINTEGRATIONOF31,WITH 8-,TECHNOLOGIES&INALLY THELASTCHAPTEREXPLORESTHEFUTUREOF31,ANDSOMEOF THEMOSTIMPORTANTTRENDSIN31, BASEDDATAMANAGEMENT
)NTRODUCTIONç
#ONVENTIONSõ5SEDõINõ4HISõ"OOK 31,4HE#OMPLETE2EFERENCE 4HIRD%DITIONDESCRIBESTHE31,FEATURESANDFUNCTIONSAVAILABLE INTHEMOSTPOPULAR31, BASED$"-3PRODUCTSANDTHOSEDESCRIBEDINTHE!.3))3/31, STANDARDS7HENEVERPOSSIBLE THE31,STATEMENTSYNTAXDESCRIBEDINTHISBOOKANDUSEDINTHE EXAMPLESAPPLIESTOALLDIALECTSOF31,7HENTHEDIALECTSDIFFER THEDIFFERENCESAREPOINTEDOUT INTHETEXT ANDTHEEXAMPLESFOLLOWTHEMOSTCOMMONPRACTICE)NTHESECASES YOUMAYHAVE TOMODIFYTHE31,STATEMENTSINTHEEXAMPLESSLIGHTLYTOSUITYOURPARTICULARBRANDOF$"-3 4HROUGHOUTTHEBOOK TECHNICALTERMSAPPEARINITALICSTHEFIRSTTIMETHEYAREUSEDAND DEFINED31,LANGUAGEELEMENTS INCLUDING31,KEYWORDS TABLEANDCOLUMNNAMES AND SAMPLE31,STATEMENTS APPEARINAN500%2#!3%-/./30!#%FONT31,!0)FUNCTION NAMESAPPEARINALOWERCASEMONOSPACEFONT0ROGRAMLISTINGSALSOAPPEARIN MONOSPACEFONTANDUSETHENORMALCASECONVENTIONSFORTHEPARTICULARPROGRAMMING LANGUAGEUPPERCASEFOR#/"/,AND&/242!. LOWERCASEFOR#AND*AVA .OTETHAT THESECONVENTIONSAREUSEDSOLELYTOIMPROVEREADABILITYMOST31,IMPLEMENTATIONSWILL ACCEPTEITHERUPPERCASEORLOWERCASESTATEMENTS-ANYOFTHE31,EXAMPLESINCLUDEQUERY RESULTS WHICHAPPEARIMMEDIATELYFOLLOWINGTHE31,STATEMENT ASTHEYWOULDINAN INTERACTIVE31,SESSION)NSOMECASES LONGQUERYRESULTSARETRUNCATEDAFTERAFEWROWS THISISINDICATEDBYAVERTICALELLIPSISx FOLLOWINGTHELASTROWOFQUERYRESULTS
7HYõ4HISõ"OOKõ)SõFORõ9OU 31,4HE#OMPLETE2EFERENCE 4HIRD%DITIONISTHERIGHTBOOKFORANYONEWHOWANTSTO UNDERSTANDANDLEARN31, INCLUDINGDATABASEUSERS DATAPROCESSINGPROFESSIONALSAND ARCHITECTS PROGRAMMERS STUDENTS ANDMANAGERS)TDESCRIBESINSIMPLE UNDERSTANDABLE LANGUAGELIBERALLYILLUSTRATEDWITHFIGURESANDEXAMPLESWHAT31,IS WHYITISIMPORTANT ANDHOWYOUUSEIT4HISBOOKISNOTSPECIFICTOONEPARTICULARBRANDORDIALECTOF31, 2ATHER ITDESCRIBESTHESTANDARD CENTRALCOREOFTHE31,LANGUAGEANDTHENGOESONTO DESCRIBETHEDIFFERENCESAMONGTHEMOSTPOPULAR31,PRODUCTS INCLUDING/RACLE -ICROSOFT 31,3ERVER )"-S$"5NIVERSAL$ATABASEAND)NFORMIX 3YBASE AND-Y31,)TALSO EXPLAINSTHEIMPORTANCEOF31, BASEDSTANDARDS SUCHAS/$"#AND*$"# ANDTHE!.3) )3/STANDARDSFOR31,AND31, RELATEDTECHNOLOGIES4HISTHIRDEDITIONCONTAINSNEW CHAPTERSANDSECTIONSTHATCOVERTHELATEST31,INNOVATIONS INTHEAREASOFOBJECT RELATIONAL TECHNOLOGIES 8-, ANDAPPLICATIONSERVERARCHITECTURES )FYOUARENEWTO31, THISBOOKOFFERSCOMPREHENSIVE STEP BY STEPTREATMENTOFTHE LANGUAGE BUILDINGFROMSIMPLEQUERIESTOMOREADVANCEDCONCEPTS4HESTRUCTUREOFTHE BOOKWILLALLOWYOUTOQUICKLYSTARTUSING31, BUTTHEBOOKWILLCONTINUETOBEVALUABLEAS YOUBEGINTOUSETHEMORECOMPLEXFEATURESOFTHELANGUAGE9OUCANCREATETHESAMPLE DATABASEUSINGAN31,SCRIPTAVAILABLEONTHE-C'RAW (ILLWEBSITESEE!PPENDIX! AND USEITTOTRYOUTTHEEXAMPLESANDBUILDYOUR31,SKILLS )FYOUAREADATAPROCESSINGPROFESSIONAL ARCHITECT ORMANAGER THISBOOKWILLGIVE YOUAPERSPECTIVEONTHEIMPACTTHAT31,ISHAVINGACROSSTHEINFORMATIONTECHNOLOGY INDUSTRYFROMPERSONALCOMPUTERSTOMAINFRAMESTODATAWAREHOUSINGTO)NTERNETWEB SITESAND)NTERNET BASEDDISTRIBUTEDAPPLICATIONS4HEEARLYCHAPTERSDESCRIBETHEHISTORY OF31, ITSROLEINTHEMARKET ANDITSEVOLUTIONFROMEARLIERDATABASETECHNOLOGIES,ATER CHAPTERSDESCRIBETHEFUTUREOF31,ANDTHEDEVELOPMENTOFNEWDATABASETECHNOLOGIES SUCHASDISTRIBUTEDDATABASES OBJECT ORIENTEDEXTENSIONSTO31, BUSINESSINTELLIGENCE DATABASES ANDDATABASE8-,INTEGRATION
XXVII
XXVIIIç
31,ç4HEç#OMPLETEç2EFERENCE
)FYOUAREAPROGRAMMER THISBOOKOFFERSAVERYCOMPLETETREATMENTOFPROGRAMMINGWITH 31,5NLIKETHEREFERENCEMANUALSOFMANY$"-3PRODUCTS ITOFFERSACONCEPTUALFRAMEWORK FOR31,PROGRAMMING EXPLAININGTHEWHYASWELLASTHEHOWOFDEVELOPINGA31, BASED APPLICATION)TCONTRASTSTHE31,PROGRAMMINGINTERFACESOFFEREDBYALLOFTHELEADING31, PRODUCTS INCLUDINGEMBEDDED31, DYNAMIC31, /$"# *$"# ANDPROPRIETARY!0)S SUCHASTHE/RACLE#ALL)NTERFACE4HEDESCRIPTIONANDCOMPARISONOFPROGRAMMINGTECHNIQUES PROVIDESAPERSPECTIVENOTFOUNDINANYOTHERBOOK )FYOUARESELECTINGA$"-3PRODUCT THISBOOKOFFERSACOMPARISONOFTHE31,FEATURES ADVANTAGES ANDBENEFITSOFFEREDBYTHEVARIOUS$"-3VENDORS4HEDIFFERENCESBETWEEN THELEADING$"-3PRODUCTSAREEXPLAINED NOTONLYINTECHNICALTERMS BUTALSOINTERMS OFTHEIRIMPACTONAPPLICATIONSANDTHEIREVOLVINGCOMPETITIVEPOSITIONINTHEMARKETPLACE 4HEhSAMPLEDATABASEvCANBEUSEDTOTRYTHESEFEATURESINAPROTOTYPEOFYOUROWN APPLICATION )NSHORT BOTHTECHNICALANDNONTECHNICALUSERSCANBENEFITFROMTHISBOOK)TISTHEMOST COMPREHENSIVESOURCEOFINFORMATIONAVAILABLEABOUTTHE31,LANGUAGE 31,FEATURESAND BENEFITS POPULAR31, BASEDPRODUCTS THEHISTORYOF31, ANDTHEIMPACTOF31,ONTHE FUTUREDIRECTIONOFTHEINFORMATIONTECHNOLOGYINDUSTRY
*
0!24
!Nç/VERVIEWçOFç31,
4
HEFIRSTFOURCHAPTERSOFTHISBOOKPROVIDEAPERSPECTIVEAND AQUICKINTRODUCTIONTO31,#HAPTERDESCRIBESWHAT31,IS ANDEXPLAINSITSMAJORFEATURESANDBENEFITS)N#HAPTER AQUICKTOUROF31,SHOWSYOUMANYOFITSCAPABILITIESWITHSIMPLE RAPID FIREEXAMPLES#HAPTEROFFERSAMARKETPERSPECTIVEOF31, BYTRACINGITSHISTORY DESCRIBINGTHE31,STANDARDSANDTHEMAJOR VENDORSOF31, BASEDPRODUCTS ANDBYIDENTIFYINGTHEREASONSFOR 31,SPROMINENCETODAY#HAPTERDESCRIBESTHERELATIONALDATA MODELUPONWHICH31,ISBASEDANDCOMPARESITWITHEARLIERDATA MODELS
#(!04%2ç )NTRODUCTION $)"15&3 !1UICK4OUROF31, $)"15&3 31,IN0ERSPECTIVE $)"15&3 2ELATIONAL$ATABASES
This page intentionally left blank
#(!04%2
)NTRODUCTION
4
HE31,LANGUAGEANDRELATIONALDATABASESYSTEMSBASEDONITCONSTITUTEONEOFTHE MOSTIMPORTANTFOUNDATIONTECHNOLOGIESINTHECOMPUTERINDUSTRY/VERTHELASTTHREE DECADES 31,HASGROWNFROMITSFIRSTCOMMERCIALUSEINTOACOMPUTERPRODUCTAND SERVICESMARKETSEGMENTWORTHTENSOFBILLIONSOFDOLLARSPERYEAR AND31,STANDSTODAYAS THESTANDARDCOMPUTERDATABASELANGUAGE(UNDREDSOFDATABASEPRODUCTSNOWSUPPORT 31, RUNNINGONCOMPUTERSYSTEMSFROMMAINFRAMESTOPERSONALCOMPUTERS!31, BASED DATABASEMAYEVENBEEMBEDDEDINYOURMOBILEPHONEOR0$! ORINTHEENTERTAINMENT SYSTEMOFYOURCAR!NOFFICIALINTERNATIONAL31,STANDARDHASBEENADOPTEDANDEXPANDED SEVERALTIMES%VERYMAJORENTERPRISESOFTWAREPRODUCTRELIESON31,FORITSDATAMANAGEMENT AND31,ISATTHECOREOFTHEFLAGSHIPDATABASEPRODUCTSFROM-ICROSOFT /RACLE AND)"- THREEOFTHELARGESTSOFTWARECOMPANIESINTHEWORLD31,ISALSOATTHEHEARTOFOPEN SOURCE DATABASEPRODUCTSSUCHAS-Y31,AND0OSTGRESTHATAREHELPINGTOFUELTHEPOPULARITYOF ,INUXANDTHEOPENSOURCEMOVEMENT&ROMITSOBSCUREBEGINNINGSASAN)"-RESEARCHPROJECT 31,HASGROWNTOBECOMEBOTHANIMPORTANTPIECEOFINFORMATIONTECHNOLOGYANDAPOWERFUL MARKETFORCE 7HAT EXACTLY IS31,7HYISITIMPORTANT7HATCANITDO ANDHOWDOESITWORK)F 31,ISREALLYASTANDARD WHYDOWEHAVESOMANYDIFFERENTVERSIONSANDDIALECTS(OWDO POPULAR31,PRODUCTSLIKE31,3ERVER /RACLE -Y31, 3YBASE AND$"COMPARE(OW DOES31,RELATETO-ICROSOFTSTANDARDSSUCHAS/$"#AND.%4(OWDOES*$"#LINK31, TOTHEWORLDOF*AVAANDOBJECTTECHNOLOGY7HATROLEDOESITPLAYINTHE3ERVICE /RIENTED !RCHITECTURE3/! ANDWEBSERVICESBEINGEMBRACEDBYENTERPRISE)4ORGANIZATIONS$OES 31,REALLYSCALEFROMMAINFRAMESTOHANDHELDDEVICES(ASITREALLYDELIVEREDTHE PERFORMANCENEEDEDFORHIGH VOLUMETRANSACTIONPROCESSING(OWWILL31,IMPACTTHE WAYYOUUSECOMPUTERS ANDHOWCANYOUGETTHEMOSTOUTOFTHISIMPORTANTDATA MANAGEMENTTOOL4HISBOOKANSWERSTHOSEQUESTIONSBYGIVINGYOUACOMPLETEPERSPECTIVE ANDASOLIDWORKINGKNOWLEDGEOF31,
ç
0ARTç)ç
!Nç/VERVIEWçOFç31,
4HEõ31,õ,ANGUAGE 31,ISATOOLFORORGANIZING MANAGING ANDRETRIEVINGDATASTOREDBYACOMPUTERDATABASE 4HEORIGINALNAMEGIVENITBY)"-WAS3TRUCTURED%NGLISH1UERY,ANGUAGE SHORTENEDTOTHE ACRONYM3%15%,7HEN)"-DISCOVEREDTHAT3%15%,WASATRADEMARKOWNEDBYTHE(AWKER 3IDDELEY!IRCRAFT#OMPANYOFTHE5NITED+INGDOM THEYSHORTENEDTHEACRONYMTO31,4HE WORDh%NGLISHvWASTHENDROPPEDFROMTHESPELLED OUTNAMETOMATCHTHENEWACRONYM4O THISDAY YOUWILLHEARTHEACRONYM31,PRONOUNCEDASEITHERAWORDhSEQUELv ORASASTRING OFLETTERSh3 1 ,v ANDWHILETHELATTERISGENERALLYPREFERRED BOTHARECONSIDEREDCORRECT!S THENAMEIMPLIES 31,ISACOMPUTERLANGUAGETHATYOUUSETOINTERACTWITHADATABASE)NFACT 31,WORKSWITHONESPECIFICTYPEOFDATABASE CALLEDARELATIONALDATABASE WHICHHASBECOME THEMAINSTREAMWAYTOORGANIZEDATAACROSSAVERYBROADRANGEOFCOMPUTERAPPLICATIONS &IGURE SHOWSHOW31,WORKS4HECOMPUTERSYSTEMINTHEFIGUREHASADATABASETHAT STORESIMPORTANTINFORMATION)FTHECOMPUTERSYSTEMISINABUSINESS THEDATABASEMIGHT STOREINVENTORY PRODUCTION SALES ORPAYROLLDATA/NAPERSONALCOMPUTER THEDATABASE MIGHTSTOREDATAABOUTTHECHECKSYOUHAVEWRITTEN LISTSOFPEOPLEANDTHEIRPHONENUMBERS ORDATAEXTRACTEDFROMALARGERCOMPUTERSYSTEM4HECOMPUTERPROGRAMTHATCONTROLSTHE DATABASEISCALLEDADATABASEMANAGEMENTSYSTEM$"-3 7HENYOUNEEDTORETRIEVEDATAFROMADATABASE YOUUSETHE31,TOMAKETHEREQUEST 4HE$"-3PROCESSESTHE31,REQUEST RETRIEVESTHEREQUESTEDDATA ANDRETURNSITTOYOU 4HISPROCESSOFREQUESTINGDATAFROMADATABASEANDRECEIVINGTHERESULTSISCALLEDADATABASE QUERYHENCETHENAME3TRUCTURED1UERY,ANGUAGE h3TRUCTURED1UERY,ANGUAGEvISACTUALLYSOMEWHATOFAMISNOMER&IRSTOFALL 31,IS FARMORETHANAQUERYTOOL ALTHOUGHTHATWASITSORIGINALPURPOSE ANDRETRIEVINGDATAISSTILL ONEOFITSMOSTIMPORTANTFUNCTIONS31,ISUSEDTOCONTROLALLOFTHEFUNCTIONSTHATA$"-3 PROVIDESFORITSUSERS INCLUDING
1, Ê££Ê 1Ã}Ê-+ÊvÀÊ`>Ì>L>ÃiÊ>VViÃÃ
#HAPTERçç
)NTRODUCTIONç
s $ATADEFINITION 31,LETSAUSERDEFINETHESTRUCTUREANDORGANIZATIONOFTHESTORED DATAANDRELATIONSHIPSAMONGTHESTOREDDATAITEMS
s $ATAMANIPULATION 31,ALLOWSAUSERORANAPPLICATIONPROGRAMTOUPDATETHE DATABASEBYADDINGNEWDATA REMOVINGOLDDATA ANDMODIFYINGPREVIOUSLY STOREDDATA s !CCESSCONTROL 31,CANBEUSEDTORESTRICTAUSERSABILITYTORETRIEVE ADD AND MODIFYDATA PROTECTINGSTOREDDATAAGAINSTUNAUTHORIZEDACCESS s $ATASHARING 31,ISUSEDTOCOORDINATEDATASHARINGBYCONCURRENTUSERS ENSURING THATCHANGESMADEBYONEUSERDONOTINADVERTENTLYWIPEOUTCHANGESMADEAT NEARLYTHESAMETIMEBYANOTHERUSER s $ATAINTEGRITY 31,DEFINESINTEGRITYCONSTRAINTSINTHEDATABASE PROTECTINGITFROM CORRUPTIONDUETOINCONSISTENTUPDATESORSYSTEMFAILURES 31,ISTHUSACOMPREHENSIVELANGUAGEFORCONTROLLINGANDINTERACTINGWITHADATABASE MANAGEMENTSYSTEM 3ECOND 31,ISNOTREALLYACOMPLETECOMPUTERLANGUAGELIKE#/"/, # # OR*AVA )NSTEAD 31,ISADATABASESUBLANGUAGE CONSISTINGOFABOUTSTATEMENTSSPECIALIZEDFOR DATABASEMANAGEMENTTASKS4HESE31,STATEMENTSCANBEEMBEDDEDINTOANOTHERLANGUAGE SUCHAS#/"/,OR#TOEXTENDTHATLANGUAGEFORUSEINDATABASEACCESS!LTERNATIVELY THESTATEMENTSCANBEEXPLICITLYSENTTOADATABASEMANAGEMENTSYSTEMFORPROCESSING VIAACALL LEVELINTERFACEFROMALANGUAGESUCHAS# # OR*AVA ORVIAMESSAGESSENTOVER ACOMPUTERNETWORK 31,ALSODIFFERSFROMOTHERCOMPUTERLANGUAGESBECAUSEITDESCRIBESWHATTHEUSER WANTSTHECOMPUTERTODORATHERTHANHOWTHECOMPUTERSHOULDDOIT)NMORETECHNICAL TERMS 31,ISADECLARATIVEORDESCRIPTIVELANGUAGERATHERTHANAPROCEDURALONE 31, CONTAINSNO)&STATEMENTFORTESTINGCONDITIONS ANDNO'/4/ $/ OR&/2STATEMENTSFOR PROGRAMFLOWCONTROL2ATHER 31,STATEMENTSDESCRIBEHOWACOLLECTIONOFDATAISTOBE ORGANIZED ORWHATDATAISTOBERETRIEVEDORADDEDTOTHEDATABASE4HESEQUENCEOFSTEPS TODOTHOSETASKSISLEFTFORTHE$"-3TODETERMINE &INALLY 31,ISNOTAPARTICULARLYSTRUCTUREDLANGUAGE ESPECIALLYWHENCOMPAREDWITH HIGHLYSTRUCTUREDLANGUAGESSUCHAS# 0ASCAL OR*AVA)NSTEAD 31,STATEMENTSRESEMBLE %NGLISHSENTENCES COMPLETEWITHhNOISEWORDSvTHATDONTADDTOTHEMEANINGOFTHE STATEMENTBUTMAKEITREADMORENATURALLY4HE31,HASQUITEAFEWINCONSISTENCIESANDALSO SOMESPECIALRULESTOPREVENTYOUFROMCONSTRUCTING31,STATEMENTSTHATLOOKPERFECTLYLEGAL BUTTHATDONTMAKESENSE $ESPITETHEINACCURACYOFITSNAME 31,HASEMERGEDASTHESTANDARDLANGUAGEFORUSING RELATIONALDATABASES31,ISBOTHAPOWERFULLANGUAGEANDONETHATISRELATIVELYEASYTO LEARN4HEQUICKTOUROF31,IN#HAPTERWILLGIVEYOUAGOODOVERVIEWOFTHELANGUAGE ANDITSCAPABILITIES
0!24ç)
s $ATARETRIEVAL 31,ALLOWSAUSERORANAPPLICATIONPROGRAMTORETRIEVESTOREDDATA FROMTHEDATABASEANDUSEIT
ç
0ARTç)ç
!Nç/VERVIEWçOFç31,
4HEõ2OLEõOFõ31, 31,ISNOTITSELFADATABASEMANAGEMENTSYSTEM NORISITASTAND ALONEPRODUCT9OUCANNOT GOTOACOMPUTERRETAILERORAWEBSITESELLINGCOMPUTERSOFTWAREANDBUY31,)NSTEAD 31,ISANINTEGRALPARTOFADATABASEMANAGEMENTSYSTEM ALANGUAGEANDATOOLFOR COMMUNICATINGWITHTHE$"-3&IGURE SHOWSSOMEOFTHECOMPONENTSOFATYPICAL $"-3ANDHOW31,LINKSTHEMTOGETHER 4HEDATABASEENGINEISTHEHEARTOFTHE$"-3 RESPONSIBLEFORACTUALLYSTRUCTURING STORING ANDRETRIEVINGTHEDATAINTHEDATABASE)TACCEPTS31,REQUESTSFROMOTHER$"-3COMPONENTS SUCHASAFORMSFACILITY REPORTWRITER ORINTERACTIVEQUERYFACILITY FROMUSER WRITTEN APPLICATIONPROGRAMS ANDEVENFROMOTHERCOMPUTERSYSTEMS!STHEFIGURESHOWS 31,PLAYS MANYDIFFERENTROLES s 31,ISANINTERACTIVEQUERYLANGUAGE5SERSTYPE31,COMMANDSINTOANINTERACTIVE 31,PROGRAMTORETRIEVEDATAANDDISPLAYITONTHESCREEN PROVIDINGACONVENIENT EASY TO USETOOLFORADHOCDATABASEQUERIES s 31,ISADATABASEPROGRAMMINGLANGUAGE0ROGRAMMERSEMBED31,COMMANDSINTO THEIRAPPLICATIONPROGRAMSTOACCESSTHEDATAINADATABASE"OTHUSER WRITTEN PROGRAMSANDDATABASEUTILITYPROGRAMSSUCHASREPORTWRITERSANDDATAENTRY TOOLS USETHISTECHNIQUEFORDATABASEACCESS
1, Ê£ÓÊ «iÌÃÊvÊ>ÊÌÞ«V>Ê`>Ì>L>ÃiÊ>>}iiÌÊÃÞÃÌi
#HAPTERçç
)NTRODUCTIONç
s 31,ISACLIENTSERVERLANGUAGE0ERSONALCOMPUTERPROGRAMSUSE31,TOCOMMUNICATE OVERANETWORKWITHDATABASESERVERSTHATSTORESHAREDDATA4HISCLIENTSERVER ARCHITECTUREISUSEDBYMANYPOPULARENTERPRISE CLASSAPPLICATIONS s 31,ISAN)NTERNETDATAACCESSLANGUAGE)NTERNETWEBSERVERSTHATINTERACTWITH CORPORATEDATAAND)NTERNETAPPLICATIONSERVERSALLUSE31,ASASTANDARDLANGUAGE FORACCESSINGCORPORATEDATABASES OFTENBYEMBEDDING31,DATABASEACCESSWITHIN POPULARSCRIPTINGLANGUAGESLIKE0(0OR0ERL s 31,ISADISTRIBUTEDDATABASELANGUAGE$ISTRIBUTEDDATABASEMANAGEMENTSYSTEMSUSE 31,TOHELPDISTRIBUTEDATAACROSSMANYCONNECTEDCOMPUTERSYSTEMS4HE$"-3 SOFTWAREONEACHSYSTEMUSES31,TOCOMMUNICATEWITHTHEOTHERSYSTEMS SENDING REQUESTSFORDATAACCESS s 31,ISADATABASEGATEWAYLANGUAGE)NACOMPUTERNETWORKWITHAMIXOFDIFFERENT $"-3PRODUCTS 31,ISOFTENUSEDINAGATEWAYTHATALLOWSONEBRANDOF$"-3TO COMMUNICATEWITHANOTHERBRAND 31,HASTHUSEMERGEDASAUSEFUL POWERFULTOOLFORLINKINGPEOPLE COMPUTERPROGRAMS ANDCOMPUTERSYSTEMSTOTHEDATASTOREDINARELATIONALDATABASE
31,õ3UCCESSõ&ACTORS )NHISTORICALTERMS 31,HASBEENANEXTRAORDINARILYSUCCESSFULINFORMATIONTECHNOLOGY 4HINKABOUTTHECOMPUTERMARKETINTHEMID S WHEN31,FIRSTSTARTEDTOBECOME IMPORTANT-AINFRAMESANDMINICOMPUTERSDOMINATEDCORPORATECOMPUTING4HE)"- PERSONALCOMPUTERHADBEENINTRODUCEDONLYAFEWYEARSBEFORE ANDTHE-3 $/3COMMAND LINEWASITSUSERINTERFACE)"-SMAINFRAMEOPERATINGSYSTEMSANDMINICOMPUTEROPERATING SYSTEMSFROM$IGITAL%QUIPMENT $ATA'ENERAL (EWLETT 0ACKARD ANDOTHERSDOMINATED BUSINESSCOMPUTING0ROPRIETARYNETWORKINGSCHEMESLIKE)"-S3.!OR$IGITAL%QUIPMENTS $%#NETLINKEDCOMPUTERSTOGETHER4HE)NTERNETWASSTILLATOOLFORCOLLABORATIONAMONG RESEARCHLABS ANDTHE7ORLD7IDE7EBHADNOTYETAPPEAREDONTHESCENE#/"/, # AND 0ASCALWEREDOMINANTCOMPUTERLANGUAGESOBJECT ORIENTEDPROGRAMMINGWASONLY BEGINNINGTOEMERGEAND*AVAHADNOTBEENINVENTED !CROSSALLOFTHESEAREASOFCOMPUTERTECHNOLOGYFROMCOMPUTERHARDWARETOOPERATING SYSTEMSTONETWORKINGTOLANGUAGESTHEIMPORTANTKEYTECHNOLOGIESOFTHEMID S HAVEFADEDORBECOMEOBSOLETE REPLACEDBYSIGNIFICANTNEWONES"UTINTHEWORLDOFDATA MANAGEMENT THERELATIONALDATABASEAND31,CONTINUETODOMINATETHELANDSCAPE4HEY HAVEEXPANDEDOVERTHEYEARSTOSUPPORTNEWHARDWARE OPERATINGSYSTEMS NETWORKS AND LANGUAGES BUTDESPITEMANYATTEMPTSTODETHRONETHEM THECORERELATIONALMODELANDTHE 31,HAVETHRIVEDANDREMAINTHEDOMINANTFORCESINDATAMANAGEMENT(EREARESOMEOFTHE MAJORFEATURESANDMARKETFORCESTHATHAVECONTRIBUTEDTOTHISSUCCESSOVERTHEPASTYEARS s 6ENDORINDEPENDENCE s 0ORTABILITYACROSSCOMPUTERSYSTEMS
0!24ç)
s 31,ISADATABASEADMINISTRATIONLANGUAGE4HEDATABASEADMINISTRATORRESPONSIBLEFOR MANAGINGAMINICOMPUTERORMAINFRAMEDATABASEUSES31,TODEFINETHEDATABASE STRUCTUREANDTOCONTROLACCESSTOTHESTOREDDATA
ç
0ARTç)ç
!Nç/VERVIEWçOFç31,
s /FFICIAL31,STANDARDS s %ARLY)"-COMMITMENT s -ICROSOFTSUPPORT s 2ELATIONALFOUNDATION s (IGH LEVEL %NGLISH LIKESTRUCTURE s )NTERACTIVE ADHOCQUERIES s 0ROGRAMMATICDATABASEACCESS s -ULTIPLEVIEWSOFDATA s #OMPLETEDATABASELANGUAGE s $YNAMICDATADEFINITION s #LIENT3ERVERARCHITECTURE s %NTERPRISEAPPLICATIONSUPPORT s %XTENSIBILITYANDOBJECTTECHNOLOGY s )NTERNETDATABASEACCESS s *AVAINTEGRATION*$"# s /PENSOURCESUPPORT s )NDUSTRYINFRASTRUCTURE 4HESECTIONSTHATFOLLOWBRIEFLYDESCRIBEEACHOFTHESEANDHOWTHEYCONTRIBUTEDTO 31,SSUCCESS
6ENDORõ)NDEPENDENCE 31,ISOFFEREDBYALLOFTHELEADING$"-3VENDORS ANDNONEWDATABASEPRODUCTOVERTHE LASTDECADEHASBEENHIGHLYSUCCESSFULWITHOUT31,SUPPORT!31, BASEDDATABASEANDTHE PROGRAMSTHATUSEITCANBEMOVEDFROMONE$"-3TOANOTHERVENDORS$"-3WITH MINIMALCONVERSIONEFFORTANDLITTLERETRAININGOFPERSONNEL$ATABASETOOLSSUCHASQUERY TOOLS REPORTWRITERS ANDAPPLICATIONGENERATORSWORKWITHMANYDIFFERENTBRANDSOF31, DATABASES4HEVENDORINDEPENDENCETHUSPROVIDEDBY31,WASONEOFTHEMOSTIMPORTANT REASONSFORITSEARLYPOPULARITYANDREMAINSANIMPORTANTFEATURETODAY
0ORTABILITYõ!CROSSõ#OMPUTERõ3YSTEMS 31, BASEDDATABASEPRODUCTSRUNONCOMPUTERSYSTEMSRANGINGFROMMAINFRAMESAND MIDRANGESYSTEMSTOPERSONALCOMPUTERS WORKSTATIONS AWIDERANGEOFSPECIALIZEDSERVER COMPUTERS ANDEVENHANDHELDDEVICES4HEYOPERATEONSTAND ALONECOMPUTERSYSTEMS IN DEPARTMENTALLOCALAREANETWORKS ANDINENTERPRISEWIDEOR)NTERNETWIDENETWORKS31, BASEDAPPLICATIONSTHATBEGINONSINGLE USERORDEPARTMENTALSERVERSYSTEMSCANBEMOVED TOLARGERSERVERSYSTEMSASTHEYGROW$ATAFROMCORPORATE31, BASEDDATABASESCANBE EXTRACTEDANDDOWNLOADEDINTODEPARTMENTALORPERSONALDATABASES&INALLY ECONOMICAL PERSONALCOMPUTERSCANBEUSEDTOTESTAPROTOTYPEOFA31, BASEDDATABASEAPPLICATION BEFOREMOVINGITTOANEXPENSIVEMULTIUSERSYSTEM
#HAPTERçç
)NTRODUCTIONç
/FFICIALõ31,õ3TANDARDS
%ARLYõ)"-õ#OMMITMENT 31,WASORIGINALLYINVENTEDBY)"-RESEARCHERSANDFAIRLYQUICKLYBECAMEASTRATEGIC PRODUCTFOR)"-BASEDONITSFLAGSHIP$"DATABASE31,SUPPORTISAVAILABLEONALLMAJOR )"-PRODUCTFAMILIES FROMPERSONALCOMPUTERSTHROUGHMIDRANGESYSTEMSAND5.)8 BASED SERVERSTO)"-MAINFRAMES)"-SINITIALWORKPROVIDEDACLEARSIGNALOF)"-SDIRECTIONFOR OTHERDATABASEANDSYSTEMVENDORSTOFOLLOWEARLYINTHEDEVELOPMENTOF31,ANDRELATIONAL DATABASES,ATER )"-SCOMMITMENTANDBROADSUPPORTSPEEDEDTHEMARKETACCEPTANCEOF 31,)NTHES )"-WASTHEDOMINANTFORCEINBUSINESSCOMPUTING SOITSEARLYAND SUSTAINEDSUPPORTASTHEINVENTORANDCHAMPIONOF31,ENSUREDITSEARLYIMPORTANCE
-ICROSOFTõ3UPPORT -ICROSOFTHASLONGCONSIDEREDDATABASEACCESSAKEYPARTOFITS7INDOWSPERSONALCOMPUTER SOFTWAREARCHITECTURE"OTHDESKTOPANDSERVERVERSIONSOF7INDOWSPROVIDESTANDARDIZED RELATIONALDATABASEACCESSTHROUGH/PEN$ATABASE#ONNECTIVITY/$"# A31, BASED CALL LEVEL!0)APPLICATIONPROGRAMMINGINTERFACE ,EADING7INDOWSSOFTWAREAPPLICATIONS SPREADSHEETS WORDPROCESSORS DATABASES ETC FROM-ICROSOFTANDOTHERVENDORS SUPPORT/$"# ANDALLLEADING31,DATABASESPROVIDE/$"#ACCESS-ICROSOFTHAS ENHANCED/$"#SUPPORTWITHHIGHER LEVEL MOREOBJECT ORIENTEDDATABASEACCESSLAYERS OVERTHEYEARS INCLUDINGDATAMANAGEMENTSUPPORTIN.%4TODAY"UTTHESENEW TECHNOLOGIESCOULDALWAYSINTERACTWITHRELATIONALDATABASESTHROUGHTHE/$"#31, LAYERSBELOW7HEN-ICROSOFTBEGANITSEFFORTINTHELATESTOMAKE7INDOWSAVIABLE SERVEROPERATINGSYSTEM ITINTRODUCED31,3ERVERASITSOWN31, BASEDOFFERING31, 3ERVERCONTINUESTODAYASAFLAGSHIP-ICROSOFTPRODUCTANDASAKEYCOMPONENTOFTHE -ICROSOFT.%4ARCHITECTUREFORWEBSERVICES
2ELATIONALõ&OUNDATION 31,ISALANGUAGEFORRELATIONALDATABASES ANDITHASBECOMEPOPULARALONGWITHTHE RELATIONALDATABASEMODEL4HETABULAR ROWCOLUMNSTRUCTUREOFARELATIONALDATABASE ISINTUITIVETOUSERS KEEPINGTHE31,SIMPLEANDEASYTOUNDERSTAND4HERELATIONAL MODELALSOHASASTRONGTHEORETICALFOUNDATIONTHATHASGUIDEDTHEEVOLUTIONAND IMPLEMENTATIONOFRELATIONALDATABASES2IDINGAWAVEOFACCEPTANCEBROUGHTABOUTBY THESUCCESSOFTHERELATIONALMODEL 31,HASBECOMETHEDATABASELANGUAGEFORRELATIONAL DATABASES
0!24ç)
!NOFFICIALSTANDARDFOR31,WASINITIALLYPUBLISHEDBYTHE!MERICAN.ATIONAL3TANDARDS )NSTITUTE!.3) ANDTHE)NTERNATIONAL3TANDARDS/RGANIZATION)3/ IN ANDWAS EXPANDEDINANDAGAININ AND31,ISALSOA53&EDERAL )NFORMATION0ROCESSING3TANDARD&)03 MAKINGITAKEYREQUIREMENTFORLARGEGOVERNMENT COMPUTERCONTRACTS/VERTHEYEARS OTHERINTERNATIONAL GOVERNMENT ANDVENDORGROUPS HAVEPIONEEREDTHESTANDARDIZATIONOFNEW31,CAPABILITIES SUCHASCALL LEVELINTERFACESOR OBJECT BASEDEXTENSIONS-ANYOFTHESENEWINITIATIVESHAVEBEENINCORPORATEDINTOTHE !.3))3/STANDARDOVERTIME4HEEVOLVINGSTANDARDSSERVEASANOFFICIALSTAMPOF APPROVALFOR31,ANDHAVESPEEDEDITSMARKETACCEPTANCE
ç
0ARTç)ç
!Nç/VERVIEWçOFç31,
(IGH ,EVEL õ%NGLISH ,IKEõ3TRUCTURE 31,STATEMENTSLOOKLIKESIMPLE%NGLISHSENTENCES MAKING31,RELATIVELYEASYTOLEARNAND UNDERSTAND4HISISINPARTBECAUSE31,STATEMENTSDESCRIBETHEDATATOBERETRIEVED RATHER THANSPECIFYINGHOWTOFINDTHEDATA4ABLESANDCOLUMNSINA31,DATABASECANHAVELONG DESCRIPTIVENAMES!SARESULT MOST31,STATEMENTShSAYWHATTHEYMEANvANDCANBEREAD ASCLEAR NATURALSENTENCES
)NTERACTIVE õ!Dõ(OCõ1UERIES 31,ISANINTERACTIVEQUERYLANGUAGETHATGIVESUSERSADHOCACCESSTOSTOREDDATA5SING 31,INTERACTIVELY AUSERCANGETANSWERSEVENTOCOMPLEXQUESTIONSINMINUTESORSECONDS INSHARPCONTRASTTOTHEDAYSORWEEKSITWOULDTAKEFORAPROGRAMMERTOWRITEACUSTOM REPORTPROGRAM"ECAUSEOFTHE31,ADHOCQUERYPOWER DATAISMOREACCESSIBLEANDCANBE USEDTOHELPANORGANIZATIONMAKEBETTER MOREINFORMEDDECISIONS31,SADHOCQUERY CAPABILITYWASANIMPORTANTADVANTAGEOVERNONRELATIONALDATABASESEARLYINITSEVOLUTION ANDMORERECENTLYHASCONTINUEDASAKEYADVANTAGEOVERPUREOBJECT BASEDDATABASES
0ROGRAMMATICõ$ATABASEõ!CCESS 31,ISALSOADATABASELANGUAGEUSEDBYPROGRAMMERSTOWRITEAPPLICATIONSTHATACCESSA DATABASE4HESAME31,STATEMENTSAREUSEDFORBOTHINTERACTIVEANDPROGRAMMATICACCESS SOTHEDATABASEACCESSPARTSOFAPROGRAMCANBETESTEDFIRSTWITHINTERACTIVE31,ANDTHEN EMBEDDEDINTOTHEPROGRAM)NCONTRAST NONRELATIONALOROBJECT ORIENTEDDATABASES PROVIDEDONESETOFTOOLSFORPROGRAMMATICACCESSANDASEPARATEQUERYFACILITYFORADHOC REQUESTS WITHOUTANYSYNERGYBETWEENTHETWOMODESOFACCESS
-ULTIPLEõ6IEWSõOFõ$ATA 5SING31, THECREATOROFADATABASECANGIVEDIFFERENTUSERSOFTHEDATABASEDIFFERENTVIEWS OFITSSTRUCTUREANDCONTENTS&OREXAMPLE THEDATABASECANBECONSTRUCTEDSOTHATEACHUSER SEESDATAONLYFORHISORHERDEPARTMENTORSALESREGION)NADDITION DATAFROMSEVERAL DIFFERENTPARTSOFTHEDATABASECANBECOMBINEDANDPRESENTEDTOTHEUSERASASIMPLEROW COLUMNTABLE31,VIEWSCANTHUSBEUSEDTOENHANCETHESECURITYOFADATABASEANDTOTAILOR ITTOTHEPARTICULARNEEDSOFINDIVIDUALUSERSWHILEPRESERVINGTHEFUNDAMENTALROWCOLUMN STRUCTUREOFTHEDATA
#OMPLETEõ$ATABASEõ,ANGUAGE 31,WASFIRSTDEVELOPEDASANADHOCQUERYLANGUAGE BUTITSPOWERSNOWGOFARBEYOND DATARETRIEVAL31,PROVIDESACOMPLETE CONSISTENTLANGUAGEFORCREATINGADATABASE MANAGINGITSSECURITY UPDATINGITSCONTENTS RETRIEVINGDATA ANDSHARINGDATAAMONGMANY CONCURRENTUSERS31,CONCEPTSTHATARELEARNEDINONEPARTOFTHELANGUAGECANBEAPPLIED TOOTHER31,COMMANDS MAKINGUSERSMOREPRODUCTIVE
$YNAMICõ$ATAõ$EFINITION 5SING31, THESTRUCTUREOFADATABASECANBECHANGEDANDEXPANDEDDYNAMICALLY EVEN WHILEUSERSAREACCESSINGDATABASECONTENTS4HISISAMAJORADVANCEOVERSTATICDATA DEFINITIONLANGUAGES WHICHPREVENTEDACCESSTOTHEDATABASEWHILEITSSTRUCTUREWASBEING CHANGED31,THUSPROVIDESMAXIMUMFLEXIBILITY ALLOWINGADATABASETOADAPTTOCHANGING REQUIREMENTSWHILEONLINEAPPLICATIONSCONTINUEUNINTERRUPTED
#HAPTERçç
)NTRODUCTIONç
#LIENT3ERVERõ!RCHITECTURE
%NTERPRISEõ!PPLICATIONõ3UPPORT 4HELARGESTENTERPRISEAPPLICATIONSTHATSUPPORTTHEDAILYOPERATIONOFLARGECOMPANIESAND ORGANIZATIONSALLUSE31, BASEDDATABASESTOSTOREANDORGANIZETHEIRDATA)NTHES DRIVEN BYTHEIMPENDINGDEADLINEFORSUPPORTINGDATESINTHEYEARANDBEYONDTHESO CALLED h9+vPROBLEM LARGEENTERPRISESMOVEDENMASSETOABANDONTHEIRHOMEGROWNSYSTEMSAND CONVERTTOPACKAGEDENTERPRISEAPPLICATIONSFROMVENDORSLIKE3!0 /RACLE 0EOPLE3OFT 3IEBEL ANDOTHERS4HEDATAPROCESSEDBYTHESEAPPLICATIONSORDERS SALESAMOUNTS CUSTOMERS INVENTORYLEVELS PAYMENTAMOUNTS ETC TENDSTOHAVEASTRUCTURED RECORDS AND FIELDSFORMAT WHICHCONVERTSEASILYINTOTHEROWCOLUMNFORMATOF31,"YCONSTRUCTINGTHEIRAPPLICATIONS TOUSEENTERPRISE CLASS31,DATABASES THEMAJORAPPLICATIONVENDORSELIMINATEDTHENEEDTO DEVELOPTHEIROWNDATAMANAGEMENTSOFTWAREANDBENEFITEDFROMEXISTINGTOOLSAND PROGRAMMINGSKILLS"ECAUSEEVERYMAJORENTERPRISEAPPLICATIONREQUIRESA31, BASEDDATABASE FORITSOPERATION NEWSALESOFENTERPRISEAPPLICATIONSAUTOMATICALLYGENERATEhDRAG ALONGv DEMANDFORNEWCOPIESOFDATABASESOFTWARE
%XTENSIBILITYõANDõ/BJECTõ4ECHNOLOGY 4HEMAJORCHALLENGETO31,SCONTINUEDDOMINANCEASADATABASESTANDARDHASCOMEFROM THEEMERGENCEOFOBJECT BASEDPROGRAMMINGTHROUGHLANGUAGESSUCHAS*AVAAND# AND FROMTHEINTRODUCTIONOFOBJECT BASEDDATABASESASANEXTENSIONOFTHEBROADMARKETTREND TOWARDOBJECT BASEDTECHNOLOGY31, BASEDDATABASEVENDORSHAVERESPONDEDTOTHIS CHALLENGEBYSLOWLYEXPANDINGANDENHANCING31,TOINCLUDEOBJECTFEATURES4HESEhOBJECT RELATIONALvDATABASES WHICHCONTINUETOBEBASEDON31, HAVEEMERGEDASAMOREPOPULAR ALTERNATIVETOhPUREOBJECTvDATABASESANDHAVEPERPETUATED31,SDOMINANCETHROUGHTHE LASTDECADE4HENEWESTWAVEOFOBJECTTECHNOLOGY EMBODIEDINTHE8-,STANDARDANDWEB SERVICESARCHITECTURES ONCEAGAINCREATEDACROPOFh8-,DATABASESvANDALTERNATIVEQUERY LANGUAGESTOCHALLENGE31,INTHEEARLYS"UTONCEAGAIN THEMAJORVENDORSOF31, BASEDDATABASESRESPONDEDBYADDING8-, BASEDEXTENSIONS MEETINGTHECHALLENGEAND SECURING31,SCONTINUINGIMPORTANCE(ISTORYSUGGESTSTHATTHIShEXTENDANDINTEGRATEv APPROACHWILLBESUCCESSFULINWARDINGOFFNEWCHALLENGESINTHEFUTUREASWELL
)NTERNETõ$ATABASEõ!CCESS 7ITHTHEEXPLODINGPOPULARITYOFTHE)NTERNETANDTHE7ORLD7IDE7EB ANDTHEIR STANDARDS BASEDFOUNDATION 31,FOUNDANEWROLEINTHELATESASAN)NTERNETDATA ACCESSSTANDARD%ARLYINTHEDEVELOPMENTOFTHE7EB DEVELOPERSNEEDEDAWAYTORETRIEVE ANDPRESENTDATABASEINFORMATIONONWEBPAGESANDUSED31,ASACOMMONLANGUAGEFOR DATABASEGATEWAYS-ORERECENTLY THEEMERGENCEOFTHREE TIERED)NTERNETARCHITECTURESWITH DISTINCTTHINCLIENT APPLICATIONSERVER ANDDATABASESERVERLAYERS HASESTABLISHED31,AS THESTANDARDLINKBETWEENTHEAPPLICATIONANDDATABASETIERS4HEROLEOF31,INMULTITIER
0!24ç)
31,ISANATURALVEHICLEFORIMPLEMENTINGAPPLICATIONSUSINGADISTRIBUTED CLIENTSERVER ARCHITECTURE)NTHISROLE 31,SERVESASTHELINKBETWEENhFRONT ENDvCOMPUTERSYSTEMS OPTIMIZEDFORUSERINTERACTIONANDhBACK ENDvSYSTEMSSPECIALIZEDFORDATABASEMANAGEMENT ALLOWINGEACHSYSTEMTODOWHATITDOESBEST31,ALSOALLOWSPERSONALCOMPUTERSTO FUNCTIONASFRONT ENDSTONETWORKSERVERSORTOLARGERMINICOMPUTERANDMAINFRAME DATABASES PROVIDINGACCESSTOCORPORATEDATAFROMPERSONALCOMPUTERAPPLICATIONS
ç
0ARTç)ç
!Nç/VERVIEWçOFç31,
ARCHITECTURESISNOWBEGINNINGTOEXTENDBEYONDTHEBACK ENDDATABASELAYER TOINCLUDE DATACACHINGANDREAL TIMEDATAMANAGEMENTINORNEARTHEAPPLICATIONTIER
*AVAõ)NTEGRATIONõ*$"# !MAJORAREAOF31,DEVELOPMENTOVERTHELASTFIVETOTENYEARSHASBEENTHEINTEGRATIONOF 31,WITH*AVA3EEINGTHENEEDTOLINKTHE*AVALANGUAGETOEXISTINGRELATIONALDATABASES 3UN-ICROSYSTEMSTHECREATOROF*AVA INTRODUCED*AVA$ATABASE#ONNECTIVITY*$"# A STANDARD!0)THATALLOWS*AVAPROGRAMSTOUSE31,FORDATABASEACCESS*$"#RECEIVEDA FURTHERBOOSTWHENITWASADOPTEDASTHEDATAACCESSSTANDARDWITHINTHE*AVA%NTERPRISE %DITION*%% SPECIFICATION WHICHDEFINESTHEOPERATINGENVIRONMENTPROVIDEDBYMOSTOF THELEADING)NTERNETAPPLICATIONSERVERS)NADDITIONTOTHEROLEOF*AVAASAPROGRAMMING LANGUAGEFROMWHICHDATABASESAREUSED MANYOFTHELEADINGDATABASEVENDORSHAVEALSO ANNOUNCEDORIMPLEMENTED*AVASUPPORTWITHINTHEIRDATABASESYSTEMS ALLOWING*AVATOBE USEDASALANGUAGEFORSTOREDPROCEDURESANDBUSINESSLOGICWITHINTHEDATABASEITSELF4HIS TRENDTOWARDINTEGRATIONBETWEEN*AVAAND31,WILLENSURETHECONTINUEDIMPORTANCEOF 31,INTHENEWERAOF*AVA BASEDPROGRAMMING
/PENõ3OURCEõ3UPPORT /NEOFTHENEWERIMPORTANTDEVELOPMENTSINTHECOMPUTERINDUSTRYISTHEEMERGENCEOF ANhOPENSOURCEvAPPROACHTOBUILDINGCOMPLEXSOFTWARESYSTEMS7ITHTHISAPPROACH THE SOURCECODETHATDEFINESTHEOPERATIONOFASOFTWARESYSTEMISOPENANDFREELYAVAILABLE ANDMANYDIFFERENTPROGRAMMERSCANCONTRIBUTETOIT ADDINGFEATURES FIXINGBUGS ENHANCING ITSFUNCTIONALITY ANDPROVIDINGSUPPORTFORITSUSE4HISCOMMUNITYOFPROGRAMMERS POTENTIALLYSPREADACROSSTHOUSANDSOFDIFFERENTORGANIZATIONSANDAROUNDTHEGLOBE WITH SOMECOORDINATIONBECOMESTHEENGINETHATDRIVESTHEFURTHERDEVELOPMENTOFTHETECHNOLOGY /PENSOURCESOFTWAREISGENERALLYAVAILABLEATVERYLOWPRICESORFREE ADDINGTOITSAPPEAL 3EVERALSUCCESSFULOPENSOURCE31, BASEDDATABASESHAVEBEENBUILTINTHELASTDECADE AND ONEOFTHESE -Y31, ISASTANDARDCOMPONENTOFTHEMOSTPOPULAROPENSOURCEhSTACKvOF SOFTWARETHE,!-0STACKWHICHALSOINCLUDES,INUX THE!PACHEWEBSERVER ANDTHE0(0 SCRIPTINGLANGUAGE4HEWIDESPREADAVAILABILITYOFFREE31, BASEDOPENSOURCEDATABASESHAS EXPOSED31,TOANEVENBROADERRANGEOFPROGRAMMERS CONTINUINGTOBUILDITSPOPULARITY
)NDUSTRYõ)NFRASTRUCTURE 0ERHAPSTHEMOSTIMPORTANTFACTORCONTRIBUTINGTOTHEGROWINGIMPORTANCEOF31,ISTHE EMERGENCEOFANENTIRECOMPUTERINDUSTRYINFRASTRUCTUREBASEDON31,31, BASED RELATIONALDATABASESYSTEMSAREANIMPORTANTPARTOFTHISINFRASTRUCTURE%NTERPRISE APPLICATIONSTHATUSE31,ANDREQUIREA31, BASEDDATABASEAREANOTHERIMPORTANTPART AS AREREPORTINGTOOLS DATAENTRYTOOLS DESIGNTOOLS PROGRAMMINGTOOLS ANDAHOSTOFOTHER TOOLSTHATSIMPLIFYTHEUSEOF31,!LARGEPOOLOFEXPERIENCED31,PROGRAMMERSISACRITICAL PARTOFTHEINFRASTRUCTURE!NOTHERIMPORTANTPARTISTHETRAININGANDSUPPORTSERVICESTHAT SURROUND31,ANDHELPTOCREATEANDPERPETUATE31,EXPERTISE!NENTIRESUBINDUSTRYHAS EMERGEDAROUND31,CONSULTING OPTIMIZATION ANDPERFORMANCE TUNING!LLPARTSOFTHIS INFRASTRUCTURETENDTOREINFORCEONEANOTHERANDTOCONTRIBUTETOTHEONGOINGSUCCESSOFTHE OTHERPARTS3IMPLYSTATED TOSOLVEDATAMANAGEMENTPROBLEMS THEEASIEST LOWEST RISK LOWEST COSTSOLUTIONISALMOSTALWAYSASOLUTIONBASEDON31,
#(!04%2
!ç1UICKç4OURçOFç31,
"
EFOREWEDIVEINTOTHEDETAILSOF31, ITSAGOODIDEATODEVELOPANOVERALL PERSPECTIVEONTHELANGUAGEANDHOWITWORKS4HISCHAPTERCONTAINSAQUICKTOUROF 31,THATILLUSTRATESITSMAJORFEATURESANDFUNCTIONS4HEGOALOFTHEQUICKTOURISNOT TOMAKEYOUPROFICIENTINWRITING31,STATEMENTSTHATSTHEGOALOF0ART))OFTHISBOOK 2ATHER BYTHETIMEYOUVEFINISHEDTHISCHAPTER YOUWILLHAVEABASICFAMILIARITYWITHTHE 31,ANDANOVERVIEWOFITSCAPABILITIES
!õ3IMPLEõ$ATABASE 4HEEXAMPLESINTHISQUICKTOURAREBASEDONASIMPLERELATIONALDATABASEFORASMALL DISTRIBUTIONCOMPANY4HEDATABASE SHOWNIN&IGURE STORESTHEINFORMATIONNEEDEDTO IMPLEMENTASMALLORDER PROCESSINGAPPLICATION9OUWILLFINDINSTRUCTIONSFORCREATINGTHE SAMPLEDATABASEIN!PPENDIX! SOYOUCANTRYTHESEQUERIESYOURSELFASYOUREAD 3PECIFICALLY ITSTORESTHEFOLLOWINGINFORMATION s 4HECUSTOMERSWHOBUYTHECOMPANYSPRODUCTS s 4HEORDERSPLACEDBYTHOSECUSTOMERS s 4HESALESPEOPLEWHOSELLTHEPRODUCTSTOCUSTOMERS s 4HESALESOFFICESWHERETHOSESALESPEOPLEWORK 4HISDATABASE LIKEMOSTOTHERS ISAMODELOFTHEhREALWORLDv4HEDATASTOREDINTHE DATABASEREPRESENTSREALENTITIESCUSTOMERS ORDERS SALESPEOPLE ANDOFFICES%ACHDIFFERENT KINDOFENTITYHASASEPARATETABLEOFDATA&OREXAMPLE INTHE3!,%32%03TABLE EACH SALESPERSONISREPRESENTEDBYONEROW ANDEACHCOLUMNHOLDSONETYPEOFINFORMATION ABOUTSALESPEOPLE SUCHASTHEIRNAMEORTHESALESOFFICEWHERETHEYAREASSIGNED$ATABASE REQUESTSTHATYOUMAKEUSINGTHE31,PARALLELREAL WORLDACTIVITIES ASCUSTOMERSPLACE CANCEL ANDCHANGEORDERSASYOUHIREANDFIRESALESPEOPLEANDSOON,ETSSEEHOWYOU CANUSE31,TOMANIPULATEDATA
ç
0ARTç)ç
!Nç/VERVIEWçOFç31,
1, ÊÓ£Ê ÊëiÊÀi>Ì>Ê`>Ì>L>Ãi
2ETRIEVINGõ$ATA &IRST LETSLISTTHESALESOFFICES SHOWINGTHECITYWHEREEACHONEIS ITSOFFICENUMBER ANDITS YEAR TO DATESALES4HE31,STATEMENTTHATRETRIEVESDATAFROMTHEDATABASEISCALLED3%,%#4 4HIS31,STATEMENTRETRIEVESTHEDATAYOUWANT 3%,%#4#)49 /&&)#% 3!,%3 &2/-/&&)#%3 #)49/&&)#%3!,%3
$ENVER .EW9ORK #HICAGO !TLANTA ,OS!NGELES
#HAPTERçç
! ç 1 U I C K ç 4O U R ç O F ç 3 1 , ç
3%,%#4.!-% 2%0?/&&)#% 3!,%3 15/4! &2/-3!,%32%03 .!-%2%0?/&&)#%3!,%315/4!
"ILL!DAMS -ARY*ONES 3UE3MITH 3AM#LARK "OB3MITH $AN2OBERTS 4OM3NYDER.5,, .5,, ,ARRY&ITCH 0AUL#RUZ .ANCY!NGELLI
4HE.5,,VALUESFOR4OM3NYDERREPRESENTMISSINGORUNKNOWNDATA(EISNEWTOTHE COMPANYANDHASNOTYETBEENASSIGNEDTOASALESOFFICEORBEENGIVENASALESQUOTA(OWEVER HEHASALREADYMADESOMESALES4HEDATAINHISROWOFQUERYRESULTSSHOWSTHISCLEARLY 31,ALSOLETSYOUASKFORCALCULATEDRESULTS&OREXAMPLE YOUCANASK31,TOCALCULATE THEAMOUNTBYWHICHEACHSALESPERSONISOVERORUNDERQUOTA 3%,%#4.!-% 3!,%3 15/4! 3!,%3n15/4! &2/-3!,%32%03 .!-%3!,%315/4!3!,%3n15/4!
"ILL!DAMS -ARY*ONES 3UE3MITH 3AM#LARK "OB3MITH n $AN2OBERTS 4OM3NYDER .5,,.5,, ,ARRY&ITCH 0AUL#RUZ .ANCY!NGELLI n
4HEREQUESTEDDATAINCLUDINGTHECALCULATEDDIFFERENCEBETWEENSALESANDQUOTAFOR EACHSALESPERSON ONCEAGAINAPPEARSINAROWCOLUMNTABLE0ERHAPSYOUWOULDLIKETO FOCUSONTHESALESPEOPLEWHOSESALESARELESSTHANTHEIRQUOTAS31,LETSYOURETRIEVETHAT
0!24ç)
4HE3%,%#4STATEMENTASKSFORTHREEPIECESOFDATATHECITY THEOFFICENUMBER ANDTHE AMOUNTOFSALESFOREACHOFFICE)TALSOSPECIFIESTHATALLOFTHISDATACOMESFROMTHE /&&)#%3TABLE WHICHSTORESDATAABOUTSALESOFFICES4HERESULTSOFTHEQUERYAPPEAR IN TABULARFORM IMMEDIATELYAFTERTHEREQUEST.OTETHATTHEFORMATTINGOFTHEQUERYRESULTS WILLVARYFROMONE31,IMPLEMENTATIONTOANOTHER 4HE3%,%#4STATEMENTISUSEDFORALL31,QUERIES&OREXAMPLE HEREISAQUERYTHATLISTS THENAMESANDYEAR TO DATESALESFOREACHSALESPERSONINTHEDATABASE)TALSOSHOWSTHE QUOTASALESTARGET ANDTHEOFFICENUMBERWHEREEACHPERSONWORKS)NTHISCASE THEDATA COMESFROMTHE3!,%32%03TABLE
ç
0ARTç)ç
!Nç/VERVIEWçOFç31,
KINDOFSELECTIVEINFORMATIONVERYEASILY BYADDINGAMATHEMATICALCOMPARISONTOTHE PREVIOUSREQUEST 3%,%#4.!-% 3!,%3 15/4! 3!,%3n15/4! &2/-3!,%32%03 7(%2%3!,%315/4! .!-%3!,%315/4!3!,%3n15/4!
"OB3MITH n .ANCY!NGELLI n
9OUCANUSETHESAMETECHNIQUETOLISTLARGEORDERSINTHEDATABASEANDFINDOUTWHICH CUSTOMERPLACEDTHEORDER WHICHPRODUCTWASORDERED ANDINWHATQUANTITY9OUCANALSO ASK31,TOSORTTHEORDERSBASEDONTHEORDERAMOUNT 3%,%#4/2$%2?.5- #534 02/$5#4 149 !-/5.4 &2/-/2$%23 7(%2%!-/5.4 /2$%2"9!-/5.4 /2$%2?.5-#53402/$5#4149!-/5.4
9 # !, !2
3UMMARIZINGõ$ATA 31,NOTONLYRETRIEVESINDIVIDUALPIECESOFDATAFROMTHEDATABASE BUTITALSOCAN SUMMARIZETHEDATABASECONTENTS7HATSTHEAVERAGESIZEOFANORDERINTHEDATABASE4HIS REQUESTASKS31,TOLOOKATALLTHEORDERSANDFINDTHEAVERAGEAMOUNT 3%,%#4!6'!-/5.4 &2/-/2$%23 !6'!-/5.4
9OUCOULDALSOASKFORTHEAVERAGEORDERSIZEFORAPARTICULARCUSTOMER 3%,%#4!6'!-/5.4 &2/-/2$%23 7(%2%#534 !6'!-/5.4
#HAPTERçç
! ç 1 U I C K ç 4O U R ç O F ç 3 1 , ç
3%,%#4#534 35-!-/5.4 &2/-/2$%23 '2/50"9#534 #53435-!-/5.4
!DDINGõ$ATAõTOõTHEõ$ATABASE 9OUALSOUSE31,TOADDNEWDATATOTHEDATABASE&OREXAMPLE SUPPOSEYOUJUSTOPENEDA NEW7ESTERNREGIONSALESOFFICEIN$ALLAS WITHTARGETSALESOF (ERESTHE).3%24 STATEMENTTHATADDSTHENEWOFFICETOTHEDATABASE ASOFFICENUMBER ).3%24).4//&&)#%3#)49 2%')/. 4!2'%4 3!,%3 /&&)#% 6!,5%3g$ALLASg g7ESTERNg ROWINSERTED
3IMILARLY IF-ARY*ONESEMPLOYEENUMBER SIGNSUPANEWCUSTOMER !CME )NDUSTRIES THIS).3%24STATEMENTADDSTHECUSTOMERTOTHEDATABASEASCUSTOMERNUMBER WITHA CREDITLIMIT ).3%24).4/#534/-%23#/-0!.9 #534?2%0 #534?.5- #2%$)4?,)-)4 6!,5%3g!CME)NDUSTRIESg ROWINSERTED
9OUMAYHAVENOTICEDTHATTHE31,ENGINERETURNEDFEEDBACKROWINSERTED TOTELL YOUTHATTHESTATEMENTSWORKED4HEEXACTWORDINGANDFORMATTINGOFTHISFEEDBACKWILL VARYFROMONE31,IMPLEMENTATIONTOANOTHER
0!24ç)
&INALLY LETSFINDOUTTHETOTALVALUEOFTHEORDERSPLACEDBYEACHCUSTOMER4ODOTHIS YOUCANASK31,TOGROUPTHEORDERSTOGETHERBYCUSTOMERNUMBERANDTHENTOTALTHEORDERS FOREACHCUSTOMER
ç
0ARTç)ç
!Nç/VERVIEWçOFç31,
$ELETINGõ$ATA *USTASTHE31,).3%24STATEMENTADDSNEWDATATOTHEDATABASE THE31,$%,%4%STATEMENT REMOVESDATAFROMTHEDATABASE)F!CME)NDUSTRIESDECIDESAFEWDAYSLATERTOSWITCHTOA COMPETITOR YOUCANDELETE!CMESCUSTOMERINFORMATIONFROMTHEDATABASEWITHTHISSTATEMENT $%,%4%&2/-#534/-%23 7(%2%#/-0!.9g!CME)NDUSTRIESg ROWDELETED
!NDIFYOUDECIDETOTERMINATEALLSALESPEOPLEWHOSESALESARELESSTHANTHEIRQUOTAS YOUCANREMOVETHEMFROMTHEDATABASEWITHTHIS$%,%4%STATEMENT $%,%4%&2/-3!,%32%03 7(%2%3!,%315/4! ROWSDELETED
5PDATINGõTHEõ$ATABASE 9OUCANUSE31,TOMODIFYDATATHATISALREADYSTOREDINTHEDATABASE&OREXAMPLE TO INCREASETHECREDITLIMITFOR&IRST#ORPTO YOUWOULDUSETHE31,50$!4% STATEMENT 50$!4%#534/-%23 3%4#2%$)4?,)-)4 7(%2%#/-0!.9g&IRST#ORPg ROWUPDATED
4HE50$!4%STATEMENTCANALSOMAKEMANYCHANGESINTHEDATABASEATONCE&OR EXAMPLE THIS50$!4%STATEMENTRAISESTHEQUOTAFORALLSALESPEOPLEBY 50$!4%3!,%32%03 3%415/4!15/4! ROWSUPDATED
0ROTECTINGõ$ATA !NIMPORTANTROLEOFADATABASEISTOPROTECTTHESTOREDDATAFROMACCESSORMODIFICATIONBY UNAUTHORIZEDUSERS&OREXAMPLE SUPPOSEYOURASSISTANT -ARY HASADATABASEACCOUNTBUT HASNOTBEENPREVIOUSLYAUTHORIZEDTOINSERTDATAABOUTNEWCUSTOMERSINTOTHEDATABASE 4HIS31,STATEMENTGRANTSHERTHATPERMISSION '2!.4).3%24 /.#534/-%23 4/-!29 0RIVILEGEGRANTED
#HAPTERçç
! ç 1 U I C K ç 4O U R ç O F ç 3 1 , ç
3IMILARLY THEFOLLOWING31,STATEMENTGIVES-ARYPERMISSIONTOUPDATEDATAABOUT CUSTOMERSANDTORETRIEVECUSTOMERDATAWITHTHE3%,%#4STATEMENT
)F-ARYISNOLONGERALLOWEDTOADDNEWCUSTOMERSTOTHEDATABASE THIS2%6/+%STATEMENT WILLDISALLOWIT 2%6/+%).3%24 /.#534/-%23 &2/--!29 0RIVILEGEREVOKED
3IMILARLY THIS2%6/+%STATEMENTWILLREVOKEALLOF-ARYSPRIVILEGESTOACCESSORMODIFY CUSTOMERDATAINANYWAY 2%6/+%!,, /.#534/-%23 &2/--!29 0RIVILEGEREVOKED
#REATINGõAõ$ATABASE "EFOREYOUCANSTOREDATAINADATABASE YOUMUSTFIRSTDEFINETHESTRUCTUREOFTHEDATA 3UPPOSEYOUWANTTOEXPANDTHESAMPLEDATABASEBYADDINGATABLEOFDATAABOUTTHE PRODUCTSYOURCOMPANYSELLS&OREACHPRODUCT THEDATATOBESTOREDINCLUDESTHE FOLLOWING s !THREE CHARACTERMANUFACTURER)$CODE s !FIVE CHARACTERPRODUCT)$CODE s !PRODUCTDESCRIPTIONOFUPTOCHARACTERS s 4HEPRICEOFTHEPRODUCT s 4HEQUANTITYCURRENTLYONHAND 4HIS31,#2%!4%4!",%STATEMENTDEFINESANEWTABLETOSTORETHEPRODUCTSDATA #2%!4%4!",%02/$5#43 -&2?)$#(!2 02/$5#4?)$#(!2 $%3#2)04)/.6!2#(!2 02)#%$%#)-!, 149?/.?(!.$).4%'%2 4ABLECREATED
0!24ç)
'2!.450$!4% 3%,%#4 /.#534/-%23 4/-!29 0RIVILEGEGRANTED
ç
0ARTç)ç
!Nç/VERVIEWçOFç31,
!LTHOUGHMORECRYPTICTHANTHEPREVIOUS31,STATEMENTEXAMPLES THE#2%!4%4!",% STATEMENTISSTILLFAIRLYSTRAIGHTFORWARD)TASSIGNSTHENAME02/$5#43TOTHENEWTABLEAND SPECIFIESTHENAMEANDTYPEOFDATASTOREDINEACHOFITSFIVECOLUMNS4HEMANUFACTURERAND PRODUCT)$SARESTOREDASFIXED LENGTHSEQUENCESOFCHARACTERS THEPRODUCTDESCRIPTIONISA VARIABLE LENGTHCHARACTERSTRING THEPRICEISDECIMALDATAAREALNUMBER ANDTHEQUANTITY ISANINTEGER /NCETHETABLEHASBEENCREATED YOUCANFILLITWITHDATA(ERESAN).3%24STATEMENT FORANEWSHIPMENTOFSIZEWIDGETSPRODUCT!#) WHICHCOSTAPIECE ).3%24).4/02/$5#43-&2?)$ 02/$5#4?)$ $%3#2)04)/. 02)#% 149?/.?(!.$ 6!,5%3g!#)g gg g3IZE7IDGETg ROWINSERTED
&INALLY IFYOUDISCOVERLATERTHATYOUNOLONGERNEEDTOSTORETHEPRODUCTSDATAINTHE DATABASE YOUCANERASETHETABLEANDALLOFTHEDATAITCONTAINS WITHTHE$2/04!",% STATEMENT $2/04!",%02/$5#43 4ABLEDROPPED
3UMMARY 4HISQUICKTOUROF31,SHOWEDYOUWHAT31,CANDOANDILLUSTRATEDTHESTYLEOFTHE31,BY USINGEIGHTOFTHEMOSTCOMMONLYUSED31,STATEMENTS4OSUMMARIZE s 5SE31,TORETRIEVEDATAFROMTHEDATABASE BYUSINGTHE3%,%#4STATEMENT9OUCAN RETRIEVEALLORPARTOFTHESTOREDDATA SORTIT ANDASK31,TOSUMMARIZETHEDATA USINGTOTALSANDAVERAGES s 5SE31,TOUPDATETHEDATABASE BYADDINGNEWDATAWITHTHE).3%24STATEMENT DELETINGDATAWITHTHE$%,%4%STATEMENT ANDMODIFYINGEXISTINGDATAWITHTHE 50$!4%STATEMENT s 5SE31,TOCONTROLACCESSTOTHEDATABASE BYGRANTINGANDREVOKINGSPECIFIC PRIVILEGESFORSPECIFICUSERSWITHTHE'2!.4AND2%6/+%STATEMENTS s 5SE31,TOCREATEMODIFYTHEDATABASEBYDEFININGTHESTRUCTUREOFNEWTABLESAND DROPPINGTABLESWHENTHEYARENOLONGERNEEDED BYUSINGTHE#2%!4%AND$2/0 STATEMENTS
#(!04%2
31,çINç0ERSPECTIVE
3
1,ISTHESTANDARDLANGUAGEFORDATABASEMANAGEMENTTODAY7HATDOESITMEAN FOR31,TOBEASTANDARD(OWDIDITBECOMEASTANDARD7HATROLEDOESTHE OFFICIAL31,STANDARDPLAY(OWBROADLYADOPTEDISIT ANDWHYARETHERESTILL DIALECTSOF31,DESPITETHESTANDARD(OWBROADIS31,SIMPACTONVARIOUSSEGMENTS OFTHE)4LANDSCAPE4OANSWERTHESEQUESTIONS THISCHAPTERTRACESTHEHISTORYOF31, ANDDESCRIBESITSCURRENTROLEINTHECOMPUTERMARKET
31,õANDõTHEõ%VOLUTIONõOFõ$ATABASEõ-ANAGEMENT /NEOFTHEMAJORTASKSOFACOMPUTERSYSTEMISTOSTOREANDMANAGEDATA4OHANDLETHISTASK SPECIALIZEDCOMPUTERPROGRAMSKNOWNASDATABASEMANAGEMENTSYSTEMSBEGANTOAPPEARINTHE LATESANDEARLYS!DATABASEMANAGEMENTSYSTEM OR$"-3 HELPEDCOMPUTER USERSTOORGANIZEANDSTRUCTURETHEIRDATAANDALLOWEDTHECOMPUTERSYSTEMTOPLAYAMORE ACTIVEROLEINMANAGINGTHEDATA!LTHOUGHDATABASEMANAGEMENTSYSTEMSWEREFIRST DEVELOPEDONLARGEMAINFRAMESYSTEMS THEIRPOPULARITYQUICKLYSPREADTOMINICOMPUTERS ANDTHENTOCOMPUTERWORKSTATIONS PERSONALCOMPUTERS ANDSPECIALIZEDSERVERCOMPUTERS $ATABASEMANAGEMENTHASALSOPLAYEDAKEYROLEINTHEEXPLOSIONOFCOMPUTER NETWORKINGANDTHE)NTERNET%ARLYDATABASESYSTEMSRANONLARGE MONOLITHICCOMPUTER SYSTEMS WHERETHEDATA THEDATABASEMANAGEMENTSOFTWARE ANDTHEUSERSORAPPLICATION PROGRAMSACCESSINGTHEDATABASEALLOPERATEDONTHESAMESYSTEM4HESANDSSAW THEEXPLOSIONOFANEWCLIENTSERVERMODELFORDATABASEACCESS INWHICHAUSERORAN APPLICATIONPROGRAMRUNNINGONAPERSONALCOMPUTERACCESSESADATABASEONASEPARATE COMPUTERSYSTEMBYUSINGANETWORK)NTHELATES THEINCREASINGPOPULARITYOFTHE )NTERNETANDTHE7ORLD7IDE7EBIMPACTEDTHEARCHITECTUREOFDATAMANAGEMENTAGAIN 4ODAY USERSREQUIRELITTLEMORETHANAWEBBROWSERTOACCESSANDINTERACTWITHDATABASES NOTONLYWITHINTHEIROWNORGANIZATIONS BUTALSOAROUNDTHEWORLD4HESE)NTERNET BASED ARCHITECTURESUSUALLYINVOLVETHREEORMORECOMPUTERSYSTEMSONETHATRUNSTHEWEB BROWSERANDINTERACTSWITHTHEUSER CONNECTEDOVERTHE)NTERNETTOASECONDSYSTEMTHAT RUNSANAPPLICATIONPROGRAMORAPPLICATIONSERVER WHICHISINTURNCONNECTEDTOATHIRD SYSTEMTHATRUNSTHEDATABASEMANAGEMENTSYSTEM $ATABASEMANAGEMENTHASBECOMEAVERYBIGBUSINESS)NDEPENDENTSOFTWARECOMPANIES ANDCOMPUTERVENDORSSHIPBILLIONSOFDOLLARSWORTHOFDATABASEMANAGEMENTPRODUCTS EVERYYEAR6IRTUALLYALLENTERPRISE CLASSCOMPUTERAPPLICATIONSTHATSUPPORTTHEDAILYOPERATION
ç
0ARTç)ç
!Nç/VERVIEWçOFç31,
OFLARGECOMPANIESANDOTHERORGANIZATIONSUSEDATABASES4HESEAPPLICATIONSINCLUDESOMEOF THEFASTEST GROWINGAPPLICATIONCATEGORIES SUCHAS%NTERPRISE2ESOURCE0LANNING%20 #USTOMER2ELATIONSHIP-ANAGEMENT#2- 3UPPLY#HAIN-ANAGEMENT3#- 3ALES&ORCE !UTOMATION3&! ANDFINANCIALAPPLICATIONS3PECIALIZEDHIGH PERFORMANCESERVERCOMPUTERS OPTIMIZEDTORUNTHEMOSTPOPULARDATABASESOFTWARECONSTITUTEAMULTIBILLION DOLLARMARKET ANDLOW COSTSERVERSUSEDEXCLUSIVELYFORDATAMANAGEMENTADDBILLIONSMORE$ATABASES PROVIDETHEINTELLIGENCEBEHINDMOSTTRANSACTION ORIENTEDWEBSITES ANDTHEYAREUSEDTO CAPTUREANDANALYZEUSERINTERACTIONSWITHWEBSITES$ATABASEMANAGEMENTTHUSTOUCHES EVERYSEGMENTOFTHECOMPUTERMARKET 3INCETHELATES ASPECIFICTYPEOF$"-3 CALLEDARELATIONALDATABASEMANAGEMENT SYSTEM2$"-3 HASBECOMESOPOPULARTHATITISTHESTANDARDDATABASEFORM2ELATIONAL DATABASESORGANIZEDATAINASIMPLE TABULARFORMANDPROVIDEMANYADVANTAGESOVER EARLIERTYPESOFDATABASES31,ISSPECIFICALLYARELATIONALDATABASELANGUAGEUSEDTOWORK WITHRELATIONALDATABASES
!õ"RIEFõ(ISTORYõOFõ31, 4HEHISTORYOFTHE31,ISINTIMATELYINTERTWINEDWITHTHEDEVELOPMENTOFRELATIONALDATABASES 4ABLE SHOWSSOMEOFTHEEARLYMILESTONESINITS YEARHISTORY4HERELATIONALDATABASE CONCEPTWASORIGINALLYDEVELOPEDBY%DGAR&RANKh4EDv#ODD AN)"-RESEARCHER)N*UNE #ODDPUBLISHEDANARTICLEENTITLEDh!2ELATIONAL-ODELOF$ATAFOR,ARGE3HARED$ATA"ANKS v WHICHOUTLINEDAMATHEMATICALTHEORYOFHOWDATACOULDBESTOREDANDMANIPULATEDUSING ATABULARSTRUCTURE2ELATIONALDATABASESAND31,TRACETHEIRORIGINSTOTHISARTICLE WHICH APPEAREDINTHE#OMMUNICATIONSOFTHE!SSOCIATIONFOR#OMPUTING-ACHINERY
4HEõ%ARLYõ9EARS #ODDSARTICLETRIGGEREDAFLURRYOFRELATIONALDATABASERESEARCH INCLUDINGAMAJORRESEARCH PROJECTWITHIN)"-4HEGOALOFTHEPROJECT CALLED3YSTEM2 WASTOPROVETHEWORKABILITYOF THERELATIONALCONCEPTANDTOPROVIDESOMEEXPERIENCEINACTUALLYIMPLEMENTINGARELATIONAL $"-37ORKON3YSTEM2BEGANINTHEMID SAT)"-S3ANTA4ERESALABORATORIESIN 3AN*OSE #ALIFORNIA )NAND THEFIRSTPHASEOFTHE3YSTEM2PROJECTPRODUCEDAMINIMALPROTOTYPE OFARELATIONAL$"-3)NADDITIONTOTHE$"-3ITSELF THE3YSTEM2PROJECTINCLUDEDWORK ONDATABASEQUERYLANGUAGES/NEOFTHESELANGUAGESWASCALLED3%15%, ANACRONYMFOR 3TRUCTURED%NGLISH1UERY,ANGUAGE)NAND THE3YSTEM2RESEARCHPROTOTYPE WASREWRITTENFROMSCRATCH ANDTHENEWIMPLEMENTATIONWASDISTRIBUTEDTOSELECTED)"- CUSTOMERSFOREVALUATIONINAND4HESEEARLYCUSTOMERSITESPROVIDEDSOMEACTUAL USEREXPERIENCEWITH3YSTEM2ANDITSDATABASELANGUAGE WHICH FORLEGALREASONS HAD BEENRENAMED31, OR3TRUCTURED1UERY,ANGUAGE)N THE3YSTEM2RESEARCHPROJECT CAMETOANEND WITH)"-CONCLUDINGTHATRELATIONALDATABASESWERENOTONLYFEASIBLE BUT ALSOCOULDBETHEBASISFORAUSEFULCOMMERCIALPRODUCT
%ARLYõ2ELATIONALõ0RODUCTS 4HE3YSTEM2PROJECTANDITS31,DATABASELANGUAGEWEREWELL CHRONICLEDINTECHNICALJOURNALS DURINGTHES3EMINARSONDATABASETECHNOLOGYFEATUREDDEBATESONTHEMERITSOFTHENEW ANDHERETICALRELATIONALMODEL"Y ITWASAPPARENTTHAT)"-WASBECOMINGENTHUSIASTIC ABOUTRELATIONALDATABASETECHNOLOGYANDTHATITWASMAKINGAMAJORCOMMITMENTTO31,
#HAPTERçç
31,çINç0ERSPECTIVEç
ÛiÌ
£Çä
``Ê`iviÃÊÀi>Ì>Ê`>Ì>L>ÃiÊ`i
£Ç{
ÊLi}ÃÊ-ÞÃÌiÉ,Ê«ÀiVÌ
£Ç{
ÀÃÌÊ>ÀÌViÊ`iÃVÀL}ÊÌ
iÊ- +1 Ê>}Õ>}iÊÃÊ«ÕLÃ
i`
£Çn
-ÞÃÌiÉ,ÊVÕÃÌiÀÊÌiÃÌÃÊ>ÀiÊV`ÕVÌi`
£Ç
"À>ViÊÌÀ`ÕViÃÊvÀÃÌÊViÀV>Ê, -
£n£
,i>Ì>Ê/iV
}ÞÊÌÀ`ÕViÃÊ}ÀiÃ
£n£
Ê>ÕViÃÊ-+É -
£nÓ
-ÊvÀÃÊ-+ÊÃÌ>`>À`ÃÊVÌÌii
£nÎ
Ê>ÕViÃÊ Ó
£nÈ
-Ê-+£ÊÃÌ>`>À`ÊÃÊÀ>Ìvi`
£nÈ
-ÞL>ÃiÊÌÀ`ÕViÃÊ, -ÊvÀÊÌÀ>Ã>VÌÊ«ÀViÃÃ}
£nÇ
-"Ê-+£ÊÃÌ>`>À`ÊÃÊÀ>Ìvi`
£nn
Ã
Ì/>ÌiÊ>`ÊVÀÃvÌÊ>ÕViÊ-+Ê-iÀÛiÀÊvÀÊ"-ÉÓ
£n
ÀÃÌÊ/* ÊLiV
>ÀÊ/* ®ÊÃÊ«ÕLÃ
i`
£ä
/* ÊLiV
>ÀÊÃÊ«ÕLÃ
i`
££
-+ÊVViÃÃÊÀÕ«Ê`>Ì>L>ÃiÊ>VViÃÃÊëiVvV>ÌÊÃÊ«ÕLÃ
i`
£Ó
VÀÃvÌÊ«ÕLÃ
iÃÊ" ÊëiVvV>Ì
£Ó
-Ê-+ÓÊÃÌ>`>À`Ê-+Ó®ÊÃÊÀ>Ìvi`
£Ó
/* Ê"/*®ÊLiV
>ÀÊÃÊ«ÕLÃ
i`
£Î
-«iV>âi`Ê-+Ê`>Ì>ÊÜ>Ài
ÕÃ}ÊÃÞÃÌiÃÊ>ÀiÊÃ
««i`ÊvÀÊÌ
iÊvÀÃÌÊÌi
£Î
" Ê«À`ÕVÌÃÊ>ÀiÊÃ
««i`ÊvÀÊÌ
iÊvÀÃÌÊÌi
£{
*>À>iÊ`>Ì>L>ÃiÊÃiÀÛiÀÊÌiV
}ÞÊÃÊÃ
««i`ÊViÀV>Þ
£x
"«iÊÃÕÀViÊÞ-+ÊvÀÃÌÊÀii>Ãi`
£È
-Ì>`>À`Ê*ÊvÀÊ"*Ê`>Ì>L>ÃiÊ>VViÃÃÊ>`Ê"*ÊLiV
>ÀÊÃÊ«ÕLÃ
i`
£Ç
Ê ÓÊ1 ÊÕviÃÊ ÓÊ>ÀV
ÌiVÌÕÀiÊ>VÀÃÃÊ Ê>`ÊÌ
iÀÊÛi`ÀÊ«>ÌvÀÃ
£Ç
>ÀÊ -ÊÛi`ÀÃÊ>ÕViÊ>Û>ÊÌi}À>ÌÊÃÌÀ>Ìi}iÃ
£n
VÀÃvÌÊ-+Ê-iÀÛiÀÊÇÊ«ÀÛ`iÃÊiÌiÀ«ÀÃiiÛiÊ`>Ì>L>ÃiÊÃÕ««ÀÌÊvÀÊ7`ÜÃÊ /
£n
"À>ViÊnIÊ«ÀÛ`iÃÊ`>Ì>L>ÃiÉÌiÀiÌÊÌi}À>ÌÊ>`ÊÛiÃÊ>Ü>ÞÊvÀÊViÌÉÃiÀÛiÀÊ`i
£n
iÀV>ÊiÀÞÊ`>Ì>L>ÃiÊ«À`ÕVÌÃÊ>ÀiÊÃ
««i`ÊvÀÊÌ
iÊvÀÃÌÊÌi
£
Ó
ÊÃÌ>`>À`âiÃÊ Ê`>Ì>L>ÃiÊ>VViÃÃÊvÀÊ>««V>ÌÊÃiÀÛiÀÃ
£
-É-"Ê-+\£ÊÃÌ>`>À`ÊÀ>Ìvi`]Ê>``}ÊLiVÌÀiÌi`ÊVÃÌÀÕVÌÃÊÌÊÌ
iÊ>}Õ>}i
Óäää
"À>ViÊÌÀ`ÕViÃÊ>««V>ÌÊÃiÀÛiÀÃÊÜÌ
ÊÌi}À>Ìi`Ê`>Ì>L>ÃiÊV>V
}
Óäää
VÀÃvÌÊÌÀ`ÕViÃÊ-+Ê-iÀÛiÀÊÓäää]Ê>i`Ê>ÌÊiÌiÀ«ÀÃiÊ>««V>ÌÃ
Óää£
8ÊÌi}À>ÌÊV>«>LÌiÃÊ>««i>ÀÊÊ>ÃÌÀi>Ê, -Ê«À`ÕVÌÃ
Óää£
Ê>VµÕÀiÃÊvÀÝÊ`>Ì>L>ÃiÊLÕÃiÃÃ
ÓääÓ
>ÀÌiÀÊÀ>ÃÊ Ê>ÃÊ£Ê`>Ì>L>ÃiÊÛi`À]Ê«>ÃÃ}Ê"À>Vi
ÓääÎ
-É-"Ê-+\ÓääÎÊÀ>Ìvi`]Ê>``}Ê-+É8
ÓääÈ
-É-"Ê-+\ÓääÈÊÀ>Ìvi`]ÊÃ}vV>ÌÞÊiÝ«>`}Ê-+É8Ê>`ÊLiVÌÀiÌi`ÊVÃÌÀÕVÌÃ
ÓääÈ
Ê>`Ê>ÀÌiÀÊÃÌÕ`iÃÊÃ
ÜÊ"À>ViÊi>`}ÊÊ>ÀiÌÊÃ
>Ài
Óään
Þ-+Ê Ê>VµÕÀi`ÊLÞÊ-ÕÊVÀÃÞÃÌiÃ
Óään
-É-"Ê-+\ÓäänÊÀ>Ìvi`
/ ÊÎ£Ê iÃÌiÃÊÊ-+Ê iÛi«iÌ
0!24ç)
9i>À
ç
0ARTç)ç
!Nç/VERVIEWçOFç31,
4HEPUBLICITYABOUT3YSTEM2ATTRACTEDTHEATTENTIONOFAGROUPOFENGINEERSIN-ENLO 0ARK #ALIFORNIA WHODECIDEDTHAT)"-SRESEARCHFORESHADOWEDACOMMERCIALMARKETFOR RELATIONALDATABASES)NTHEYFORMEDACOMPANY 2ELATIONAL3OFTWARE )NC TOBUILDA RELATIONAL$"-3BASEDON31,4HEIRPRODUCTNAMED/RACLE SHIPPEDINANDBECAME THEFIRSTCOMMERCIALLYAVAILABLERELATIONAL$"-3/RACLEBEAT)"-SFIRSTPRODUCTTOMARKET BYAFULLTWOYEARS AND/RACLERANON$IGITALS6!8MINICOMPUTERS WHICHWERELESS EXPENSIVETHAN)"-MAINFRAMES4HECOMPANYAGGRESSIVELYSOLDTHEMERITSOFTHENEW RELATIONALSTYLEOFDATABASEMANAGEMENTANDEVENTUALLYRENAMEDITSELFAFTERITSFLAGSHIP PRODUCT4ODAY /RACLE#ORPORATIONISTHELEADINGVENDOROFRELATIONALDATABASE MANAGEMENTSYSTEMSANDAMAJORVENDOROFENTERPRISEAPPLICATIONSBASEDONTHE/RACLE DATABASE WITHANNUALSALESOFTENSOFBILLIONSOFDOLLARS 0ROFESSORSATTHE5NIVERSITYOF#ALIFORNIAS"ERKELEYCOMPUTERLABORATORIESWEREALSO RESEARCHINGRELATIONALDATABASESINTHEMID S,IKETHE)"-RESEARCHTEAM THEYBUILTA PROTOTYPEOFARELATIONAL$"-3ANDCALLEDTHEIRSYSTEM)NGRES4HE)NGRESPROJECTINCLUDEDA QUERYLANGUAGENAMED15%,THAT ALTHOUGHMORESTRUCTUREDTHAN31, WASLESS%NGLISH LIKE-ANYDATABASEPIONEERS KEYDATABASEDEVELOPERS ANDFOUNDERSOFDATABASESTARTUP COMPANIESTRACETHEIRHISTORYBACKTOTHE"ERKELEY)NGRESPROJECT )N SEVERALPROFESSORSLEFT"ERKELEYANDFOUNDED2ELATIONAL4ECHNOLOGY )NC TO BUILDACOMMERCIALVERSIONOF)NGRES WHICHWASANNOUNCEDIN)NGRESAND/RACLE QUICKLYBECAMEBITTERARCHRIVALS BUTTHEIRRIVALRYHELPEDTOCALLATTENTIONTORELATIONAL DATABASETECHNOLOGYINTHISEARLYSTAGE$ESPITEITSTECHNICALSUPERIORITYINMANYAREAS )NGRESBECAMEACLEARSECOND PLACEPLAYERINTHEMARKET COMPETINGAGAINSTTHE31, BASED CAPABILITIESANDTHEAGGRESSIVEMARKETINGANDSALESSTRATEGIES OF/RACLE4HEORIGINAL 15%,QUERYLANGUAGEWASEFFECTIVELYREPLACEDBY31,IN ATESTIMONYTOTHEMARKET POWEROFTHE31,STANDARD"YTHEMID S THE)NGRESTECHNOLOGYHADBEENSOLDTO #OMPUTER!SSOCIATES ALEADINGMAINFRAMESOFTWAREVENDOR#OMPUTER!SSOCIATESSOLD ITSINTERESTIN)NGRESTOAPRIVATEEQUITYCOMPANYIN
)"-õ0RODUCTS 7HILE/RACLEAND)NGRESRACEDTOBECOMECOMMERCIALPRODUCTS )"-S3YSTEM2PROJECTHAD ALSOTURNEDINTOANEFFORTTOBUILDACOMMERCIALPRODUCT NAMED31,$ATA3YSTEM31,$3 )"-ANNOUNCED31,$3INANDBEGANSHIPPINGTHEPRODUCTIN)N )"- ANNOUNCEDAVERSIONOF31,$3FOR6-#-3 ANOPERATINGSYSTEMTHATWASFREQUENTLY USEDON)"-MAINFRAMESINCORPORATEINFORMATIONCENTERAPPLICATIONS )N )"-ALSOINTRODUCED$ATABASE$" ANOTHERRELATIONAL$"-3FORITS MAINFRAMESYSTEMS$"OPERATEDUNDER)"-S-63OPERATINGSYSTEM THEWORKHORSE OPERATINGSYSTEMUSEDINLARGEMAINFRAMEDATACENTERS4HEFIRSTRELEASEOF$"BEGAN SHIPPINGIN AND)"-OFFICIALSHAILEDITASASTRATEGICPIECEOF)"-SOFTWARETECHNOLOGY $"HASSINCEBECOME)"-SFLAGSHIPRELATIONAL$"-3 ANDWITH)"-SWEIGHTBEHINDIT $"S31,BECAMETHEDEFACTOSTANDARDDATABASELANGUAGE$"TECHNOLOGYHASNOW MIGRATEDACROSSALL)"-PRODUCTLINES FROMPERSONALCOMPUTERSTONETWORKSERVERSTO MAINFRAMES)N )"-TOOKTHE$"CROSS PLATFORMSTRATEGYEVENFURTHER BYANNOUNCING $"VERSIONSFORSERVERSFROM)"-HARDWARERIVALS3UN-ICROSYSTEMSAND(EWLETT 0ACKARD $"ONMAINFRAMESREMAINSTHECENTERPIECEOF)"-SDATABASESTRATEGY HOWEVER ANDIS AVITALFORCEINENTERPRISECOMPUTING
#HAPTERçç
31,çINç0ERSPECTIVEç
#OMMERCIALõ!CCEPTANCE
0!24ç)
$URINGTHEFIRSTHALFOFTHES THERELATIONALDATABASEVENDORSSTRUGGLEDFORCOMMERCIAL ACCEPTANCEOFTHEIRPRODUCTS4HERELATIONALPRODUCTSHADSEVERALDISADVANTAGESCOMPARED WITHTHETRADITIONALDATABASEARCHITECTURES4HEPERFORMANCEOFRELATIONALDATABASESWAS SERIOUSLYINFERIORTOTHATOFTRADITIONALDATABASES%XCEPTFORTHE)"-PRODUCTS THERELATIONAL DATABASESCAMEFROMSMALLUPSTARTVENDORS!ND EXCEPTFORTHE)"-PRODUCTS THERELATIONAL DATABASESTENDEDTORUNONMINICOMPUTERSRATHERTHANON)"-MAINFRAMES 4HERELATIONALPRODUCTSDIDHAVEONEMAJORADVANTAGE HOWEVER4HEIRRELATIONALQUERY LANGUAGES31, 15%, ANDOTHERS ALLOWEDUSERSTOPOSEADHOCQUERIESTOTHEDATABASE ANDGETIMMEDIATEANSWERSWITHOUTWRITINGPROGRAMS!SARESULT RELATIONALDATABASES BEGANSLOWLYTURNINGUPININFORMATIONCENTERAPPLICATIONSASDECISION SUPPORTTOOLS "Y-AY /RACLEPROUDLYCLAIMEDTOHAVEOVERINSTALLATIONS)NGRESWASINSTALLED INACOMPARABLENUMBEROFSITES$"AND31,$3WEREALSOBEINGSLOWLYACCEPTEDAND COUNTEDTHEIRCOMBINEDINSTALLATIONSATSLIGHTLYOVERSITES $URINGTHELASTHALFOFTHES 31,ANDRELATIONALDATABASESWERERAPIDLYACCEPTEDAS THEDATABASETECHNOLOGYOFTHEFUTURE4HEPERFORMANCEOFTHERELATIONALDATABASEPRODUCTS IMPROVEDDRAMATICALLY)NGRESAND/RACLE INPARTICULAR LEAPFROGGED WITHEACHNEWVERSION CLAIMINGSUPERIORITYOVERTHECOMPETITORANDTWOORTHREETIMESTHEPERFORMANCEOFTHE PREVIOUSRELEASE)MPROVEMENTSINTHEPROCESSINGPOWEROFTHEUNDERLYINGCOMPUTER HARDWAREALSOHELPEDTOBOOSTPERFORMANCE -ARKETFORCESALSOBOOSTEDTHEPOPULARITYOF31,INTHELATES)"-STEPPEDUP ITSEVANGELISMOF31, POSITIONING$"ASTHEDATAMANAGEMENTSOLUTIONFORTHES 0UBLICATIONOFTHEFIRST!.3))3/STANDARDFOR31,31, INGAVE31,OFFICIAL STATUSASASTANDARD31,ALSOEMERGEDASASTANDARDON5.)8 BASEDCOMPUTERSYSTEMS WHOSEPOPULARITYACCELERATEDINTHES!SPERSONALCOMPUTERSBECAMEMOREPOWERFUL ANDWERELINKEDINLOCALAREANETWORKS,!.S THEYNEEDEDMORESOPHISTICATED DATABASEMANAGEMENT0#DATABASEVENDORSEMBRACED31,ASTHESOLUTIONTOTHESENEEDS ANDMINICOMPUTERDATABASEVENDORSMOVEDDOWNMARKETTOCOMPETEINTHEEMERGING 0#LOCALAREANETWORKMARKET 4HROUGHTHEEARLYS STEADILYIMPROVING31,IMPLEMENTATIONSANDDRAMATIC IMPROVEMENTSINPROCESSORSPEEDSMADE31,APRACTICALSOLUTIONFORTRANSACTIONPROCESSING APPLICATIONS31,BECAMEAKEYPARTOFTHECLIENTSERVERARCHITECTURETHATUSED0#S LOCAL AREANETWORKS ANDNETWORKSERVERSTOBUILDMUCHLOWER COSTINFORMATIONPROCESSING SYSTEMS7HENTHE)NTERNETANDTHEDOT COMBOOMBURSTUPONTHE)4LANDSCAPE 31,FOUND ANEWROLEASTHEDATABASELANGUAGEFOR)NTERNETAPPLICATIONSANDE COMMERCE 31,SSUPREMACYINTHEDATABASEWORLDHASNOTGONEUNCHALLENGED/BJECT ORIENTED PROGRAMMINGEMERGEDINTHESASTHEMETHODOFCHOICEFORAPPLICATIONSDEVELOPMENT ESPECIALLYFORPERSONALCOMPUTERSANDTHEIRGRAPHICALUSERINTERFACES4HEOBJECTMODEL WITHITSOBJECTS CLASSES METHODS ANDINHERITANCE DIDNOTFITWELLWITHTHERELATIONALMODEL OFTABLES ROWS ANDCOLUMNSOFDATA%ARLYhOBJECTDATABASEvPRODUCTSINCLUDED3ERVIO ,OGICS'EMSTONE 'RAPHAELS'BASE AND/NTOLOGICS6BASE!NEWGENERATIONOFVENTURE CAPITALnBACKEDOBJECTDATABASECOMPANIESSPRANGUPINTHEEARLYTOMID S HOPINGTO MAKERELATIONALDATABASESANDTHEIRVENDORSOBSOLETE JUSTAS31,HADDONETOTHEEARLIER NONRELATIONALVENDORS4HESEPRODUCTSINCLUDED)TASCA3YSTEMS)4!3#! &UJITSUS*ASMINE -ATISSE3OFTWARES-ATISSE /BJECTIVITYS/BJECTIVITY$" /NTOS )NCSRENAMEDFROM /NTOLOGIC /.4/3 /4ECHNOLOGYS/ ALONGWITHPERHAPSAHALFDOZENOTHERS(OWEVER 31,ANDTHERELATIONALMODELMORETHANWITHSTOODTHECHALLENGE!FEWOFTHESEPRODUCTS
ç
0ARTç)ç
!Nç/VERVIEWçOFç31,
REMAININTHEMARKETTODAY BUTMOSTHAVEBEENACQUIREDORSIMPLYFADEDAWAY&OREXAMPLE /4ECHNOLOGYMERGEDWITHSEVERALCOMPANIES WASACQUIREDBY)NFORMIX AND)NFORMIXWAS LATERACQUIREDBY)"-4OTALANNUALREVENUESFOROBJECT ORIENTEDDATABASESAREMEASUREDIN THELOWMILLIONSOFDOLLARS WHILE31,ANDRELATIONALDATABASESYSTEMS TOOLS ANDSERVICES PRODUCETENSOFBILLIONSOFDOLLARSOFSALESPERYEAR !S31,GREWTOADDRESSANEVER WIDERVARIETYOFDATAMANAGEMENTTASKS THEONE SIZE FITS ALLAPPROACHOFTHEEARLIER31,PRODUCTSSHOWEDSERIOUSSTRAIN3PECIALIZEDDATABASE SYSTEMSSPRANGUPTOSUPPORTDIFFERENTMARKETNEEDS/NEOFTHEFASTEST GROWINGSEGMENTS WASDATAWAREHOUSING WHEREDATABASESWEREUSEDTOSEARCHTHROUGHHUGEAMOUNTSOFDATA TODISCOVERUNDERLYINGTRENDSANDPATTERNS!SECONDMAJORTRENDWASTHEINCORPORATION OFNEWDATATYPESSUCHASMULTIMEDIADATA ANDOBJECT ORIENTEDPRINCIPLESINTO31, !THIRDIMPORTANTSEGMENTWASMOBILEDATABASESFORPORTABLEPERSONALCOMPUTERSTHATCOULD OPERATEWHENSOMETIMESCONNECTEDTO ANDSOMETIMESDISCONNECTEDFROM ACENTRALIZED DATABASESYSTEM!NOTHERIMPORTANTAPPLICATIONSEGMENTWASEMBEDDEDDATABASESFOR USEWITHININTELLIGENTDEVICESSUCHASNETWORKEQUIPMENT)N MEMORYDATABASESEMERGED ASANOTHERSEGMENT DESIGNEDFORVERYHIGHLEVELSOFPERFORMANCE ANDSTREAM ORIENTED DATABASESFOCUSEDONMANAGINGDATAASITFLOWEDOVERANETWORK $ESPITETHEEMERGENCEOFSUBSEGMENTSOFTHEDATABASEMARKET 31,HASREMAINEDA COMMONDENOMINATORACROSSTHEMALL&ORTYYEARSAFTERITFIRSTEMERGED 31,HASBROADENED TREMENDOUSLY AND31,SDOMINANCEASTHEDATABASESTANDARDREMAINSVERYSTRONG.EW CHALLENGESCONTINUETOEMERGETHENEEDTOINCORPORATE8-,ANDITSHIERARCHICALDATA MODELANDTHENEEDTOSUPPORTMASSIVEQUANTITIESOFDATATOSUPPORTDATAMANAGEMENTON THESCALEOFTHE)NTERNETARETWOOFTHEMOSTRECENT"UTTHEHISTORYOFTHEPASTYEARS INDICATESTHAT31,ANDTHERELATIONALMODELHAVEAPOWERFULABILITYTOEMBRACEANDADAPT TONEWDATAMANAGEMENTNEEDS
31,õ3TANDARDS /NEOFTHEMOSTIMPORTANTDEVELOPMENTSINTHEMARKETACCEPTANCEOF31,ISTHEEMERGENCE OF31,STANDARDS2EFERENCESTOhTHE31,STANDARDvUSUALLYMEANTHEOFFICIALSTANDARD ADOPTEDBYTHE!MERICAN.ATIONAL3TANDARDS)NSTITUTE!.3) ANDTHE)NTERNATIONAL /RGANIZATIONFOR3TANDARDIZATION)3/ (OWEVER THEREAREOTHERIMPORTANT31, STANDARDS INCLUDINGTHEDEFACTOSTANDARDFORSOMEPARTSOFTHE31,THATHAVEBEEN DEFINEDBY)"-S$"PRODUCTFAMILY AND/RACLES31,DIALECT WHICHHASADOMINANT INSTALLED BASEMARKETSHARE
4HEõ!.3))3/õ3TANDARDS 7ORKONTHEOFFICIAL31,STANDARDBEGANIN WHEN!.3)CHARGEDITS8( COMMITTEEWITHDEFININGASTANDARDRELATIONALDATABASELANGUAGE!TFIRST THE COMMITTEEDEBATEDTHEMERITSOFVARIOUSPROPOSEDDATABASELANGUAGES(OWEVER AS )"-SCOMMITMENTTO31,INCREASEDAND31,EMERGEDASADEFACTOSTANDARDINTHE MARKET THECOMMITTEESELECTED31,ASTHEIRRELATIONALDATABASELANGUAGEANDTURNED THEIRATTENTIONTOSTANDARDIZINGIT
#HAPTERçç
31,çINç0ERSPECTIVEç
0!24ç)
4HERESULTING!.3)STANDARDFOR31,WASLARGELYBASEDON$"31, ALTHOUGHIT CONTAINEDAFEWMAJORDIFFERENCESFROM$"!FTERSEVERALREVISIONS THESTANDARDWAS OFFICIALLYADOPTEDAS!.3)STANDARD8IN ANDASAN)3/STANDARDIN4HE !.3))3/STANDARDWASALSOADOPTEDASA&EDERAL)NFORMATION0ROCESSING3TANDARD&)03 BYTHE53GOVERNMENT4HISEARLY31,STANDARD SLIGHTLYREVISEDANDEXPANDEDIN IS USUALLYCALLEDTHE31,STANDARD OR31, -ANYOFTHE!.3)AND)3/STANDARDSCOMMITTEEMEMBERSWEREREPRESENTATIVESFROM DATABASEVENDORSWHOHADEXISTING31,PRODUCTS EACHIMPLEMENTINGASLIGHTLYDIFFERENT 31,DIALECT,IKEDIALECTSOFHUMANLANGUAGES THE31,DIALECTSWEREGENERALLYVERYSIMILAR TOONEANOTHER BUTWEREINCOMPATIBLEINTHEIRDETAILS)NMANYAREAS THECOMMITTEESIMPLY SIDESTEPPEDTHESEDIFFERENCESBYOMITTINGSOMEPARTSOFTHELANGUAGEFROMTHESTANDARDAND SPECIFYINGOTHERSAShIMPLEMENTER DEFINEDv4HESEDECISIONSALLOWEDEXISTING31, IMPLEMENTATIONSTOCLAIMBROADADHERENCETOTHERESULTING!.3))3/STANDARD BUTMADE THEINITIALSTANDARDRELATIVELYWEAK 4OADDRESSTHEHOLESINTHEORIGINALSTANDARD THE!.3)COMMITTEECONTINUEDITSWORK AND DRAFTSFORANEW MORERIGOROUSh31,vSTANDARDWERECIRCULATED5NLIKETHESTANDARD THE31,DRAFTSSPECIFIEDFEATURESCONSIDERABLYBEYONDTHOSEFOUNDINCURRENTCOMMERCIAL 31,PRODUCTS%VENMOREFAR REACHINGCHANGESWEREPROPOSEDFORAFOLLOW ON31,STANDARD )NADDITION THEDRAFTSTANDARDSATTEMPTEDTOOFFICIALLYSTANDARDIZEPARTSOFTHE31,WHERE DIFFERENTPROPRIETARYSTANDARDSHADLONGSINCEBEENSETBYTHEVARIOUSMAJOR$"-3BRANDS !SARESULT THEPROPOSED31,AND31,STANDARDSWEREAGOODDEALMORECONTROVERSIAL THANTHEINITIAL31,STANDARD4HE31,STANDARDWEAVEDITSWAYTHROUGHTHE!.3)APPROVAL PROCESSANDWASFINALLYAPPROVEDIN/CTOBER7HILETHEORIGINALSTANDARDHADLESS THANPAGES THEREVISEDSTANDARD OFFICIALLYCALLED31, HADNEARLYPAGES 4HESTANDARDSCOMMITTEEACKNOWLEDGEDTHELARGESTEPFROM31, TO31, BY EXPLICITLYCREATINGTHREELEVELSOF31,STANDARDSCOMPLIANCE4HELOWESTCOMPLIANCELEVEL %NTRY ,EVEL REQUIREDONLYMINIMALADDITIONALCAPABILITYBEYONDTHE31, STANDARD 4HEMIDDLEONE)NTERMEDIATE ,EVEL WASCREATEDASANACHIEVABLEMAJORSTEPBEYOND 31, BUTAVOIDEDTHEMOSTCOMPLEX SYSTEM DEPENDENT AND$"-3BRAND DEPENDENT ISSUES4HETHIRDCOMPLIANCELEVEL&ULL REQUIREDAFULLIMPLEMENTATIONOFALLAREAS4HROUGHOUT THEPUBLISHEDSTANDARD EACHDESCRIPTIONOFEACHFEATUREINCLUDESADEFINITIONOFTHESPECIFIC ASPECTSOFTHATFEATURETHATMUSTBESUPPORTEDTOACHIEVEVARIOUSLEVELSOFCOMPLIANCE 4ODAY SPECIALIZEDDATABASES SUCHASTHOSEUSEDINEMBEDDEDAPPLICATIONSORSUPPORTED BYOPENSOURCEEFFORTS STILLOFFERLOWERLEVELSOF31,STANDARDCOMPLIANCEINSOMEAREAS BUTALLOFTHEMAJORENTERPRISE CLASSDATABASESYSTEMSHAVEEVOLVEDTOFULLYSUPPORTTHE 31, STANDARD !FTERTHEADOPTIONOF31, 31,STANDARDSWORKTOOKADIFFERENTDIRECTION4HESINGLE STANDARDSCOMMITTEEBROKEUPINTOANUMBEROFDIFFERENTCOMMITTEES FOCUSEDONDIFFERENT EXTENSIONSTOTHELANGUAGE3OMEOFTHESE SUCHASSTOREDPROCEDURECAPABILITIES WERE ALREADYFOUNDINMANYCOMMERCIAL31,PRODUCTSANDPOSEDTHESAMESTANDARDIZATION CHALLENGESFACEDBY31,/THERS SUCHASPROPOSEDOBJECTEXTENSIONSTO31, WERENOTYET WIDELYAVAILABLEORFULLYIMPLEMENTED BUTTHEDATABASEVENDORSWEREUNDERSIGNIFICANT PRESSURETOADDRESSTHEMASOBJECT ORIENTEDTECHNOLOGIESAND8-,SURGEDINIMPORTANCE .EWREVISIONSTOTHESTANDARDWEREPRODUCEDINANDAGAININ AND 4HEREVISIONINCLUDEDSIGNIFICANTEXTENSIONTOTHE8-,PARTSOFTHESTANDARD
ç
0ARTç)ç
!Nç/VERVIEWçOFç31,
!TTHISWRITING THE!.3))3/STANDARDHADBEENEXPANDEDINTODEFINEDh0ARTSv !FEWOFTHEMWEREDROPPEDAFTERSOMEINITIALACTIVITY SOMEWEREMERGEDBACKINTOOTHER PARTS ANDSOMECONTINUEASSTAND ALONE PARALLELEFFORTSWITHINTHEOVERALLSTANDARD v 0ARTn31,&RAMEWORKCONTAINSCOMMONDEFINITIONSANDSERVESASAhTABLEOF CONTENTSvFORTHEOTHERPARTS v 0ARTn31,&OUNDATIONISTHELARGESTPARTANDCARRIESTHEMAINSTREAMDEFINITIONOF THE31,STATEMENTSTHATDEFINETHESTRUCTUREOFADATABASEANDMANIPULATEDATA)TIS THEDESCENDANTOFTHEEARLY31, AND31, VERSIONSOFTHESTANDARD)THASBEEN SIGNIFICANTLYEXTENDEDTOINCLUDE31,STRUCTURESFORBUSINESSANALYTICS v 0ARTn31,#,)#ALL,EVEL)NTERFACE DESCRIBESTHEPROCEDURALCALL LEVELINTERFACE BETTERKNOWNAS-ICROSOFTS/$"#STANDARD)TDEBUTEDIN v 0ARTn31,03-0ERSISTENT3TORED-ODULES DESCRIBESPROCEDURALEXTENSIONS TO31, PARALLELINGTHEFEATURESFOUNDINPOPULAR31,PROCEDURALLANGUAGESLIKE /RACLES0,31, v 0ARTn31,"INDINGSDESCRIBEDHOW31,ISEMBEDDEDINOTHERPROCEDURAL LANGUAGES4HISPARTWASMERGEDINTO0ARTn31,&OUNDATIONSINTHE31, VERSIONOFTHESTANDARD v 0ARTn31,4RANSACTIONWASFOCUSEDONEXTENSIONSTOTHE8!DISTRIBUTEDTRANSACTION STANDARD BUTWASDROPPED v 0ARTn31,4EMPORALWASFOCUSEDONEXTENDING31,TODEALWITHTIME ORIENTED DATA BUTWASDROPPED v 0ARTn31,/BJECTSHELDTHEOBJECT ORIENTEDEXTENSIONSTO31,DURINGTHE DEVELOPMENTOF31,4HESEEXTENSIONSWEREMERGEDBACKINTO0ARTn&OUNDATION IN31, v 0ARTn31,-%$-ANAGEMENTOF%XTERNAL$ATA ADDSFACILITIESTOALLOW31,TO PROCESSNONRELATIONALDATASOURCES ANDAPPEAREDIN31, v 0ARTn31,/,"/BJECT,ANGUAGE"INDINGS DESCRIBESACCESSTO31,FROM*AVA )TISRELATEDTO*$"#ANDEMBEDDED31,FOR*AVA ANDAPPEAREDIN31, v 0ARTn31,3CHEMATACONTAINSSTANDARDSFORTHEhDATABASECATALOGvORSYSTEM INFORMATIONTABLESTHATSELF DESCRIBEADATABASE4HISSPECIFICATIONWASIN0ARTIN 31, BUTWASSEPARATEDOUTINTOITSOWNPARTIN31, v 0ARTn31,2EPLICATIONWASSTARTEDTODEFINESTANDARDSFORHOWREPLICATIONFROM ONE31,DATABASETOANOTHERISSPECIFIED BUTWASDROPPED v 0ARTn31,*24*AVA2OUTINESAND4YPES DESCRIBESROUTINESANDTYPESUSEDIN THE*AVALANGUAGETOACCESS31,DATABASES ANDFIRSTAPPEAREDIN31, v 0ARTn31,8-,DESCRIBESHOW%XTENSIBLE-ARKUP,ANGUAGE8-, IS INTEGRATEDINTOTHE31,LANGUAGE)TFIRSTAPPEAREDIN31,ANDHASBEEN SIGNIFICANTLYEXPANDEDSINCE &ROMAFEWHUNDREDPAGESDESCRIBINGTHECOMMONCOREFEATURESOFTHE31,LANGUAGE IN THE!.3))3/31,STANDARDHASTHUSGROWNDRAMATICALLYINCOMPLEXITY SCOPEAND LENGTH4HEhREALv31,STANDARD OFCOURSE ISTHE31,IMPLEMENTEDINPRODUCTSTHATARE
#HAPTERçç
31,çINç0ERSPECTIVEç
/THERõ%ARLYõ31,õ3TANDARDS !LTHOUGHITWASTHEMOSTWIDELYRECOGNIZED THE!.3))3/STANDARDWASNOTTHEONLY STANDARDINTHEEARLYDAYSOF31,8/0%. A%UROPEANVENDORGROUP ALSOADOPTED31, ASPARTOFITSSUITEOFSTANDARDSFORAPORTABLEAPPLICATIONENVIRONMENTBASEDON5.)84HE 8/0%.STANDARDSPLAYEDAMAJORROLEINTHEDEVELOPMENTOFTHE%UROPEANCOMPUTERMARKET WHEREPORTABILITYAMONGCOMPUTERSYSTEMSFROMDIFFERENTVENDORSWASAKEYCONCERN )"-ALSOINCLUDED31,INTHESPECIFICATIONOFITSBOLDS3YSTEMS!PPLICATION !RCHITECTURE3!! BLUEPRINT PROMISINGTHATALLOFITS31,PRODUCTSWOULDEVENTUALLYMOVE TOTHIS3!!31,DIALECT!LTHOUGH3!!FAILEDTOACHIEVEITSPROMISEOFUNIFYINGTHE)"- PRODUCTLINE THEMOMENTUMTOWARDAUNIFIED)"-31,CONTINUED7ITHITSMAINFRAME$" DATABASEASTHEFLAGSHIP )"-INTRODUCED$"IMPLEMENTATIONSFOR/3 ITSPERSONAL COMPUTEROPERATINGSYSTEM ANDFORITS23LINEOF5.)8 BASEDWORKSTATIONSAND SERVERS4HEEXPANSIONOF$"NOTONLYACROSSHARDWARESYSTEMS BUTALSOACROSSMANY DIFFERENTTYPESOFDATA WASEMBODIEDIN)"-SNAMINGONEOFITSLATERIMPLEMENTATIONS $"5NIVERSAL$ATABASE OR5$"
/$"#õANDõTHEõ31,õ!CCESSõ'ROUP !NIMPORTANTAREAOFDATABASETECHNOLOGYNOTADDRESSEDBYTHEEARLIEROFFICIALSTANDARDSIS DATABASEINTEROPERABILITYTHEMETHODSBYWHICHDATACANBEEXCHANGEDAMONGDIFFERENT DATABASES USUALLYOVERANETWORK)N AGROUPOFVENDORSFORMEDTHE31,!CCESS 'ROUPTOADDRESSTHISPROBLEM4HERESULTING31,!CCESS'ROUPSPECIFICATIONFOR2EMOTE $ATABASE!CCESS2$! WASPUBLISHEDIN5NFORTUNATELY THE2$!SPECIFICATIONWAS CLOSELYTIEDTOTHE/3)NETWORKINGPROTOCOLS WHICHLOSTTHENETWORKINGBATTLETOTHE )NTERNETS4#0)0SUITE SO2$!WASNEVERWIDELYIMPLEMENTED !SECONDSTANDARDFROMTHE31,!CCESS'ROUPHADFARMOREMARKETIMPACT!T -ICROSOFTSURGINGANDINSISTENCE THE31,!CCESS'ROUPEXPANDEDITSFOCUSTOINCLUDEA CALL LEVELINTERFACEFOR31,"ASEDONADRAFTFROM-ICROSOFT THERESULTING#ALL ,EVEL )NTERFACE#,) SPECIFICATIONWASPUBLISHEDIN-ICROSOFTSOWN/PEN$ATABASE #ONNECTIVITY/$"# SPECIFICATION BASEDONTHE#,)STANDARD WASPUBLISHEDTHESAME YEAR7ITHTHEMARKETPOWEROF-ICROSOFTBEHINDIT ANDTHEhOPENSTANDARDSvBLESSINGOF THE31,!CCESS'ROUP /$"#EMERGEDASTHEDEFACTOSTANDARDINTERFACEFOR0#ACCESSTO 31,DATABASES!PPLEAND-ICROSOFTANNOUNCEDANAGREEMENTTOSUPPORT/$"#ON -ACINTOSHAND7INDOWSINTHESPRINGOF GIVING/$"#INDUSTRYSTANDARDSTATUSIN BOTHPOPULARGRAPHICALUSERINTERFACEENVIRONMENTS/$"#IMPLEMENTATIONSFOR5.)8 BASEDSYSTEMSSOONFOLLOWED)N THE/$"#INTERFACEEFFECTIVELYBECAMEAN!.3) )3/STANDARD WITHTHEPUBLICATIONOFTHE31,#ALL ,EVEL)NTERFACE#,) STANDARD /VERTHEPASTDECADE /$"#HASCONTINUEDTOEVOLVE BUTATASLOWERPACE-ICROSOFTSTILL SUPPORTS/$"# BUTHASFOCUSEDMAJOREFFORTINTOBUILDINGHIGHER LEVEL MOREOBJECT ORIENTED
0!24ç)
BROADLYACCEPTEDBYTHEMARKETPLACE&ORTHEMOSTPART PROGRAMMERSANDUSERSTENDTO STICKWITHTHOSEPARTSOFTHELANGUAGETHATARETHESAMEACROSSABROADRANGEOFPRODUCTS 4HEINNOVATIONOFTHEDATABASEVENDORSCONTINUESTODRIVETHEINVENTIONOFMOSTNEW31, EXTENSIONS3OMEOFTHESEFAILTOGAINTRACTIONANDFADEFROMTHELANGUAGEOVERTIME /THERSAREINTRODUCEDANDREMAINYEARSLATERONLYFORBACKWARDCOMPATIBILITYOTHERSFIND COMMERCIALSUCCESSANDMOVEINTOTHEMAINSTREAMANDEVENTUALLYFINDTHEIRWAYINTOTHE OFFICIALSTANDARD
ç
0ARTç)ç
!Nç/VERVIEWçOFç31,
INTERFACESFORUNIVERSALDATABASEACCESS(OWEVER /$"#STILLPLAYSAMAJORROLEPROVIDING PORTABILITYACROSSDATABASESFORMAJORENTERPRISEAPPLICATIONSANDFORDATABASETOOLS)TS QUITECOMMONFORADATABASETOOLORANENTERPRISEAPPLICATIONTOSUPPORTSPECIFIChDRIVERSv THATOPTIMIZEITFORDIRECTACCESSTO/RACLEAND$"AND31,3ERVERUSINGTHEIRPROPRIETARY CALL LEVELINTERFACES4HEAPPLICATIONWILLTYPICALLYINCLUDEANADDITIONALDRIVERTHATUSES /$"#ASAWAYTOSUPPORTABROADRANGEOFOTHERDATABASES"ECAUSESOMANYAPPLICATIONS ANDTOOLSADOPTTHISAPPROACH NEARLYALLDATABASEVENDORSOFFER/$"#ACCESS SOMETIMESAS THEIRPRIMARYCALL LEVELINTERFACEANDSOMETIMESASASUPPLEMENTTOAHIGHER PERFORMANCE PROPRIETARYINTERFACE
*$"#õANDõ!PPLICATIONõ3ERVERS 4HEEXPLOSIVEPOPULARITYOFTHE)NTERNETDROVETHEFURTHERDEVELOPMENTOFDATABASEACCESS STANDARDSTOSUPPORTTHEACCOMPANYINGRISEOFTHEOBJECT ORIENTED*AVAPROGRAMMING LANGUAGE*AVAEVENTUALLYBECAMETHESTANDARDLANGUAGEFORBUILDING)NTERNET DELIVERED APPLICATIONSTHATRANON*AVA BASEDAPPLICATIONSERVERS3UN-ICROSYSTEMS THEINVENTOROF *AVA LEDTHEEFFORTTOSTANDARDIZETHEUSEOF*AVAFORAPPLICATIONSERVERSTHROUGHTHE*AVA %NTERPRISE%DITION*%% SPECIFICATION*%%INCLUDED*AVA$ATABASE#ONNECTIVITY*$"# ASITSSTANDARDFOR*AVAACCESSTORELATIONALDATABASES5NLIKEDATABASEACCESSFORTHE# PROGRAMMINGLANGUAGE WHEREPROPRIETARYCALL LANGUAGEINTERFACESPREDATED/$"#BY MANYYEARS THE*$"#STANDARDWASDEVELOPEDRELATIVELYEARLYINTHEEXPLOSIONOF*AVA POPULARITY!SARESULT PROPRIETARY*AVAINTERFACESFAILEDTOEMERGE AND*$"#ISTHE STANDARDFOR31,ACCESSFROMTHE*AVALANGUAGE
31,õANDõ0ORTABILITY 4HEEXISTENCEOFPUBLISHED31,STANDARDSHASSPAWNEDQUITEAFEWEXAGGERATEDCLAIMS ABOUT31,ANDAPPLICATIONSPORTABILITY$IAGRAMSSUCHASTHEONEIN&IGURE ARE FREQUENTLYDRAWNTOSHOWHOWANAPPLICATIONUSING31,CANWORKINTERCHANGEABLYWITH ANY31, BASEDDATABASEMANAGEMENTSYSTEM)NFACT THEDIFFERENCESBETWEEN31,DIALECTS ARESIGNIFICANTENOUGHTHATANAPPLICATIONMUSTOFTENBEMODIFIEDWHENMOVEDFROMONE
1, ÊÎ£Ê /
iÊ-+Ê«ÀÌ>LÌÞÊÞÌ
#HAPTERçç
31,çINç0ERSPECTIVEç
v $ATATYPES 4HE31,STANDARDHASEVOLVEDTOADDRESSANEVER BROADERSETOFDATA TYPES BUTVENDORSKEEPADDINGNEWONES%VENOLDERDATATYPESCANCAUSE PORTABILITYISSUES/RACLES.5-"%2DATATYPE FOREXAMPLE ISTHEMOSTWIDELY USEDTOREPRESENTNUMERICDATAINAN/RACLEDATABASE ANDITSPECULIARITIESARE COMPLETELYUNIQUETO/RACLE v "ACKWARDCOMPATIBILITY )TSNOTUNCOMMONFORENTERPRISEAPPLICATIONSTOSTILLBE INUSEORYEARSAFTERTHEYWEREFIRSTWRITTEN LONGAFTERTHEPROGRAMMERSWHO DEVELOPEDTHEMAREGONE4HESEPROGRAMSTENDTOBECOMEhUNTOUCHABLE vSINCETHE DETAILEDKNOWLEDGEOFHOWTHEYWORKHASOFTENBEENLOST,ARGESECTIONSOFTHESE PROGRAMSMAYDEPENDONOLDER PROPRIETARY31,FEATURES ANDDATABASEVENDORS AREFORCEDTOMAINTAINBACKWARDCOMPATIBILITYWITHTHEMORRISKhBREAKINGvTHE APPLICATIONS4HISPERPETUATESDIALECTDIFFERENCESTHATINHIBITPORTABILITY v 3YSTEMTABLES 4HE31,STANDARDADDRESSEDTHESYSTEMTABLESTHATPROVIDE INFORMATIONABOUTTHESTRUCTUREOFTHEDATABASEITSELFSTARTINGWITHTHE31, STANDARD"YTHISTIME DATABASEVENDORSHADBUILTTHEIROWNPROPRIETARYSYSTEM TABLESTRUCTURES ANDTHEYHAVECONTINUEDTOEVOLVETHEM OFTENCONTAININGUSEFUL INFORMATIONTHATGOESWELLBEYONDTHEITEMSSPECIFIEDINTHESTANDARD!PPLICATIONS THATUSETHESEPROPRIETARYSYSTEMTABLESARENOTPORTABLE v 0ROGRAMMATICINTERFACE 4HEEARLY31,STANDARDSPECIFIEDANABSTRACTTECHNIQUE FORUSING31,FROMWITHINANAPPLICATIONSPROGRAMWRITTENIN#/"/, # &/242!. ANDOTHERPROGRAMMINGLANGUAGES WHICHWASNOTWIDELYADOPTED4HE31, #,)STANDARDFINALLYADDRESSEDPROGRAMMATIC31,ACCESS BUTBYTHEN COMMERCIAL $"-3PRODUCTSHADPOPULARIZEDPROPRIETARYINTERFACESANDDEEPLYEMBEDDED THEMINHUNDREDSOFTHOUSANDSOFUSERAPPLICATIONSANDAPPLICATIONPACKAGES !LTHOUGHSTANDARD!0)SARENOWWIDELYSUPPORTED MOSTDATABASEVENDORSSTILL MAINTAINPROPRIETARYINTERFACESTHATOFFERHIGHERPERFORMANCEANDRICHER FUNCTIONALITY WITHTHESIDE EFFECTOFLOCKINGINAPPLICATIONS v 3EMANTICDIFFERENCES "ECAUSETHESTANDARDSSPECIFYCERTAINDETAILSAS IMPLEMENTER DEFINED ITSPOSSIBLETORUNTHESAMEQUERYAGAINSTTWODIFFERENT CONFORMING31,IMPLEMENTATIONSANDPRODUCETWODIFFERENTSETSOFQUERYRESULTS %XAMPLESOFTHESEDIFFERENCESCANBEFOUNDINAREASLIKETHEHANDLINGOF.5,, VALUES COLUMNFUNCTIONS ANDDUPLICATEROWELIMINATION v 2EPLICATIONANDDATAMIRRORING -ANYPRODUCTIONDATABASESCONTAINTABLESTHAT AREREPLICATEDINTWOORMOREGEOGRAPHICALLYSEPARATEDDATABASES TOPROVIDEHIGH AVAILABILITYORDISASTERRECOVERY TOSPREADOUTPROCESSINGWORKLOADS ORTOREDUCE NETWORKDELAYS4HETECHNIQUESFORSPECIFYINGANDMANAGINGTHESEREPLICATION SCHEMESAREPROPRIETARYTOEACHDATABASESYSTEM ANDATTEMPTSTOSTANDARDIZE REPLICATIONHAVEBEENABANDONED
0!24ç)
31,DATABASETOANOTHER/VERTIME THECOREOFTHELANGUAGEHASBECOMEMORESTANDARD ANDHASBROADENED BUTATTHESAMETIME NEWCAPABILITIESHAVEBEENADDEDBYTHEDATABASE VENDORS OFTENWITHPROPRIETARYLANGUAGEEXTENSIONS%XAMPLESOFAREASWHERETHESE DIFFERENCESARISEINCLUDE
ç
0ARTç)ç
!Nç/VERVIEWçOFç31,
v %RRORCODES 4HE31, STANDARDINTRODUCEDSTANDARDERRORCODESTOBERETURNED WHEN31,DETECTSANERROR BUTALLOFTHEPOPULARDATABASESYSTEMSHADLONGBEEN USINGTHEIROWNPROPRIETARYERRORCODESBYTHISTIME%VENWHENUSEDINAMODE WITHSTANDARDERRORCODES PROPRIETARYEXTENSIONSCANGENERATETHEIROWNERRORSTHAT AREOUTSIDETHESPECIFIEDSTANDARDCODES v $ATABASESTRUCTURE 4HE31, STANDARDSPECIFIEDTHE31,LANGUAGETOBEUSED ONCEAPARTICULARDATABASEHASBEENOPENEDANDISREADYFORPROCESSING4HEDETAILS OFDATABASENAMINGANDHOWTHEINITIALCONNECTIONTOTHEDATABASEISESTABLISHED WEREALREADYDIVERSEANDNOTPORTABLEBYTHETIMETHISINITIALSTANDARDWASWRITTEN 4HE31, STANDARDCREATEDMOREUNIFORMITY BUTTHESTANDARDCANNOTCOMPLETELY MASKTHESEIMPLEMENTATIONDETAILS $ESPITETHESEDIFFERENCES COMMERCIALDATABASETOOLSBOASTINGPORTABILITYACROSSSEVERAL DIFFERENTBRANDSOF31,DATABASESBEGANTOEMERGEINTHEEARLYSANDAREBROADLY POPULARTODAY)NPRACTICE THESETOOLSALWAYSINCLUDESPECIFICDRIVERSFORCOMMUNICATING WITHEACHOFTHEMAJOR$"-3BRANDS WHICHGENERATETHEAPPROPRIATE31,DIALECT HANDLE DATATYPECONVERSION TRANSLATEERRORCODES ANDSOON
31,õANDõ.ETWORKING 4HEDRAMATICGROWTHOFCOMPUTERNETWORKINGINTHESHADAMAJORIMPACTONDATABASE MANAGEMENTANDGAVE31,ANEWPROMINENCE!SNETWORKSBECAMEMORECOMMON APPLICATIONSTHATTRADITIONALLYRANONACENTRALMINICOMPUTERORMAINFRAMEMOVEDTOLOCALAREA NETWORKSOFDESKTOPWORKSTATIONSANDSERVERS)NTHESENETWORKS 31,PLAYSACRUCIALROLEAS THELINKBETWEENANAPPLICATIONRUNNINGONADESKTOPWORKSTATIONWITHAGRAPHICALUSER INTERFACEANDTHE$"-3THATMANAGESSHAREDDATAONACOST EFFECTIVESERVER-ORERECENTLY THE EXPLODINGPOPULARITYOFTHE)NTERNETANDTHE7ORLD7IDE7EBHASREINFORCEDTHENETWORKROLE FOR31,)NTHEEMERGINGTHREE TIER)NTERNETARCHITECTURE 31,ONCEAGAINPROVIDESTHELINK BETWEENTHEAPPLICATIONLOGICNOWRUNNINGINTHEMIDDLETIER ONANAPPLICATIONSERVERORWEB SERVER ANDTHEDATABASERESIDINGINTHEBACK ENDTIER4HENEXTFEWSECTIONSDISCUSSTHE EVOLUTIONOFDATABASENETWORKARCHITECTURESANDTHEROLEOF31,INEACHONE
#ENTRALIZEDõ!RCHITECTURE &IGURE SHOWSTHETRADITIONALDATABASEARCHITECTUREUSEDBY$"ANDTHEORIGINAL MINICOMPUTERDATABASESSUCHAS/RACLEAND)NGRES)NTHISARCHITECTURE THE$"-3ANDTHE PHYSICALDATABOTHRESIDEONACENTRALMINICOMPUTERORMAINFRAMESYSTEM ALONGWITH THEAPPLICATIONPROGRAMTHATACCEPTSINPUTFROMTHEUSERSTERMINALANDDISPLAYSDATAON THEUSERSSCREEN4HEAPPLICATIONPROGRAMCOMMUNICATESWITHTHE$"-3USING31,
1, ÊÎÓÊ >Ì>L>ÃiÊ>>}iiÌÊÊ>ÊViÌÀ>âi`Ê>ÀV
ÌiVÌÕÀi
#HAPTERçç
31,çINç0ERSPECTIVEç
&ILEõ3ERVERõ!RCHITECTURE 4HEINTRODUCTIONOFPERSONALCOMPUTERSANDLOCALAREANETWORKSLEDTOTHEDEVELOPMENTOF THEFILESERVERARCHITECTURE SHOWNIN&IGURE )NTHISARCHITECTURE ANAPPLICATIONRUNNING ONAPERSONALCOMPUTERCANTRANSPARENTLYACCESSDATALOCATEDONAFILESERVER WHICHSTORES SHAREDFILES7HENA0#APPLICATIONREQUESTSDATAFROMASHAREDFILE THENETWORKINGSOFTWARE AUTOMATICALLYRETRIEVESTHEREQUESTEDBLOCKOFTHEFILEFROMTHESERVER%ARLY0#DATABASES SUCHASD"!3%ANDLATER-ICROSOFTS!CCESS SUPPORTEDTHISFILESERVERAPPROACH WITHEACH PERSONALCOMPUTERRUNNINGITSOWNCOPYOFTHE$"-3SOFTWARE &ORTYPICALQUERIESTHATRETRIEVEONLYONEROWORAFEWROWSFROMTHEDATABASE THIS ARCHITECTUREPROVIDESEXCELLENTPERFORMANCE BECAUSEEACHUSERHASTHEFULLPOWEROFA PERSONALCOMPUTERRUNNINGITSOWNCOPYOFTHE$"-3(OWEVER CONSIDERTHEQUERYMADE INTHEPREVIOUSEXAMPLE"ECAUSETHEQUERYREQUIRESASEQUENTIALSCANOFTHEDATABASE THE $"-3REPEATEDLYREQUESTSBLOCKSOFDATAFROMTHEDATABASE WHICHISPHYSICALLYLOCATED ACROSSTHENETWORKONTHESERVER%VENTUALLY EVERYBLOCKOFTHEFILEWILLBEREQUESTEDAND SENTACROSSTHENETWORK/BVIOUSLY THISARCHITECTUREPRODUCESVERYHEAVYNETWORKTRAFFIC ANDSLOWPERFORMANCEFORQUERIESOFTHISTYPE
1, ÊÎÎÊ >Ì>L>ÃiÊ>>}iiÌÊÊ>ÊwiÊÃiÀÛiÀÊ>ÀV
ÌiVÌÕÀi
0!24ç)
3UPPOSETHEUSERTYPESAQUERYTHATREQUIRESASEQUENTIALSEARCHOFADATABASE SUCHASA REQUESTTOFINDTHEAVERAGEORDERSIZEFORALLORDERS4HE$"-3RECEIVESTHEQUERY SCANS THROUGHTHEDATABASEFETCHINGEACHRECORDOFDATAFROMTHEDISKORMEMORY CALCULATESTHE AVERAGE ANDDISPLAYSTHERESULTONTHETERMINALSCREEN"OTHTHEAPPLICATIONPROCESSINGAND THEDATABASEPROCESSINGOCCURONTHECENTRALCOMPUTER SOEXECUTIONOFTHISTYPEOFQUERY ANDINFACT ALLKINDSOFQUERIES ISVERYEFFICIENT 4HEDISADVANTAGEOFTHECENTRALIZEDARCHITECTUREISSCALABILITY!SMOREANDMOREUSERS AREADDED EACHOFTHEMADDSAPPLICATIONPROCESSINGWORKLOADTOTHESYSTEM"ECAUSETHE SYSTEMISSHARED EACHUSEREXPERIENCESDEGRADEDPERFORMANCEASTHESYSTEMBECOMESMORE HEAVILYLOADED
ç
0ARTç)ç
!Nç/VERVIEWçOFç31,
#LIENT3ERVERõ!RCHITECTURE &IGURE SHOWSTHENEXTSTAGEOFNETWORKDATABASEEVOLUTIONTHECLIENTSERVERDATABASE ARCHITECTURE)NTHISSCHEME PERSONALCOMPUTERSARECOMBINEDINALOCALAREANETWORKWITH ADATABASESERVERTHATSTORESSHAREDDATABASES4HEFUNCTIONSOFTHE$"-3ARESPLITINTOTWO PARTS$ATABASEFRONT ENDS SUCHASINTERACTIVEQUERYTOOLS REPORTWRITERS ANDAPPLICATION PROGRAMS RUNONTHEPERSONALCOMPUTER4HEBACK ENDDATABASEENGINETHATSTORESAND MANAGESTHEDATARUNSONTHESERVER!STHECLIENTSERVERARCHITECTUREGREWINPOPULARITY DURINGTHES 31,BECAMETHESTANDARDDATABASELANGUAGEFORCOMMUNICATIONBETWEEN THEFRONT ENDTOOLSANDTHEBACK ENDENGINEINTHISARCHITECTURE #ONSIDERONCEMORETHEQUERYREQUESTINGTHEAVERAGEORDERSIZE)NTHECLIENTSERVER ARCHITECTURE THEQUERYTRAVELSACROSSTHENETWORKTOTHEDATABASESERVERASA31,REQUEST4HE DATABASEENGINEONTHESERVERPROCESSESTHEREQUESTANDSCANSTHEDATABASE WHICHALSORESIDES ONTHESERVER7HENTHERESULTISCALCULATED THEDATABASEENGINESENDSITBACKACROSSTHENETWORK ASASINGLEREPLYTOTHEINITIALREQUEST ANDTHEFRONT ENDAPPLICATIONDISPLAYSITONTHE0#SCREEN 4HECLIENTSERVERARCHITECTUREREDUCESTHENETWORKTRAFFICANDSPLITSTHEDATABASEWORKLOAD 5SER INTENSIVEFUNCTIONS SUCHASHANDLINGINPUTANDDISPLAYINGDATA ARECONCENTRATEDONTHE USERS0#$ATA INTENSIVEFUNCTIONS SUCHASFILE)/ANDQUERYPROCESSING ARECONCENTRATEDIN THEDATABASESERVER-OSTIMPORTANTLY THE31,PROVIDESAWELL DEFINEDINTERFACEBETWEENTHE FRONT ENDANDBACK ENDSYSTEMS COMMUNICATINGDATABASEACCESSREQUESTSINANEFFICIENTMANNER "YTHEMID S THESEADVANTAGESMADETHECLIENTSERVERARCHITECTURETHEMOST POPULARSCHEMEFORIMPLEMENTINGNEWAPPLICATIONS!LLOFTHEMOSTPOPULAR$"-3 PRODUCTS/RACLE )NFORMIX 3YBASE 31,3ERVER $" ANDMANYMOREOFFEREDCLIENT SERVERCAPABILITY4HEDATABASEINDUSTRYGREWTOINCLUDEMANYCOMPANIESOFFERINGTOOLS FORBUILDINGCLIENTSERVERAPPLICATIONS3OMEOFTHESECAMEFROMTHEDATABASECOMPANIES THEMSELVESOTHERSCAMEFROMINDEPENDENTCOMPANIES ,IKEALLARCHITECTURES CLIENTSERVERHADITSDISADVANTAGES4HEMOSTSERIOUSOFTHESEWAS THEPROBLEMOFMANAGINGTHEAPPLICATIONSSOFTWARETHATWASNOWDISTRIBUTEDACROSSHUNDREDS ORTHOUSANDSOFDESKTOP0#SINSTEADOFRUNNINGONACENTRALMINICOMPUTERORMAINFRAME4O UPDATEANAPPLICATIONPROGRAMINALARGECOMPANY THEINFORMATIONSYSTEMSDEPARTMENTHADTO UPDATETHOUSANDSOF0#SYSTEMS ONEATATIME4HESITUATIONWASEVENWORSEIFCHANGESTOTHE APPLICATIONPROGRAMHADTOBESYNCHRONIZEDWITHCHANGESTOOTHERAPPLICATIONS ORTOTHE
1, ÊÎ{Ê >Ì>L>ÃiÊ>>}iiÌÊÊ>ÊViÌÉÃiÀÛiÀÊ>ÀV
ÌiVÌÕÀi
#HAPTERçç
31,çINç0ERSPECTIVEç
-ULTITIERõ!RCHITECTURE 7ITHTHEEMERGENCEOFTHE)NTERNETANDESPECIALLYTHE7ORLD7IDE7EB NETWORKDATABASE ARCHITECTURETOOKANOTHERSTEPINITSEVOLUTION!TFIRST THE7EBWASUSEDTOACCESSBROWSE STATICDOCUMENTSANDEVOLVEDOUTSIDEOFTHEDATABASEWORLD"UTASTHEUSEOFWEBBROWSERS BECAMEWIDESPREAD ITWASNTLONGBEFORECOMPANIESTHOUGHTABOUTUSINGTHEMASASIMPLE WAYTOPROVIDEACCESSTOCORPORATEDATABASESASWELL&OREXAMPLE SUPPOSEACOMPANY STARTSUSINGTHE7EBTOPROVIDEPRODUCTINFORMATIONTOITSCUSTOMERSBYMAKINGPRODUCT DESCRIPTIONSANDGRAPHICSAVAILABLEONITSWEBSITE!NATURALNEXTSTEPISTOGIVECUSTOMERS ACCESSTOCURRENTPRODUCTAVAILABILITYINFORMATIONTHROUGHTHESAMEWEBBROWSERINTERFACE 4HISREQUIRESLINKINGTHEWEBSERVERTOTHEDATABASESYSTEMTHATSTORESTHECONSTANTLY CHANGING CURRENTPRODUCTINVENTORYLEVELS 4HEMETHODSUSEDTOLINKWEBSERVERSAND$"-3SYSTEMSEVOLVEDRAPIDLYINTHELATE SANDEARLYS ANDHAVECONVERGEDONTHETHREE TIERNETWORKARCHITECTURESHOWNIN &IGURE 4HEUSERINTERFACEISAWEBBROWSERRUNNINGONA0#ORSOMEOTHERTHINCLIENT
1, ÊÎxÊ >Ì>L>ÃiÊ>>}iiÌÊÊ>ÊÌ
ÀiiÌiÀÊÌiÀiÌÊ>ÀV
ÌiVÌÕÀi
0!24ç)
$"-3SYSTEMITSELF)NADDITION WITHPERSONALCOMPUTERSONUSERSDESKS USERSTENDEDTOADD NEWPERSONALSOFTWAREOFTHEIROWNORTOCHANGETHECONFIGURATIONOFTHEIRSYSTEMS3UCH CHANGESOFTENDISRUPTEDEXISTINGAPPLICATIONS ADDINGTOTHESUPPORTBURDEN#OMPANIES DEVELOPEDSTRATEGIESTODEALWITHTHESEISSUES BUTBYTHELATES THEREWASGROWINGCONCERN ABOUTTHEMANAGEABILITYOFCLIENTSERVERAPPLICATIONSONLARGE DISTRIBUTED0#NETWORKS
ç
0ARTç)ç
!Nç/VERVIEWçOFç31,
DEVICE SUCHASSMARTPHONE INTHEFRONT ENDTIER)TCOMMUNICATESWITHAWEBSERVERINTHE MIDDLETIER7HENTHEUSERREQUESTISFORSOMETHINGMORECOMPLEXTHANASIMPLEWEBPAGE THEWEBSERVERPASSESTHEREQUESTTOANAPPLICATIONSERVER WHOSEROLEISTOHANDLETHE BUSINESSLOGICREQUIREDTOPROCESSTHEREQUEST/FTENTHEREQUESTWILLINVOLVEACCESSTOAN EXISTINGLEGACY APPLICATIONRUNNINGONAMAINFRAMESYSTEMORTOACORPORATEDATABASE 4HESESYSTEMSRUNINTHEBACK ENDTIEROFTHEARCHITECTURE !SWITHTHECLIENTSERVERARCHITECTURE 31,ISSOLIDLYENTRENCHEDASTHESTANDARD DATABASELANGUAGEFORCOMMUNICATINGBETWEENTHEAPPLICATIONSERVERANDBACK END DATABASES!LLOFTHEPACKAGEDAPPLICATIONSERVERPRODUCTSPROVIDEA31, BASEDCALLABLE !0)FORDATABASEACCESS!SMUCHOFTHEAPPLICATIONSERVERMARKETHASCONVERGEDAROUND THE*AVA%NTERPRISE%DITION*%% STANDARD *AVA$ATABASE#ONNECTIVITY*$"# HAS EMERGEDASTHELEADINGSTANDARD!0)FORAPPLICATIONSERVERACCESSTODATABASES
4HEõ0ROLIFERATIONõOFõ31, !STHESTANDARDFORRELATIONALDATABASEACCESS 31,HASHADAMAJORIMPACTONALLPARTSOF THECOMPUTERMARKET)"-S31, BASED$"DOMINATESMAINFRAMEDATAMANAGEMENT /RACLES31, BASEDDATABASEDOMINATESTHEMARKETFOR5.)8 BASEDCOMPUTERSYSTEMSAND SERVERS-ICROSOFTS31,3ERVERDOMINATESONSERVER ORIENTED7INDOWSOPERATINGSYSTEMS FORWORKGROUPSANDDEPARTMENTALAPPLICATIONS-Y31,DOMINATESTHEOPEN SOURCE DATABASEMARKET31,ISACCEPTEDASATECHNOLOGYFORONLINETRANSACTIONPROCESSING/,40 FULLYREFUTINGTHECONVENTIONALWISDOMOFTHESTHATRELATIONALDATABASESWOULDNEVER OFFERPERFORMANCEGOODENOUGHFORTRANSACTIONPROCESSINGAPPLICATIONS31, BASEDDATA WAREHOUSINGANDDATAMININGAPPLICATIONSARETHESTANDARDFORHELPINGCOMPANIESTO DISCOVERCUSTOMERPURCHASEPATTERNSANDTOOFFERBETTERPRODUCTSANDSERVICES/NTHE )NTERNET 31, BASEDDATABASESARETHEFOUNDATIONOFMOREPERSONALIZEDPRODUCTS SERVICES ANDINFORMATIONSERVICESTHATAREAKEYBENEFITOFELECTRONICCOMMERCE
31,õONõ-AINFRAMES !LTHOUGH)"-SHIERARCHICAL)-3DATABASEISSTILLOFFEREDON)"-MAINFRAMESANDSTILLRUNS MANYHIGH PERFORMANCEMAINFRAMEAPPLICATIONS )"-S31, BASED$"HASBEENITS FLAGSHIPMAINFRAMEDATABASEFORMORETHANTWODECADES)"-OFFERS$"IMPLEMENTATIONS ACROSSDIFFERENTCOMPUTERSYSTEMSARCHITECTURES BUTTHEMAINFRAME$"ISSTILLTHEhMOTHER SHIP vGENERATINGTHEVASTMAJORITYOF)"-SDATABASEREVENUES!NYNEWDATABASE DEVELOPMENTONMAINFRAMESYSTEMSTODAYUSES$" CEMENTING31,SDOMINANTROLEFOR MAINFRAMEDATAMANAGEMENT
31,õONõ-INICOMPUTERS -INICOMPUTERSWEREONEOFTHEMOSTFERTILEEARLYMARKETSFOR31, BASEDDATABASESYSTEMS /RACLEAND)NGRESWEREBOTHORIGINALLYMARKETEDON$IGITALS6!86-3MINICOMPUTER SYSTEMS"OTHPRODUCTSWERESUBSEQUENTLYPORTEDTOMANYOTHERPLATFORMS3YBASE ALATER DATABASESYSTEMSPECIALIZEDFORONLINETRANSACTIONPROCESSING ALSOTARGETEDTHE6!8ASONE OFITSPRIMARYPLATFORMS 4HROUGHTHES THEMINICOMPUTERVENDORSALSODEVELOPEDTHEIROWNPROPRIETARY RELATIONALDATABASESFEATURING31,$IGITALCONSIDEREDRELATIONALDATABASESSOIMPORTANT THATITBUNDLEDARUNTIMEVERSIONOFITS2DB6-3DATABASEWITHEVERY6!86-3SYSTEM
#HAPTERçç
31,çINç0ERSPECTIVEç
31,õONõ5.)8 "ASEDõ3YSTEMS 31,ISFIRMLYESTABLISHEDASTHEDATAMANAGEMENTSOLUTIONOFCHOICEFOR5.)8 BASED COMPUTERSYSTEMS/RIGINALLYDEVELOPEDAT"ELL,ABORATORIES 5.)8BECAMEVERYPOPULARIN THESASAVENDOR INDEPENDENT STANDARDOPERATINGSYSTEM)TRUNSONAWIDERANGEOF COMPUTERSYSTEMS FROMWORKSTATIONSTOMAINFRAMES ANDHASBECOMETHESTANDARD OPERATINGSYSTEMFORHIGH ENDSERVERSYSTEMS INCLUDINGDATABASESERVERS )NTHEEARLYS FOURMAJORDATABASESWEREALREADYAVAILABLEFOR5.)8SYSTEMS4WO OFTHEM )NGRESAND/RACLE WERE5.)8VERSIONSOFTHEPRODUCTSTHATRANON$%#S PROPRIETARYMINICOMPUTERS4HEOTHERTWO )NFORMIXAND5NIFY WEREWRITTENSPECIFICALLYFOR 5.)8.EITHEROFTHEMORIGINALLYOFFERED31,SUPPORT BUTBY 5NIFYOFFEREDA31, QUERYLANGUAGE AND)NFORMIXHADBEENREWRITTENAS)NFORMIX 31, WITHFULL31,SUPPORT 4ODAY THE/RACLEDATABASEDOMINATESTHE5.)8 BASEDDATABASEMARKETANDISAVAILABLE ONALLOFTHELEADING5.)8SERVERPLATFORMS)NFORMIXWASACQUIREDBY)"- WHICHSTILL OFFERSTHEPRODUCTFORITSOWNANDOTHER5.)8 BASEDSERVERS5.)8 BASEDANDINCREASINGLY ,INUX BASED DATABASESERVERSAREAMAINSTREAMBUILDINGBLOCKFORBOTHCLIENTSERVERAND THREE TIER)NTERNETARCHITECTURES4HECONSTANTSEARCHFORHIGHER31,DATABASEPERFORMANCE HASDRIVENSOMEOFTHEMOSTIMPORTANTTRENDSIN5.)8SYSTEMHARDWARE4HESEINCLUDETHE EMERGENCEOFSYMMETRICMULTIPROCESSING3-0 ASAMAINSTREAMSERVERARCHITECTURE THE DEVELOPMENTOFMULTICOREMICROPROCESSORSWHICHTOOK3-0TOTHECHIPLEVEL ANDTHEUSEOF 2!)$2EDUNDANT!RRAYOF)NDEPENDENT$ISKS TECHNOLOGYTOBOOST)/PERFORMANCE
31,õONõ0ERSONALõ#OMPUTERS $ATABASESHAVEBEENPOPULARONPERSONALCOMPUTERSSINCETHEEARLYDAYSOFTHE)"-0# !SHTON 4ATESD"!3%PRODUCTREACHEDANINSTALLEDBASEOFOVERMILLION-3 $/3 BASED 0#S!LTHOUGHTHESEEARLY0#DATABASESOFTENPRESENTEDDATAINTABULARFORM THEYLACKED THEFULLPOWEROFARELATIONAL$"-3ANDARELATIONALDATABASELANGUAGESUCHAS31,4HE FIRST31, BASED0#DATABASESWEREVERSIONSOFPOPULARMINICOMPUTERPRODUCTSTHATBARELY FITONPERSONALCOMPUTERS&OREXAMPLE 0ROFESSIONAL/RACLEFORTHE)"-0# INTRODUCEDIN REQUIREDTWOMEGABYTESOFMEMORYWELLABOVETHETYPICAL+"0#CONFIGURATION OFTHEDAY 4HEREALIMPACTOF31,ONPERSONALCOMPUTERSBEGANWITHTHEANNOUNCEMENTOF/3 BY)"-AND-ICROSOFTIN!PRIL)NADDITIONTOTHESTANDARD/3PRODUCT )"- ANNOUNCEDAPROPRIETARY/3%XTENDED%DITION/3%% WITHABUILT IN31,DATABASE
0!24ç)
(EWLETT 0ACKARDOFFERED!LLBASE ADATABASETHATSUPPORTEDBOTHITS(031,DIALECTANDA NONRELATIONALINTERFACE$ATA'ENERALS$'31,DATABASEREPLACEDITSOLDERNONRELATIONAL DATABASESAS$'SSTRATEGICDATAMANAGEMENTTOOL)NADDITION MANYOFTHEMINICOMPUTER VENDORSRESOLDRELATIONALDATABASESFROMTHEINDEPENDENTDATABASESOFTWAREVENDORS4HESE EFFORTSHELPEDTOESTABLISH31,ASANIMPORTANTTECHNOLOGYFORMIDRANGECOMPUTERSYSTEMS "YTHEMID S THEMINICOMPUTERVENDORS31,PRODUCTSHADLARGELYDISAPPEARED BEATENINTHEMARKETPLACEBYMULTIPLATFORMSOFTWAREFROM/RACLE )NFORMIX 3YBASE AND OTHERS/RACLEACQUIRED$IGITALS2DB ANDTHEOTHERPRODUCTSWEREGRADUALLYDROPPED 0ARALLELINGTHISTREND THEIMPORTANCEOFPROPRIETARYMINICOMPUTEROPERATINGSYSTEMSFADED REPLACEDBYWIDESPREADUSEOF5.)8ONMIDRANGESYSTEMS9ESTERDAYSMINICOMPUTER 31,MARKETHASEFFECTIVELYBECOMETODAYSMARKETFOR5.)8 BASEDDATABASESERVERS BASEDON31,
ç
0ARTç)ç
!Nç/VERVIEWçOFç31,
ANDCOMMUNICATIONSSUPPORT7ITHTHEINTRODUCTION )"-AGAINSIGNALEDITSSTRONG COMMITMENTTO31, SAYINGINEFFECTTHAT31,WASSOIMPORTANTTHATITBELONGEDINTHE COMPUTERSOPERATINGSYSTEM /3%XTENDED%DITIONPRESENTED-ICROSOFTWITHAPROBLEM!STHEDEVELOPERAND DISTRIBUTOROFSTANDARD/3TOOTHERPERSONALCOMPUTERMANUFACTURERS -ICROSOFTNEEDED ANALTERNATIVETOTHE%XTENDED%DITION-ICROSOFTRESPONDEDBYLICENSINGTHE3YBASE$"-3 WHICHHADBEENDEVELOPEDFOR6!8 ANDBEGANPORTINGITTO/3)N*ANUARY INA SURPRISEMOVE -ICROSOFTAND!SHTON 4ATETHE0#DATABASELEADERATTHETIMEWITHITSD"!3% PRODUCT ANNOUNCEDTHATTHEYWOULDJOINTLYSELLTHERESULTING/3 BASEDPRODUCT RENAMED 31,3ERVER-ICROSOFTWOULDSELL31,3ERVERWITH/3TOCOMPUTERMANUFACTURERS!SHTON 4ATEWOULDSELLTHEPRODUCTTHROUGHRETAILCHANNELSTO0#USERS)N3EPTEMBER ,OTUS $EVELOPMENTTHEOTHERMEMBEROFTHEBIGTHREEOF0#SOFTWAREATTHETIME ADDEDITS ENDORSEMENTOF31,3ERVERBYINVESTINGIN3YBASE,ATERTHATYEAR !SHTON 4ATERELINQUISHED ITSEXCLUSIVERETAILDISTRIBUTIONRIGHTSANDSOLDITSINVESTMENTTO,OTUS 31,3ERVERFOR/3METWITHONLYLIMITEDSUCCESSASDIDTHE/3OPERATINGSYSTEM ITSELF "UTINTYPICAL-ICROSOFTFASHION -ICROSOFTCONTINUEDTOINVESTHEAVILYIN31,3ERVER DEVELOPMENTANDPORTEDITTOITS7INDOWS.4OPERATINGSYSTEM&ORAWHILE -ICROSOFTAND 3YBASEREMAINEDPARTNERS WITH3YBASEFOCUSEDONTHEMINICOMPUTERAND5.)8 BASEDSERVER MARKETSAND-ICROSOFTFOCUSEDON0#,!.SAND7INDOWS.4!S7INDOWS.4AND5.)8 SYSTEMSBECAMEMOREANDMORECOMPETITIVEASDATABASESERVEROPERATINGSYSTEMPLATFORMS THERELATIONSHIPBECAMELESSCOOPERATIVEANDMORECOMPETITIVE%VENTUALLY 3YBASEAND -ICROSOFTWENTTHEIRSEPARATEWAYS4HECOMMONHERITAGEOF3YBASESAND-ICROSOFTS31, PRODUCTSCANSTILLBESEENINPRODUCTCAPABILITIESANDSOMECOMMON31,EXTENSIONS FOREXAMPLE STOREDPROCEDURES BUTTHEPRODUCTLINESHAVEALREADYDIVERGEDSIGNIFICANTLY 4ODAY 31,3ERVERISAMAJORDATABASESYSTEMON7INDOWS BASEDSERVERS)THASHADA MAJORNEWRELEASEEVERYTWOTOTHREEYEARS ADDINGMAJORCAPABILITIESINAREASASDIVERSEAS 8-,PROCESSING SPECIALDATA FULL TEXTSEARCH DATAWAREHOUSINGANDANALYTICS ANDHIGH AVAILABILITY7HILE5.)8 BASEDSERVERSAND/RACLEDATABASESCONTINUETODOMINATETHE LARGESTDATABASESERVERINSTALLATIONS SERVERCONFIGURATIONSOFTHE7INDOWSOPERATINGSYSTEM ANDTHE)NTELARCHITECTURESYSTEMSONWHICHITRUNSHAVEACHIEVEDCREDIBILITYINTHE MIDRANGEMARKET
31,õANDõ4RANSACTIONõ0ROCESSING 31,ANDRELATIONALDATABASESORIGINALLYHADVERYLITTLEIMPACTINONLINETRANSACTION PROCESSING/,40 APPLICATIONS7ITHTHEIREMPHASISONQUERIES RELATIONALDATABASESWERE CONFINEDTODECISIONSUPPORTANDLOW VOLUMEONLINEAPPLICATIONS WHERETHEIRSLOWER PERFORMANCEWASNOTADISADVANTAGE&OR/,40APPLICATIONS WHEREHUNDREDSOFUSERS NEEDEDONLINEACCESSTODATAANDSUBSECONDRESPONSETIMES )"-SNONRELATIONAL )NFORMATION-ANAGEMENT3YSTEM)-3 REIGNEDASTHEDOMINANT$"-3 )N ANEW$"-3VENDOR 3YBASE INTRODUCEDANEW31, BASEDDATABASEESPECIALLY DESIGNEDFOR/,40APPLICATIONS4HE3YBASE$"-3RANON6!86-3MINICOMPUTERSAND 3UNWORKSTATIONS ANDFOCUSEDONMAXIMUMONLINEPERFORMANCE/RACLE#ORPORATIONAND 2ELATIONAL4ECHNOLOGYFOLLOWEDSHORTLYWITHANNOUNCEMENTSTHATTHEY TOO WOULDOFFER /,40VERSIONSOFTHEIRPOPULAR/RACLEAND)NGRESDATABASESYSTEMS)NTHE5.)8MARKET )NFORMIXANNOUNCEDAN/,40VERSIONOFITS$"-3 NAMED)NFORMIX 4URBO
#HAPTERçç
31,çINç0ERSPECTIVEç
31,õANDõ7ORKGROUPõ$ATABASES 4HEDRAMATICGROWTHOF0#,!.STHROUGHTHESANDSCREATEDANEWOPPORTUNITY FORDEPARTMENTALORWORKGROUPDATABASEMANAGEMENT4HEORIGINALDATABASESYSTEMS FOCUSEDONTHISMARKETSEGMENTRANON)"-S/3OPERATINGSYSTEM)NFACT 31,3ERVER NOWAKEYPARTOF-ICROSOFTS7INDOWSSTRATEGY ORIGINALLYMADEITSDEBUTASAN/3 DATABASEPRODUCT)NTHEMID S .OVELLALSOMADEACONCENTRATEDEFFORTTOMAKEITS .ET7AREOPERATINGSYSTEMANATTRACTIVEWORKGROUPDATABASESERVERPLATFORM&ROMTHE EARLIESTDAYSOF0#,!.S .ET7AREHADBECOMEESTABLISHEDASTHEDOMINANTNETWORK OPERATINGSYSTEMFORFILEANDPRINTSERVERS4HROUGHDEALSWITH/RACLEANDOTHERS .OVELL SOUGHTTOEXTENDTHISLEADERSHIPTOWORKGROUPDATABASESERVERSASWELL 4HEARRIVALOF7INDOWS.4 ASPECIALIZEDVERSIONOF7INDOWSTUNEDFORSERVERUSE WAS THECATALYSTTHATCAUSEDTHEWORKGROUPDATABASEMARKETTOREALLYTAKEOFF7HILE.ET7ARE OFFEREDACLEARPERFORMANCEADVANTAGEOVER.4ASAWORKGROUPFILESERVER .4HADAMORE ROBUST GENERAL PURPOSEARCHITECTURE MORELIKETHEMINICOMPUTEROPERATINGSYSTEMS -ICROSOFTSUCCESSFULLYPOSITIONED.4ASAMOREATTRACTIVEPLATFORMFORRUNNINGWORKGROUP APPLICATIONSASANAPPLICATIONSERVER ANDWORKGROUPDATABASES-ICROSOFTSOWN31, 3ERVERPRODUCTWASMARKETEDANDOFTENBUNDLED WITH.4ASATIGHTLYINTEGRATED WORKGROUPDATABASEPLATFORM#ORPORATEINFORMATIONSYSTEMSDEPARTMENTSWEREATFIRST VERYCAUTIOUSABOUTUSINGRELATIVELYNEWANDUNPROVENTECHNOLOGY BUTTHE.431,3ERVER COMBINATIONALLOWEDDEPARTMENTSANDNON )3EXECUTIVESTOUNDERTAKESMALLER SCALE WORKGROUP LEVELPROJECTSONTHEIROWN WITHOUTCORPORATE)3HELP4HISPHENOMENON LIKE THEGRASSROOTSSUPPORTFORPERSONALCOMPUTERSADECADEEARLIER FUELEDTHEEARLYGROWTHOF THEWORKGROUPDATABASESEGMENT
0!24ç)
)N )"-JUMPEDONTHERELATIONAL/,40BANDWAGONWITH$"6ERSION WITH BENCHMARKSSHOWINGTHENEWVERSIONOPERATINGATOVERTRANSACTIONSPERSECONDON LARGEMAINFRAMES)"-CLAIMEDTHAT$"PERFORMANCEWASNOWSUITABLEFORALLBUTTHEMOST DEMANDING/,40APPLICATIONSANDENCOURAGEDCUSTOMERSTOCONSIDERITASASERIOUS ALTERNATIVETO)-3/,40BENCHMARKSBECAMEASTANDARDSALESTOOLFORRELATIONALDATABASES DESPITESERIOUSQUESTIONSABOUTHOWWELLTHEBENCHMARKSACTUALLYMEASUREPERFORMANCEIN REALAPPLICATIONS 4HESUITABILITYOF31,FOR/,40IMPROVEDDRAMATICALLYOVERTHENEXTDECADE WITH ADVANCESINRELATIONALTECHNOLOGYANDMOREPOWERFULCOMPUTERHARDWAREBOTHLEADINGTO EVER HIGHERTRANSACTIONRATES$"-3VENDORSSTARTEDTOPOSITIONTHEIRPRODUCTSBASEDON THEIR/,40PERFORMANCE ANDFORAFEWYEARSDATABASEADVERTISINGFOCUSEDALMOSTENTIRELY ONTHESEPERFORMANCEBENCHMARKWARS!VENDOR INDEPENDENTORGANIZATION THE 4RANSACTION0ROCESSING#OUNCIL JUMPEDINTOTHEBENCHMARKINGFRAYWITHASERIESOFVENDOR INDEPENDENTBENCHMARKS40# ! 40# " AND40# # WHICHONLYSERVEDTOINTENSIFYTHE PERFORMANCEFOCUSOFTHEVENDORS "YTHEEARLYS 31, BASEDRELATIONALDATABASESONHIGH END5.)8 BASEDDATABASE SERVERSEVOLVEDWELLPASTTHE TRANSACTIONS PER SECONDMARK#LIENTSERVERSYSTEMS USING31,DATABASESHAVEBECOMETHEACCEPTEDARCHITECTUREFORIMPLEMENTING/,40 APPLICATIONS&ROMAPOSITIONAShUNSUITABLEFOR/,40 v31,HASGROWNTOBETHEINDUSTRY STANDARDFOUNDATIONFORBUILDING/,40APPLICATIONS
ç
0ARTç)ç
!Nç/VERVIEWçOFç31,
4ODAY 31,ISWELLESTABLISHEDASAWORKGROUPDATABASESTANDARD)NADDITIONTO -ICROSOFTSNEWERVERSIONSOF7INDOWSFORSERVERS ,INUXHASEMERGEDASAVERYPOPULAR PLATFORMFORWORKGROUPSERVERS-ICROSOFT31,3ERVERAND/RACLESHARETHELARGESTPARTOF THEMARKET BUTOPENSOURCEDATABASESLIKE-Y31,HAVEEMERGEDASAVERYSTRONGANDCOST EFFECTIVEALTERNATIVE0OSTGRES ANOTHEROPENSOURCEPRODUCTDEVELOPEDATTHE5NIVERSITYOF #ALIFORNIAAT"ERKELEYASAFOLLOW ONTO)NGRES HASALSOGAINEDASMALLERBUTLOYALFOLLOWING INTHISSEGMENT
31, õ$ATAõ7AREHOUSING õANDõ"USINESSõ)NTELLIGENCE &ORSEVERALYEARS THEEFFORTTOMAKE31,AVIABLETECHNOLOGYFOR/,40APPLICATIONSSHIFTED THEFOCUSAWAYFROMTHEORIGINALRELATIONALDATABASESTRENGTHSOFQUERYPROCESSINGAND DECISIONMAKING0ERFORMANCEBENCHMARKSANDCOMPETITIONAMONGTHEMAJOR$"-3BRANDS FOCUSEDONSIMPLETRANSACTIONSLIKEADDINGANEWORDERTOTHEDATABASEORDETERMININGA CUSTOMERSACCOUNTBALANCE"ECAUSEOFTHEPOWEROFTHERELATIONALDATABASEMODEL THE DATABASESTHATCOMPANIESUSEDTOHANDLEDAILYBUSINESSOPERATIONSCOULDALSOBEUSEDTO ANALYZETHEGROWINGAMOUNTSOFDATATHATWEREBEINGACCUMULATED!FREQUENTTHEMEOF CONFERENCESANDTRADESHOWSPEECHESFOR)3MANAGERSWASTHATACORPORATIONSACCUMULATED DATASTOREDIN31,DATABASES OFCOURSE SHOULDBETREATEDASAVALUABLEASSETANDUSEDTO HELPIMPROVETHEQUALITYOFBUSINESSDECISIONMAKING !LTHOUGHRELATIONALDATABASESCOULD INTHEORY EASILYPERFORMBOTH/,40ANDDECISION MAKINGAPPLICATIONS THEREWERESOMEVERYSIGNIFICANTPRACTICALPROBLEMS/,40WORKLOADS CONSISTEDOFMANYSHORTDATABASETRANSACTIONS ANDTHERESPONSETIMEFORUSERSWASVERY IMPORTANT)NCONTRAST DECISION SUPPORTQUERIESCOULDINVOLVESEQUENTIALSCANSOFLARGE DATABASETABLESTOANSWERQUESTIONSLIKEh7HATISTHEAVERAGEORDERSIZEBYSALESREGIONv ORh(OWDOINVENTORYTRENDSCOMPAREWITHTHESAMETIMEAYEARAGOv4HESEQUERIESCOULD TAKEMINUTESORHOURS)FABUSINESSANALYSTTRIEDTORUNONEOFTHESEQUERIESDURINGATIME WHENBUSINESSTRANSACTIONVOLUMESREACHEDTHEIRPEAK ITCOULDCAUSESERIOUSDEGRADATION IN/,40PERFORMANCE!NOTHERPROBLEMWASTHATTHEDATATOANSWERUSEFULQUESTIONSABOUT BUSINESSTRENDSWASOFTENSPREADACROSSMANYDIFFERENTDATABASES TYPICALLYINVOLVING DIFFERENT$"-3VENDORSANDDIFFERENTCOMPUTERPLATFORMS 4HEDESIRETOTAKEADVANTAGEOFACCUMULATEDBUSINESSDATA ANDTHEPRACTICAL PERFORMANCEPROBLEMSITCAUSEDFOR/,40APPLICATIONS LEDTOTHECONCEPTOFADATA WAREHOUSE SHOWNIN&IGURE "USINESSDATAISEXTRACTEDFROM/,40SYSTEMS REFORMATTED ANDVALIDATEDASNECESSARY ANDTHENPLACEDINTOASEPARATEDATABASETHATISDEDICATEDTO DECISION MAKINGQUERIESTHEhWAREHOUSEv 4HEDATAEXTRACTIONANDTRANSFORMATIONCANBE SCHEDULEDFOROFF HOURSBATCHPROCESSING)DEALLY ONLYNEWORCHANGEDDATACANBE EXTRACTED MINIMIZINGTHEAMOUNTOFDATATOBEPROCESSEDINTHEMONTHLY WEEKLY ORDAILY WAREHOUSEREFRESHCYCLE7ITHTHISSCHEME THETIME CONSUMINGBUSINESSANALYSISQUERIES USETHEDATAWAREHOUSE NOTTHE/,40DATABASE ASTHEIRSOURCEOFDATA 31, BASEDRELATIONALDATABASESWEREACLEARCHOICEFORTHEWAREHOUSEDATASTOREBECAUSE OFTHEIRFLEXIBLEQUERYPROCESSING!SERIESOFNEWCOMPANIESWASFORMEDTOBUILDTHEDATA EXTRACTION TRANSFORMATION ANDDATABASEQUERYTOOLSNEEDEDBYTHEDATAWAREHOUSEMODEL )NADDITION $"-3VENDORSSTARTEDTOFOCUSONTHEKINDSOFDATABASEQUERIESTHATCUSTOMERS TENDEDTORUNINTHEDATAWAREHOUSE4HESEQUERIESTENDEDTOBELARGEANDCOMPLEXSUCH ASANALYZINGTENSORHUNDREDSOFMILLIONSOFINDIVIDUALCASH REGISTERRECEIPTSLOOKINGFOR PRODUCTPURCHASEPATTERNS4HEYOFTENINVOLVEDTIME SERIESDATAFOREXAMPLE ANALYZING
#HAPTERçç
31,çINç0ERSPECTIVEç
0!24ç)
1, ÊÎÈÊ /
iÊ`>Ì>ÊÜ>Ài
ÕÃ}ÊVVi«Ì
PRODUCTSALESORMARKETSHAREDATAOVERTIME4HEYALSOTENDEDTOINVOLVESTATISTICAL SUMMARIESOFDATATOTALSALES AVERAGEORDERVOLUME PERCENTGROWTH ANDSOONRATHER THANTHEINDIVIDUALDATAITEMSTHEMSELVES 4OADDRESSTHESPECIALIZEDNEEDSOFDATAWAREHOUSINGAPPLICATIONSOFTENCALLED/NLINE !NALYTICAL0ROCESSINGOR/,!0 SPECIALIZEDDATABASESBEGANTOAPPEAR4HESEDATABASESWERE OPTIMIZEDFOR/,!0WORKLOADSINSEVERALDIFFERENTWAYS4HEIRPERFORMANCEWASTUNEDFOR COMPLEX READ ONLYQUERYACCESS4HEYSUPPORTEDADVANCEDSTATISTICALANDOTHERDATA FUNCTIONS SUCHASBUILT INTIME SERIESPROCESSING4HEYSUPPORTEDPRECALCULATIONOFDATABASE STATISTICALDATA SOTHATRETRIEVINGAVERAGESANDTOTALSCOULDBEDRAMATICALLYFASTER3OMEOF THESESPECIALIZEDDATABASESDIDNOTUSE31, BUTMANYDIDLEADINGTOTHECOMPANIONTERM 2/,!0 FOR2ELATIONAL/NLINE!NALYTICAL0ROCESSING !STHEMARKETFORDATAWAREHOUSINGCONTINUEDTOEVOLVE THETOOLSTOTAPTHEWAREHOUSE EMERGEDASANIMPORTANTMARKETSEGMENTINTHEIROWNRIGHT OFTENLABELEDBUSINESSINTELLIGENCE 4HELINESBETWEENTHEVENDORSTHATSUPPLIEDTHEWAREHOUSEDATABASES THETOOLSTOPOPULATE THEM ANDTHETOOLSTOANALYZEDATAGRADUALLYBLURREDASTHEMARKETGREW4HREEOFTHELARGEST BUSINESSINTELLIGENCEVENDORSBECAMESUCCESSFULPUBLICCOMPANIESINTHEIROWNRIGHTBEFORE
ç
0ARTç)ç
!Nç/VERVIEWçOFç31,
BEINGACQUIREDBYTHREEOFTHEINDUSTRYGIANTS"USINESS/BJECTSWASACQUIREDBY3!0 THE LEADINGVENDOROFENTERPRISEAPPLICATIONS(YPERIONWASACQUIREDBY/RACLE AND#OGNOS WASACQUIREDBY)"-!SWITHSOMANYSEGMENTSOFTHE)4MARKET 31,SADVANTAGESASA STANDARDPROVEDTOBEAPOWERFULFORCE AND31, BASEDDATAWAREHOUSESANDANALYTICTOOLS AREFIRMLYENTRENCHED
31,õANDõ)NTERNETõ!PPLICATIONS $URINGTHELATES THE7ORLD7IDE7EBANDTHEWEBBROWSINGCAPABILITYTHATITENABLED WERETHEDRIVINGFORCEBEHINDTHEGROWTHOFTHE)NTERNET7ITHITSFOCUSONDELIVERING CONTENTINTHEFORMOFTEXTANDGRAPHICS THEEARLYUSESOFTHE7EBHADLITTLETODOWITHDATA MANAGEMENT"YTHEMID S HOWEVER MUCHOFTHECONTENTDELIVEREDFROMCORPORATE WEBSITESHADITSORIGINSIN31, BASEDCORPORATEDATABASES&OREXAMPLE ONACOMMERCIAL WEBSITEFORARETAILER WEBPAGESTHATCONTAININFORMATIONABOUTPRODUCTSAVAILABLEFORSALE THEIRPRICES PRODUCTAVAILABILITY SPECIALPROMOTIONS ANDTHELIKEARETYPICALLYCREATEDON DEMAND BASEDONDATARETRIEVEDFROMA31,DATABASE4HEVASTMAJORITYOFTHEPAGES DISPLAYEDBYANONLINEAUCTIONSITEORBYANONLINETRAVELSITEARESIMILARLYBASEDONDATA RETRIEVEDFROM31,DATABASES TRANSFORMEDINTOTHE7EBS(4-,PAGEFORMAT)NTHEOTHER DIRECTION DATAENTEREDBYAUSERINTOBROWSERPAGEFORMSISALMOSTALWAYSCAPTUREDINTO 31,DATABASESTHATFORMPARTOFTHEWEBSITEARCHITECTURE "YTHEEARLYS INDUSTRYATTENTIONHADTURNEDTOTHENEXTPHASEOFTHE)NTERNET AND THEROLETHAT)NTERNETTECHNOLOGIESCANPLAYINCONNECTINGCOMPUTERAPPLICATIONSTOONE ANOTHER4HESEDISTRIBUTEDAPPLICATIONSARCHITECTURESRECEIVEDWIDESPREADTRADEPRESS COVERAGEUNDERTHEBANNEROFWEBSERVICES)NTHELONGSTANDINGTRADITIONOFTHECOMPUTER INDUSTRY COMPETINGCAMPSEMERGED CHAMPIONINGDIFFERENTSETSOFSTANDARDSAND LANGUAGESFORIMPLEMENTINGTHEMA-ICROSOFT LEDCAMPUNDERTHE.%4&RAMEWORK AND ARIVALCAMPFOCUSEDON*AVAAND*%% BASEDAPPLICATIONSERVERS"OTHARCHITECTURES EMBRACEAKEYROLEFOR8-, ASTANDARDFOREXCHANGINGSTRUCTUREDDATALIKETHEDATATHAT RESIDESIN31,DATABASES )NRESPONSETOTHEINDUSTRYATTENTIONONWEBSERVICES AFLURRYOFPRODUCTSHASBEEN ANNOUNCEDTHATLINK8-, FORMATTEDMESSAGESTO31, BASEDDATABASES3TARTUPDATABASE VENDORSANDSOMEOFTHEOBJECTDATABASEVENDORSANNOUNCED8-, BASEDDATABASE PRODUCTS ARGUINGTHATTHEYPROVIDEANIDEAL NATIVEMATCHFORTHE8-, FORMATTEDEXCHANGE OFDATAOVERTHE)NTERNET4HEESTABLISHEDRELATIONALDATABASEPLAYERSRESPONDEDWITHTHEIR OWN8-,INITIATIVES ADDING8-,INPUTOUTPUTCAPABILITIES ANDTHENNATIVE8-,DATA TYPESUPPORT TOTHEIRPRODUCTS4IGHTERINTEGRATIONBETWEEN8-,AND31,REMAINSAN ACTIVEAREAOFINVESTMENTBYALLOFTHEMAJORDATABASEVENDORSTODAY 4HE)NTERNETAPPROACHTOSCALABILITYISALSOHAVINGAMAJORIMPACTONDATABASESOFTWARE PRODUCTS-ANY)NTERNETSOFTWAREELEMENTSOPERATEATh)NTERNETSCALEvTHROUGHAHORIZONTAL SCALINGAPPROACH SPREADINGOUTTHEIRWORKLOADACROSSDOZENSORHUNDREDSOFLOW COST COMMODITYSERVERS4HE'OOGLESEARCHENGINEISONEOFTHEMOSTEXTREMEEXAMPLESOFTHIS ARCHITECTURE WHEREEVENASINGLESEARCHCANBEDISTRIBUTEDACROSSDOZENSOFSERVERS ANDTHE TOTALSEARCHVOLUMEISDISTRIBUTEDACROSSTENSOFTHOUSANDSOFSERVERS ALLLOCATEDINTHE h)NTERNETCLOUDv4HEREAREMAJORCHALLENGESTOAPPLYINGTHISAPPROACHTODATABASE MANAGEMENT BUTPROVIDINGDATAMANAGEMENThINTHECLOUDvISANACTIVETOPICOFRESEARCH ANDDEVELOPMENTINTHEDATABASECOMMUNITY
#HAPTERçç
31,çINç0ERSPECTIVEç
3UMMARY s 31,WASORIGINALLYDEVELOPEDBY)"-RESEARCHERS AND)"-SSTRONGSUPPORTOF31, WASAKEYREASONFORITSEARLYSUCCESS s 4HEREISANOFFICIAL!.3))3/31,STANDARD WHICHHASGROWNTREMENDOUSLYINSCOPE ANDCOMPLEXITYSINCEITSDEBUTIN s $ESPITETHEEXISTENCEOFASTANDARD THEREAREMANYSMALLVARIATIONSAMONGCOMMERCIAL 31,DIALECTSNOTWO31,IMPLEMENTATIONSAREEXACTLYTHESAME s 31,HASBECOMETHESTANDARDDATABASEMANAGEMENTLANGUAGEACROSSABROADRANGE OFCOMPUTERSYSTEMSANDAPPLICATIONSAREAS INCLUDINGMAINFRAMES WORKSTATIONS PERSONALCOMPUTERS /,40SYSTEMS CLIENTSERVERSYSTEMS DATAWAREHOUSING AND THE)NTERNET
0!24ç)
4HISCHAPTERDESCRIBEDTHEDEVELOPMENTOF31,ANDITSROLEASASTANDARDLANGUAGEFORRELATIONAL DATABASEMANAGEMENT
This page intentionally left blank
#(!04%2
2ELATIONALç$ATABASES
$
ATABASEMANAGEMENTSYSTEMSORGANIZEANDSTRUCTUREDATASOTHATITCANBESAVED ANDRETRIEVEDBYUSERSANDAPPLICATIONPROGRAMS4HEDATASTRUCTURESANDACCESS TECHNIQUESPROVIDEDBYAPARTICULAR$"-3ARECALLEDITSDATAMODEL!DATAMODEL DETERMINESBOTHTHEhPERSONALITYvOFA$"-3ANDTHEAPPLICATIONSFORWHICHITISPARTICULARLY WELL SUITED 31,ISADATABASELANGUAGEFORDATABASESTHATUSETHERELATIONALDATAMODEL7HATEXACTLY ISARELATIONALDATABASE(OWISDATASTOREDINARELATIONALDATABASE(OWDORELATIONAL DATABASESCOMPAREWITHEARLIERTECHNOLOGIES SUCHASHIERARCHICALANDNETWORKDATABASES 7HATARETHEADVANTAGESANDDISADVANTAGESOFTHERELATIONALMODEL4HISCHAPTERDESCRIBES THERELATIONALDATAMODELSUPPORTEDBY31,ANDCOMPARESITWITHEARLIERSTRATEGIESFOR DATABASEORGANIZATION
%ARLYõ$ATAõ-ODELS !SDATABASEMANAGEMENTBECAMEPOPULARDURINGTHESANDS AHANDFULOFPOPULAR DATAMODELSEMERGED%ACHOFTHESEEARLYDATAMODELSHADADVANTAGESANDDISADVANTAGES THATPLAYEDKEYROLESINTHEDEVELOPMENTOFTHERELATIONALDATAMODEL)NMANYWAYS THE RELATIONALDATAMODELREPRESENTEDANATTEMPTTOSTREAMLINEANDSIMPLIFYTHEEARLIERDATA MODELS4OUNDERSTANDTHEROLEANDCONTRIBUTIONOF31,ANDTHERELATIONALMODEL ITISUSEFUL TOBRIEFLYEXAMINESOMEDATAMODELSTHATPRECEDEDTHEDEVELOPMENTOF31, SOMEOFWHICH ARESTILLINUSETODAY
&ILEõ-ANAGEMENTõ3YSTEMS "EFORETHEINTRODUCTIONOFDATABASEMANAGEMENTSYSTEMS ALLDATAPERMANENTLYSTOREDON ACOMPUTERSYSTEM SUCHASPAYROLLANDACCOUNTINGRECORDS WASSTOREDININDIVIDUALFILES !FILEMANAGEMENTSYSTEM USUALLYPROVIDEDASPARTOFTHECOMPUTERSOPERATINGSYSTEM KEPTTRACKOFTHENAMESANDLOCATIONSOFTHEFILES&ILEMANAGEMENTSYSTEMSARESTILLWIDELY USEDTODAYYOUAREPROBABLYFAMILIARWITHTHEFILES AND FOLDERSSTRUCTUREPROVIDEDBYTHE FILESYSTEMON-ICROSOFT7INDOWSOR!PPLES-ACINTOSHOPERATINGSYSTEMS3IMILARFILE SYSTEMSAREUSEDBY5.)8 BASEDSERVERSANDALLCOMMERCIALCOMPUTERSYSTEMS !FILEMANAGEMENTSYSTEMBASICALLYHASNODATAMODELITKNOWSNOTHINGABOUTTHE INTERNALCONTENTSOFFILES!TBEST THEFILESYSTEMMIGHTMAINTAINhFILETYPEvINFORMATION
ç
0ARTç)ç
!Nç/VERVIEWçOFç31,
ALONGWITHTHEFILENAME ALLOWINGITTODISTINGUISHBETWEENAWORDPROCESSINGDOCUMENT ANDAFILECONTAININGPAYROLLDATA"UTKNOWLEDGEABOUTTHEINTERNALCONTENTSOFAFILEWHAT INDIVIDUALPIECESOFDATAITCONTAINSANDHOWTHATDATAISORGANIZEDISEMBEDDEDINTHE APPLICATIONPROGRAMSTHATUSETHEFILE ASSHOWNIN&IGURE )NTHISPAYROLLAPPLICATION EACHOFTHE#/"/,PROGRAMSTHATPROCESSESTHEEMPLOYEEMASTERFILECONTAINSAFILE DESCRIPTION&$ THATDESCRIBESTHELAYOUTOFTHEDATAINTHEFILE)FTHESTRUCTUREOFTHEDATA CHANGESFOREXAMPLE IFANADDITIONALITEMOFDATAISTOBESTOREDFOREACHEMPLOYEE EVERYPROGRAMTHATACCESSESTHEFILEHASTOBEMODIFIED4HISISNTAPROBLEMFORFILES CONTAININGWORDPROCESSINGDOCUMENTSORSPREADSHEETS WHICHAREUSUALLYPROCESSEDBYA SINGLEPROGRAM"UTINCORPORATEDATAPROCESSING FILESAREOFTENSHAREDAMONGDOZENSOR EVENHUNDREDSOFPROGRAMS ASIN&IGURE !STHENUMBEROFFILESANDPROGRAMSGROWS OVERTIME MOREANDMOREOFADATA PROCESSINGDEPARTMENTSEFFORTGOESINTOMAINTAINING EXISTINGAPPLICATIONSRATHERTHANDEVELOPINGNEWONES 4HEPROBLEMSOFMAINTAININGLARGEFILE BASEDSYSTEMSLEDINTHELATESTOTHE DEVELOPMENTOFDATABASEMANAGEMENTSYSTEMS4HEIDEABEHINDTHESESYSTEMSWASSIMPLE MOVETHEDEFINITIONOFAFILESCONTENTANDSTRUCTUREOUTOFTHEINDIVIDUALPROGRAMS AND STOREIT TOGETHERWITHTHEDATA INADATABASE5SINGTHEINFORMATIONINTHEDATABASE THE $"-3THATCONTROLLEDITCOULDTAKEAMUCHMOREACTIVEROLEINMANAGINGBOTHTHEDATAAND CHANGESTOTHEDATABASESTRUCTURE-OREOVER $"-3SAREANEXTENSIONOFFILEMANAGEMENT SYSTEMSRATHERTHANAREPLACEMENTFORTHEM$"-3SUSEFILEMANAGEMENTSYSTEMSUSUALLY THEONESSUPPLIEDWITHTHEOPERATINGSYSTEM TOSTORETHEDATABASESTRUCTURES4HEDATABASE USERTHENREFERENCESTHE$"-3ANDTHE$"-3HANDLESTHEPHYSICALSTORAGEDETAILS)TISTHIS LAYEROFABSTRACTIONTHATPROVIDESPHYSICALDATAINDEPENDENCE
1, Ê{£Ê Ê«>ÞÀÊ>««V>ÌÊÕÃ}Ê>ÊwiÊ>>}iiÌÊÃÞÃÌi
#HAPTERçç
2ELATIONALç$ATABASESç
(IERARCHICALõ$ATABASES
s &INDAPARTICULARPARTBYNUMBERSUCHASTHELEFTDOOR s -OVEhDOWNvTOTHEFIRSTCHILDTHEDOORHANDLE s -OVEhUPvTOITSPARENTTHEBODY s -OVEhSIDEWAYSvTOTHENEXTCHILDTHERIGHTDOOR 2ETRIEVINGTHEDATAINAHIERARCHICALDATABASETHUSREQUIREDNAVIGATINGTHROUGHTHERECORDS MOVINGUP DOWN ANDSIDEWAYSONERECORDATATIME
1, Ê{ÓÊ Ê
iÀ>ÀV
V>ÊLv>ÌiÀ>ÃÊ`>Ì>L>Ãi
0!24ç)
/NEOFTHEMOSTIMPORTANTAPPLICATIONSFORTHEEARLIESTDATABASEMANAGEMENTSYSTEMSWAS MANAGINGOPERATIONSFORMANUFACTURINGCOMPANIES)FANAUTOMOBILEMANUFACTURERDECIDED TOPRODUCE UNITSOFONECARMODELANDUNITSOFANOTHERMODEL ITNEEDEDTO KNOWHOWMANYPARTSTOORDERFROMITSSUPPLIERS4OANSWERTHEQUESTION THEPRODUCTA CAR HADTOBEDECOMPOSEDINTOHUNDREDSOFASSEMBLIESENGINE BODY CHASSIS WHICHWERE DECOMPOSEDINTOTHOUSANDSOFSUBASSEMBLIESVALVES CYLINDERS SPARKPLUGS ANDTHENINTO SUB SUBASSEMBLIES ANDSOON(ANDLINGTHISLISTOFPARTS KNOWNASABILLOFMATERIALSWASA JOBTAILOR MADEFORCOMPUTERS 4HEBILLOFMATERIALSFORAPRODUCTHASANATURALHIERARCHICALSTRUCTURE4OSTORETHISDATA THEHIERARCHICALDATAMODEL ILLUSTRATEDIN&IGURE WASDEVELOPED)NTHISMODEL EACH RECORDINTHEDATABASEREPRESENTEDASPECIFICPART4HERECORDSHADPARENTCHILDRELATIONSHIPS LINKINGEACHPARTTOITSSUBPART ANDSOON 4OACCESSTHEDATAINTHEDATABASE APROGRAMCOULDPERFORMTHEFOLLOWINGTASKS
ç
0ARTç)ç
!Nç/VERVIEWçOFç31,
/NEOFTHEMOSTPOPULARHIERARCHICALDATABASEMANAGEMENTSYSTEMSWAS)"-S )NFORMATION-ANAGEMENT3YSTEM)-3 FIRSTINTRODUCEDIN4HEADVANTAGESOF)-3 ANDITSHIERARCHICALMODELFOLLOW s 3IMPLESTRUCTURE 4HEORGANIZATIONOFAN)-3DATABASEWASEASYTOUNDERSTAND 4HEDATABASEHIERARCHYPARALLELEDTHATOFACOMPANYORGANIZATIONCHARTORAFAMILY TREE s 0ARENTCHILDORGANIZATION !N)-3DATABASEWASEXCELLENTFORREPRESENTING PARENTCHILDRELATIONSHIPS SUCHASh!ISAPARTOF"vORh!ISOWNEDBY"v s 0ERFORMANCE )-3STOREDPARENTCHILDRELATIONSHIPSASPHYSICALPOINTERSFROMONE DATARECORDTOANOTHER SOTHATMOVEMENTTHROUGHTHEDATABASEWASRAPID )-3ISSTILLAWIDELYUSED$"-3ON)"-MAINFRAMES)TSRAWPERFORMANCEMAKESITIDEAL FORVERYHIGHVOLUMETRANSACTION PROCESSINGAPPLICATIONSSUCHASPROCESSINGCREDITCARD TRANSACTIONSORBOOKINGAIRLINERESERVATIONS$RAMATICIMPROVEMENTSINRELATIONALDATABASE PERFORMANCEOVERTHELASTTWODECADESHAVENARROWED)-3SPERFORMANCEADVANTAGE BUTTHE LARGEAMOUNTOFCORPORATEDATASTOREDIN)-3DATABASESANDTHELARGENUMBEROFMATURE APPLICATIONSTHATPROCESSTHATDATAENSURETHAT)-3USEWILLCONTINUEFORMANYYEARSTOCOME
.ETWORKõ$ATABASES 4HESIMPLESTRUCTUREOFAHIERARCHICALDATABASEBECAMEADISADVANTAGEWHENTHEDATAHADA MORECOMPLEXSTRUCTURE)NANORDER PROCESSINGDATABASE FOREXAMPLE ASINGLEORDERMIGHT PARTICIPATEINTHREEDIFFERENTPARENTCHILDRELATIONSHIPS LINKINGTHEORDERTOTHECUSTOMER WHOPLACEDIT THESALESPERSONWHOTOOKIT ANDTHEPRODUCTORDERED ASSHOWNIN&IGURE 4HISTYPEOFDATASTRUCTURESIMPLYDIDNTFITTHESTRICTHIERARCHYOF)-3 4ODEALWITHAPPLICATIONSSUCHASORDERPROCESSING ANEWNETWORKDATAMODELWAS DEVELOPED4HENETWORKDATAMODELEXTENDEDTHEHIERARCHICALMODELBYALLOWINGARECORD TOPARTICIPATEINMULTIPLEPARENTCHILDRELATIONSHIPS CALLEDSETS ASSHOWNIN&IGURE
1, Ê{ÎÊ ÕÌ«iÊ«>ÀiÌÉV
`ÊÀi>ÌÃ
«Ã
#HAPTERçç
2ELATIONALç$ATABASESç
0!24ç)
1, Ê{{Ê ÊiÌÜÀÊ " -9®ÊÀ`iÀ«ÀViÃÃ}Ê`>Ì>L>Ãi
)N THE#ONFERENCEON$ATA3YSTEMS,ANGUAGESPUBLISHEDANOFFICIALSTANDARDFOR NETWORKDATABASES CALLEDTHE#/$!39,MODEL)"-NEVERDEVELOPEDANETWORK$"-3 BUTDURINGTHES INDEPENDENTSOFTWARECOMPANIESRUSHEDTOEMBRACETHENETWORK MODEL CREATINGPRODUCTSSUCHAS#ULLINETS)$-3 #INCOMS4OTAL ANDTHE!DABAS$"-3 THATBECAMEVERYPOPULAR(OWEVER )"-ENHANCED)-3TOPROVIDEAWORKAROUNDTOTHE SINGLE PARENTRULEINCLASSICHIERARCHICALSTRUCTURES CALLINGTHEADDITIONALPARENTSLOGICAL PARENTS4HEDATAMODELBECAMEKNOWNASTHEEXTENDEDHIERARCHICALMODEL ANDITMADE )-3ADIRECTCOMPETITORWITHTHENETWORK$"-3PRODUCTS &ORAPROGRAMMER ACCESSINGANETWORKDATABASEWASVERYSIMILARTOACCESSINGA HIERARCHICALDATABASE!NAPPLICATIONPROGRAMCOULDDOTHEFOLLOWING s &INDASPECIFICPARENTRECORDBYKEYSUCHASACUSTOMERNUMBER s -OVEDOWNTOTHEFIRSTCHILDINAPARTICULARSETTHEFIRSTORDERPLACEDBYTHIS CUSTOMER s -OVESIDEWAYSFROMONECHILDTOTHENEXTINTHESETTHENEXTORDERPLACEDBYTHE SAMECUSTOMER s -OVEUPFROMACHILDTOITSPARENTINANOTHERSETTHESALESPERSONWHOTOOKTHEORDER /NCEAGAIN THEPROGRAMMERHADTONAVIGATETHEDATABASERECORDBYRECORD THISTIME SPECIFYINGWHICHRELATIONSHIPTONAVIGATEASWELLASTHEDIRECTION .ETWORKDATABASESHADSEVERALADVANTAGES s &LEXIBILITY -ULTIPLEPARENTCHILDRELATIONSHIPSALLOWEDANETWORKDATABASETO REPRESENTDATATHATDIDNOTHAVEASIMPLEHIERARCHICALSTRUCTURE s 3TANDARDIZATION 4HE#/$!39,STANDARDBOOSTEDTHEPOPULARITYOFTHENETWORK MODEL MAKINGITEASIERFORPROGRAMMERSTOMOVEBETWEEN$"-3PRODUCTS s 0ERFORMANCE 0ARENTCHILDSETSWEREREPRESENTEDBYPOINTERSTOPHYSICALDATA RECORDS ALLOWINGRAPIDNAVIGATIONTHROUGHTHESERELATIONSHIPS
ç
0ARTç)ç
!Nç/VERVIEWçOFç31,
.ETWORKDATABASESHADTHEIRDISADVANTAGES TOO,IKEHIERARCHICALDATABASES THEYWERE VERYRIGID4HESETRELATIONSHIPSANDTHESTRUCTUREOFTHERECORDSHADTOBESPECIFIEDIN ADVANCE#HANGINGTHEDATABASESTRUCTURETYPICALLYREQUIREDREBUILDINGTHEENTIREDATABASE "OTHHIERARCHICALANDNETWORKDATABASESWERETOOLSFORPROGRAMMERS4OANSWERA QUESTIONSUCHASh7HATISTHEMOSTPOPULARPRODUCTORDEREDBY!CME-ANUFACTURINGvOR h(OWMANYORDERSARETHEREFOR3IZE7IDGETSvAPROGRAMMERHADTOWRITEAPROGRAM THATNAVIGATEDITSWAYTHROUGHTHEDATABASE FOUNDTHEAPPROPRIATERECORDS ANDCALCULATED THERESULT4HEBACKLOGOFREQUESTSFORCUSTOMREPORTSOFTENSTRETCHEDTOWEEKSORMONTHS ANDBYTHETIMETHEPROGRAMWASWRITTEN THEINFORMATIONITDELIVEREDWASOFTENWORTHLESS 4HEDISADVANTAGESOFTHEHIERARCHICALANDNETWORKMODELSLEDTOINTENSEINTERESTINTHE NEWRELATIONALDATAMODELWHENITWASFIRSTDESCRIBEDBY4ED#ODDIN!TFIRSTTHE RELATIONALMODELWASLITTLEMORETHANANACADEMICCURIOSITY.ETWORKDATABASESCONTINUED TOBEIMPORTANTTHROUGHOUTTHESANDEARLYS PARTICULARLYONTHEMINICOMPUTER SYSTEMSTHATWERESURGINGINPOPULARITY(OWEVER BYTHEMID S THERELATIONALMODEL WASCLEARLYEMERGINGASTHEhNEWWAVEvINDATAMANAGEMENT"YTHEEARLYS NETWORK ANDHIERARCHICALDATABASESWERECLEARLYDECLININGINIMPORTANCE ANDTODAYTHEYPLAYONLY AMINORROLEINTHEDATABASEMARKET
4HEõ2ELATIONALõ$ATAõ-ODEL 4HERELATIONALMODELPROPOSEDBY#ODDWASANATTEMPTTOSIMPLIFYDATABASESTRUCTURE)T ELIMINATEDTHEEXPLICITPARENTCHILDSTRUCTURESFROMTHEDATABASEANDINSTEADREPRESENTED ALLDATAINTHEDATABASEASSIMPLEROWCOLUMNTABLESOFDATAVALUES&IGURE SHOWSA RELATIONALVERSIONOFTHENETWORKORDER PROCESSINGDATABASEIN&IGURE
1, Ê{xÊ ÊÀi>Ì>ÊÀ`iÀ«ÀViÃÃ}Ê`>Ì>L>Ãi
#HAPTERçç
2ELATIONALç$ATABASESç
!RELATIONALDATABASEISADATABASEWHEREALLDATAVISIBLETOTHEUSERISORGANIZEDSTRICTLY ASTABLESOFDATAVALUES ANDWHEREALLDATABASEOPERATIONSWORKONTHESETABLES 4HEDEFINITIONISINTENDEDSPECIFICALLYTORULEOUTANYUSER VISIBLESTRUCTURESSUCHASTHE EMBEDDEDPOINTERSOFAHIERARCHICALORNETWORKDATABASE!RELATIONAL$"-3CANREPRESENT PARENTCHILDRELATIONSHIPS BUTTHEYAREVISIBLEONLYTHROUGHTHEDATAVALUESCONTAINEDIN THEDATABASETABLES
4HEõ3AMPLEõ$ATABASE &IGURE SHOWSASMALLRELATIONALDATABASEFORANORDER PROCESSINGAPPLICATION4HISSAMPLE DATABASEISUSEDTHROUGHOUTTHISBOOKANDPROVIDESTHEBASISFORMOSTOFTHEEXAMPLES !PPENDIX!CONTAINSACOMPLETEDESCRIPTIONOFTHEDATABASESTRUCTUREANDITSCONTENTS &IGURE SHOWSONLYAFEWROWSOFEACHTABLEnTHECOMPLETECONTENTSOFEACHTABLEARE INCLUDEDIN!PPENDIX!
&"
!'(1+
/11 *'27
'6< 43+7
9+
2/8.
!!
&
"!
'1+7 +5
'1+7 +5
'1+7 +5
"! !'(1+ & "!&
!
%
'8).+8 /30 #/*-+8 +24:+6
$0
+*9)+6
&!
!%&&
!'(1+
&" &!
" !
!'(1+ !%
+3:+6
./)'-4
+; %460
$
#+78+63 '78+63 '78+63
" ! " !&"
1, Ê{ÈÊ /
iÊÃ>«iÊ`>Ì>L>ÃiÊ«>ÀÌ>ÊÃÌ}®
"!
!%
"!
!!
!'(1+ % 3) /678 465 )2+ ,-
" !&
!&!
0!24ç)
#ODDSWORKPRODUCEDAPRECISE MATHEMATICALDEFINITIONOFARELATIONALDATABASE ANDATHEORETICALBASISFORTHEDATABASEOPERATIONSTHATCOULDBEPERFORMEDONIT(OWEVER AMOREINFORMALDEFINITIONOFARELATIONALDATABASEISUSEFUL
ç
0ARTç)ç
!Nç/VERVIEWçOFç31,
4HESAMPLEDATABASECONTAINSFIVETABLES%ACHTABLESTORESINFORMATIONABOUTONE PARTICULARKINDOFENTITY s 4HE3!,%32%03TABLESTORESTHEEMPLOYEENUMBER NAME AGE YEAR TO DATESALES ANDOTHERDATAABOUTEACHSALESPERSON s 4HE02/$5#43TABLESTORESDATAABOUTEACHPRODUCTAVAILABLEFORSALE SUCHASTHE MANUFACTURER PRODUCTNUMBER DESCRIPTION ANDPRICE s 4HE/2$%23TABLEKEEPSTRACKOFEVERYORDERPLACEDBYACUSTOMER IDENTIFYINGTHE SALESPERSONWHOTOOKTHEORDER THEPRODUCTORDERED THEQUANTITYANDAMOUNTOF THEORDER ANDSOON&ORSIMPLICITY EACHORDERISFORONLYONEPRODUCT s 4HE/&&)#%3TABLESTORESDATAABOUTEACHOFTHESALESOFFICES INCLUDINGTHECITY WHERETHEOFFICEIS THESALESREGIONITBELONGSTO ANDSOON s 4HE#534/-%23TABLESTORESDATAABOUTEACHCUSTOMER SUCHASTHECOMPANYNAME CREDITLIMIT ANDTHESALESPERSONWHOCALLSONTHECUSTOMER
4ABLES 4HEORGANIZINGPRINCIPLEINARELATIONALDATABASEISTHETABLE ARECTANGULARROWCOLUMN ARRANGEMENTOFDATAVALUES%ACHTABLEINADATABASEHASAUNIQUETABLENAMETHATIDENTIFIES ITSCONTENTS!CTUALLY EACHUSERCANCHOOSEHISORHEROWNTABLENAMESWITHOUTWORRYING ABOUTTHENAMESCHOSENBYOTHERUSERS ASEXPLAINEDIN#HAPTER 4HEROWCOLUMNSTRUCTUREOFATABLEISSHOWNMORECLEARLYIN&IGURE WHICHISAN ENLARGEDVIEWOFTHE/&&)#%3TABLE%ACHHORIZONTALROWOFTHE/&&)#%3TABLEREPRESENTS ASINGLEPHYSICALENTITYASINGLESALESOFFICE4OGETHERTHEFIVEROWSOFTHETABLEREPRESENT ALLFIVEOFTHECOMPANYSSALESOFFICES!LLOFTHEDATAINAPARTICULARROWOFTHETABLEAPPLIES TOTHEOFFICEREPRESENTEDBYTHATROW %ACHCOLUMNOFTHE/&&)#%3TABLEREPRESENTSONEITEMOFDATATHATISSTOREDINTHE DATABASEFOREACHOFFICE&OREXAMPLE THE#)49COLUMNHOLDSTHELOCATIONOFEACHOFFICE 4HE3!,%3COLUMNCONTAINSEACHOFFICESYEAR TO DATESALESTOTAL4HE-'2COLUMNSHOWS THEEMPLOYEENUMBEROFTHEPERSONWHOMANAGESTHEOFFICE %ACHROWOFATABLECONTAINSEXACTLYONEDATAVALUEINEACHCOLUMN)NTHEROW REPRESENTINGTHE.EW9ORKOFFICE FOREXAMPLE THE#)49COLUMNCONTAINSTHEVALUEh.EW 9ORKv4HE3!,%3COLUMNCONTAINSTHEVALUEh v WHICHISTHEYEAR TO DATESALES TOTALFORTHE.EW9ORKOFFICE &OREACHCOLUMNOFATABLE ALLOFTHEDATAVALUESINTHATCOLUMNHOLDTHESAMETYPEOF DATA&OREXAMPLE ALLOFTHE#)49COLUMNVALUESARETEXT ALLOFTHE3!,%3VALUESAREMONEY AMOUNTS ANDALLOFTHE-'2VALUESAREINTEGERSREPRESENTINGEMPLOYEENUMBERS 4HESETOF DATAVALUESTHATACOLUMNCANCONTAINISCALLEDTHEDOMAINOFTHECOLUMN4HEDOMAINOFTHE #)49COLUMNISTHESETOFALLNAMESOFCITIES4HEDOMAINOFTHE3!,%3COLUMNISANY MONEYAMOUNT4HEDOMAINOFTHE2%')/.COLUMNISJUSTTWODATAVALUES h%ASTERNvAND h7ESTERNv BECAUSETHOSEARETHEONLYTWOSALESREGIONSTHECOMPANYHAS %ACHCOLUMNINATABLEHASACOLUMNNAME WHICHISUSUALLYWRITTENASAHEADINGATTHE TOPOFTHECOLUMN4HECOLUMNSOFATABLEMUSTALLHAVEDIFFERENTNAMES BUTTHEREISNO PROHIBITIONAGAINSTTWOCOLUMNSINTWODIFFERENTTABLESHAVINGIDENTICALNAMES)NFACT FREQUENTLYUSEDCOLUMNNAMESSUCHAS.!-% !$$2%33 149 02)#% AND3!,%3AREOFTEN FOUNDINMANYDIFFERENTTABLESOFAPRODUCTIONDATABASE
#HAPTERçç
2ELATIONALç$ATABASESç
0!24ç)
1, Ê{ÇÊ /
iÊÀÜÉVÕÊÃÌÀÕVÌÕÀiÊvÊ>ÊÀi>Ì>ÊÌ>Li
4HECOLUMNSOFATABLEHAVEALEFT TO RIGHTORDER WHICHISDEFINEDWHENTHETABLEISFIRST CREATED!TABLEALWAYSHASATLEASTONECOLUMN4HE!.3))3/31,STANDARDDOESNOT SPECIFYAMAXIMUMNUMBEROFCOLUMNSINATABLE BUTALMOSTALLCOMMERCIAL31,PRODUCTS DOIMPOSEALIMIT WHICHISSELDOMLESSTHANCOLUMNS 5NLIKETHECOLUMNS THEROWSINATABLEDONOTHAVEANYPARTICULARORDER)NFACT IFYOU USETWOCONSECUTIVEDATABASEQUERIESTODISPLAYTHECONTENTSOFATABLE THEREISNOGUARANTEE THATTHEROWSWILLBELISTEDINTHESAMEORDERTWICE/FCOURSEYOUCANASK31,TOSORTTHEROWS BEFOREDISPLAYINGTHEM BUTTHESORTEDORDERHASNOTHINGTODOWITHTHEACTUALARRANGEMENT OFTHEROWSWITHINTHETABLE !TABLECANHAVEANYNUMBEROFROWS!TABLEOFZEROROWSISPERFECTLYLEGALANDISCALLED ANEMPTYTABLEFOROBVIOUSREASONS !NEMPTYTABLESTILLHASASTRUCTURE IMPOSEDBYITS COLUMNSITSIMPLYCONTAINSNODATA4HE!.3))3/STANDARDDOESNOTLIMITTHENUMBEROF ROWSINATABLE ANDMANY31,PRODUCTSWILLALLOWATABLETOGROWUNTILITEXHAUSTSTHE AVAILABLESTORAGE/THER31,PRODUCTSIMPOSEALIMIT BUTITISALWAYSAVERYGENEROUSONE BILLIONROWSORMOREISCOMMON
0RIMARYõ+EYS "ECAUSETHEROWSOFARELATIONALTABLEAREUNORDERED YOUCANNOTSELECTASPECIFICROWBYITS POSITIONINTHETABLE4HEREISNOhFIRSTROW vhLASTROW vORhTHROWvOFATABLE(OW THEN CANYOUSPECIFYAPARTICULARROW SUCHASTHEROWFORTHE$ENVERSALESOFFICE )NAWELL DESIGNEDRELATIONALDATABASE EVERYTABLEHASSOMECOLUMNORCOMBINATIONOF COLUMNSWHOSEVALUESUNIQUELYIDENTIFYEACHROWINTHETABLE4HISCOLUMNORCOLUMNS ISCALLEDTHEPRIMARYKEYOFTHETABLE,OOKONCEAGAINATTHE/&&)#%3TABLEIN&IGURE
ç
0ARTç)ç
!Nç/VERVIEWçOFç31,
!TFIRSTGLANCE EITHERTHE/&&)#%COLUMNORTHE#)49COLUMNCOULDSERVEASAPRIMARYKEY FORTHETABLE"UTIFTHECOMPANYEXPANDSANDOPENSTWOSALESOFFICESINTHESAMECITY THE #)49COLUMNCOULDNOLONGERSERVEASTHEPRIMARYKEY)NPRACTICE h)$NUMBERSvSUCHAS ANOFFICENUMBER/&&)#%INTHE/&&)#%3TABLE ANEMPLOYEENUMBER%-0,?.5-INTHE 3!,%32%03TABLE ANDCUSTOMERNUMBERS#534?.5-INTHE#534/-%23TABLE AREOFTEN CHOSENASPRIMARYKEYS)NTHECASEOFTHE/2$%23TABLE YOUHAVENOCHOICETHEONLYTHING THATUNIQUELYIDENTIFIESANORDERISITSORDERNUMBER/2$%2?.5- 4HE02/$5#43TABLE PARTOFWHICHISSHOWNIN&IGURE ISANEXAMPLEOFATABLE WHERETHEPRIMARYKEYMUSTBEACOMBINATIONOFCOLUMNS4HE-&2?)$COLUMNIDENTIFIESTHE MANUFACTUREROFEACHPRODUCTINTHETABLE ANDTHE02/$5#4?)$COLUMNSPECIFIESTHE MANUFACTURERSPRODUCTNUMBER4HE02/$5#4?)$COLUMNMIGHTAPPEARTOMAKEAGOOD PRIMARYKEY BUTTHERESNOTHINGTOPREVENTTWODIFFERENTMANUFACTURERSFROMUSINGTHE SAMENUMBERFORTHEIRPRODUCTS4HEREFORE ACOMBINATIONOFTHE-&2?)$AND02/$5#4?)$ COLUMNSMUSTBEUSEDASTHEPRIMARYKEYOFTHE02/$5#43TABLE%VERYPRODUCTINTHETABLE ISGUARANTEEDTOHAVEAUNIQUECOMBINATIONOFDATAVALUESINTHESETWOCOLUMNS 4HEPRIMARYKEYHASADIFFERENTUNIQUEVALUEFOREACHROWINATABLE SONOTWOROWSOF ATABLEWITHAPRIMARYKEYAREEXACTDUPLICATESOFONEANOTHER!TABLEWHEREEVERYROWIS DIFFERENTFROMALLOTHERROWSISCALLEDARELATIONINMATHEMATICALTERMS4HENAMEhRELATIONAL DATABASEvCOMESFROMTHISTERM BECAUSERELATIONSTABLESWITHDISTINCTROWS AREATTHEHEART OFARELATIONALDATABASE !LTHOUGHPRIMARYKEYSAREANESSENTIALPARTOFTHERELATIONALDATAMODEL EARLYRELATIONAL DATABASEMANAGEMENTSYSTEMS3YSTEM2 $" /RACLE ANDOTHERS DIDNOTPROVIDEEXPLICIT SUPPORTFORPRIMARYKEYS$ATABASEDESIGNERSUSUALLYENSUREDTHATALLOFTHETABLESINTHEIR DATABASESHADAPRIMARYKEY BUTTHE$"-3ITSELFDIDNOTPROVIDEAWAYTOIDENTIFYTHE PRIMARYKEYOFATABLE$"6ERSION INTRODUCEDIN!PRIL WASTHEFIRSTOF)"-S COMMERCIAL31,PRODUCTSTOSUPPORTPRIMARYKEYS4HE!.3))3/STANDARDWAS SUBSEQUENTLYEXPANDEDTOINCLUDEADEFINITIONOFPRIMARYKEYSUPPORT ANDTODAY NEARLYALL RELATIONALDATABASEMANAGEMENTSYSTEMSPROVIDEIT
1, Ê{nÊ ÊÌ>LiÊÜÌ
Ê>ÊV«ÃÌiÊ«À>ÀÞÊiÞ
#HAPTERçç
2ELATIONALç$ATABASESç
2ELATIONSHIPS
1, Ê{Ê Ê«>ÀiÌÉV
`ÊÀi>ÌÃ
«ÊÊ>ÊÀi>Ì>Ê`>Ì>L>Ãi
0!24ç)
/NEOFTHEMAJORDIFFERENCESBETWEENTHERELATIONALMODELANDEARLIERDATAMODELSISTHAT EXPLICITPOINTERSSUCHASTHEPARENTCHILDRELATIONSHIPSOFAHIERARCHICALDATABASEAREBANNED FROMRELATIONALDATABASES9ET OBVIOUSLY THESERELATIONSHIPSEXISTINARELATIONALDATABASE &OREXAMPLE INTHESAMPLEDATABASE EACHSALESPERSONISASSIGNEDTOAPARTICULARSALES OFFICE SOTHEREISANOBVIOUSRELATIONSHIPBETWEENTHEROWSOFTHE/&&)#%3TABLEANDTHE ROWSOFTHE3!,%32%03TABLE$OESNTTHERELATIONALMODELhLOSEINFORMATIONvBYBANNING THESERELATIONSHIPSFROMTHEDATABASE !SSHOWNIN&IGURE THEANSWERTOTHEQUESTIONIShNOv4HEFIGURESHOWSACLOSE UP OFAFEWROWSOFTHE/&&)#%3AND3!,%32%03TABLES.OTETHATTHE2%0?/&&)#%COLUMN OFTHE3!,%32%03TABLECONTAINSTHEOFFICENUMBEROFTHESALESOFFICEWHEREEACHSALESPERSON WORKS4HEDOMAINOFTHISCOLUMNTHESETOFLEGALVALUESITMAYCONTAIN ISPRECISELYTHESET OFOFFICENUMBERSFOUNDINTHE/&&)#%COLUMNOFTHE/&&)#%3TABLE)NFACT YOUCANFIND THESALESOFFICEWHERE-ARY*ONESWORKSBYFINDINGTHEVALUEIN-ARYS2%0?/&&)#% COLUMN ANDFINDINGTHEROWOFTHE/&&)#%3TABLETHATHASAMATCHINGVALUEINTHE /&&)#%COLUMNINTHEROWFORTHE.EW9ORKOFFICE 3IMILARLY TOFINDALLTHESALESPEOPLEWHO WORKIN.EW9ORK YOUCOULDNOTETHE/&&)#%VALUEFORTHE.EW9ORKROW ANDTHENSCAN DOWNTHE2%0?/&&)#%COLUMNOFTHE3!,%32%03TABLELOOKINGFORMATCHINGVALUESINTHE ROWSFOR-ARY*ONESAND3AM#LARK 4HEPARENTCHILDRELATIONSHIPBETWEENASALESOFFICEANDTHEPEOPLEWHOWORKTHERE ISNTLOSTBYTHERELATIONALMODELITSJUSTNOTREPRESENTEDBYANEXPLICITPOINTERVISIBLETO THEUSER)NSTEAD THERELATIONSHIPISREPRESENTEDBYCOMMONDATAVALUESSTOREDINTHETWO TABLES!LLRELATIONSHIPSINARELATIONALDATABASEAREREPRESENTEDTHISWAY/NEOFTHEMAIN GOALSOFTHE31,ISTOLETYOURETRIEVERELATEDDATAFROMTHEDATABASEBYMANIPULATINGTHESE RELATIONSHIPSINASIMPLE STRAIGHTFORWARDWAY
ç
0ARTç)ç
!Nç/VERVIEWçOFç31,
&OREIGNõ+EYS !COLUMNINONETABLEWHOSEVALUEMATCHESTHEPRIMARYKEYINSOMEOTHERTABLEISCALLEDA FOREIGNKEY)N&IGURE THE2%0?/&&)#%COLUMNISAFOREIGNKEYFORTHE/&&)#%3TABLE !LTHOUGH2%0?/&&)#%ISACOLUMNINTHE3!,%32%03TABLE THEVALUESTHATTHISCOLUMN CONTAINSAREOFFICENUMBERS4HEYMATCHVALUESINTHE/&&)#%COLUMN WHICHISTHE PRIMARYKEYFORTHE/&&)#%3TABLE4OGETHER APRIMARYKEYANDAFOREIGNKEYCREATEA PARENTCHILDRELATIONSHIPBETWEENTHETABLESTHATCONTAINTHEM JUSTLIKETHEPARENTCHILD RELATIONSHIPSINAHIERARCHICALDATABASE *USTASACOMBINATIONOFCOLUMNSCANSERVEASTHEPRIMARYKEYOFATABLE AFOREIGNKEY CANALSOBEACOMBINATIONOFCOLUMNS)NFACT THEFOREIGNKEYWILLALWAYSBEACOMPOUND MULTICOLUMN KEYWHENITREFERENCESATABLEWITHACOMPOUNDPRIMARYKEY/BVIOUSLY THE NUMBEROFCOLUMNSANDTHEDATATYPESOFTHECOLUMNSINTHEFOREIGNKEYANDTHEPRIMARY KEYMUSTBEIDENTICALTOONEANOTHER !TABLECANCONTAINMORETHANONEFOREIGNKEYIFITISRELATEDTOMORETHANONEOTHER TABLE&IGURE SHOWSTHETHREEFOREIGNKEYSINTHE/2$%23TABLEOFTHESAMPLEDATABASE s 4HE#534COLUMNISAFOREIGNKEYFORTHE#534/-%23TABLE RELATINGEACHORDERTO THECUSTOMERWHOPLACEDIT s 4HE2%0COLUMNISAFOREIGNKEYFORTHE3!,%32%03TABLE RELATINGEACHORDERTOTHE SALESPERSONWHOTOOKIT s 4HE-&2AND02/$5#4COLUMNSTOGETHERAREACOMPOSITEFOREIGNKEYFORTHE 02/$5#43TABLE RELATINGEACHORDERTOTHEPRODUCTBEINGORDERED 4HEMULTIPLEPARENTCHILDRELATIONSHIPSCREATEDBYTHETHREEFOREIGNKEYSINTHE/2$%23 TABLEMAYSEEMFAMILIARTOYOU ANDTHEYSHOULD4HEYAREPRECISELYTHESAMERELATIONSHIPS ASTHOSEINTHENETWORKDATABASEOF&IGURE !STHEEXAMPLESHOWS THERELATIONALDATA MODELHASALLOFTHEPOWEROFTHENETWORKMODELTOEXPRESSCOMPLEXRELATIONSHIPS
1, Ê{£äÊ ÕÌ«iÊ«>ÀiÌÉV
`ÊÀi>ÌÃ
«ÃÊÊ>ÊÀi>Ì>Ê`>Ì>L>Ãi
#HAPTERçç
2ELATIONALç$ATABASESç
#ODDSõõ2ULESõFORõ2ELATIONALõ$ATABASES
!STHERELATIONALDATABASEMODELSTARTEDTOBECOMEVERYPOPULARINTHEMID S EVERY $"-3VENDORSCRAMBLEDTODESCRIBETHEIRPRODUCTAShRELATIONALv3OMEOFTHESEPRODUCTS HADONLYA31, LIKEQUERYLANGUAGELAYEREDONTOPOFANUNDERLYINGNETWORKORHIERARCHICAL DATABASE3OMEOFTHEMIMPLEMENTEDONLYAVERYRUDIMENTARYTABLESTRUCTUREANDNOQUERY LANGUAGEATALL3OONTHEQUESTIONOFh7HATISATRUERELATIONALDATABASEvBECAMEATOPIC OFDEBATE AND$"-3VENDORSBEGANCLAIMINGTHATTHEIRPRODUCTSWEREhMORERELATIONALv THANTHECOMPETITION )N 4ED#ODD WHOSESEMINALTECHNICALARTICLEYEARSEARLIERHADDEFINEDTHE RELATIONALDATAMODEL ADDRESSEDTHISQUESTIONIN#OMPUTERWORLD ONEOFTHELEADINGTRADE PUBLICATIONS)NHISTWO PARTARTICLE ENTITLED)S9OUR$"-32EALLY2ELATIONAL/CTOBER AND$OES9OUR$"-32UN"YTHE2ULES/CTOBER #ODDPRESENTEDRULESTHATA DATABASEMUSTOBEYIFITISTOBECONSIDEREDTRULYRELATIONAL
)NFORMATIONRULE!LLINFORMATIONINARELATIONALDATABASEISREPRESENTEDEXPLICITLYAT THELOGICALLEVELANDINEXACTLYONEWAYBYVALUESINTABLES
'UARANTEEDACCESSRULE%ACHANDEVERYDATUMATOMICVALUE INARELATIONALDATABASE ISGUARANTEEDTOBELOGICALLYACCESSIBLEBYRESORTINGTOACOMBINATIONOFTABLENAME PRIMARYKEYVALUE ANDCOLUMNNAME
3YSTEMATICTREATMENTOF.5,,VALUES.5,,VALUESDISTINCTFROMANEMPTYCHARACTER STRINGORASTRINGOFBLANKCHARACTERSANDDISTINCTFROMZEROORANYOTHERNUMBER ARESUPPORTEDINAFULLYRELATIONAL$"-3FORREPRESENTINGMISSINGINFORMATIONAND INAPPLICABLEINFORMATIONINASYSTEMATICWAY INDEPENDENTOFTHEDATATYPE
$YNAMICONLINECATALOGBASEDONTHERELATIONALMODEL4HEDATABASEDESCRIPTIONIS REPRESENTEDATTHELOGICALLEVELINTHESAMEWAYASORDINARYDATA SOTHATAUTHORIZED USERSCANAPPLYTHESAMERELATIONALLANGUAGETOITSINTERROGATIONASTHEYAPPLYTO THEREGULARDATA
#OMPREHENSIVEDATASUBLANGUAGERULE!RELATIONALSYSTEMMAYSUPPORTSEVERAL LANGUAGESANDVARIOUSMODESOFTERMINALUSEFOREXAMPLE THEFILL IN THE BLANKS MODE (OWEVER THEREMUSTBEATLEASTONELANGUAGEWHOSESTATEMENTSARE EXPRESSIBLE PERSOMEWELL DEFINEDSYNTAX ASCHARACTERSTRINGS ANDTHATIS COMPREHENSIVEINSUPPORTINGALLOFTHEFOLLOWINGITEMS s $ATADEFINITION s 6IEWDEFINITION s $ATAMANIPULATIONINTERACTIVEANDBYPROGRAM s )NTEGRITYCONSTRAINTS s !UTHORIZATION s 4RANSACTIONBOUNDARIESBEGIN COMMIT ANDROLLBACK
0!24ç)
&OREIGNKEYSAREAFUNDAMENTALPARTOFTHERELATIONALMODELBECAUSETHEYCREATE RELATIONSHIPSAMONGTABLESINTHEDATABASE!SWITHPRIMARYKEYS FOREIGNKEYSUPPORTWAS MISSINGFROMEARLYRELATIONALDATABASEMANAGEMENTSYSTEMS4HEYWEREADDEDTO$" 6ERSION WERESUBSEQUENTLYADDEDTOTHE!.3))3/STANDARD ANDNOWAPPEARINALLOF THEMAJORCOMMERCIALPRODUCTS
ç
0ARTç)ç
!Nç/VERVIEWçOFç31,
6IEWUPDATINGRULE!LLVIEWSTHATARETHEORETICALLYUPDATEABLEAREALSOUPDATEABLE BYTHESYSTEM
(IGH LEVELINSERT UPDATE ANDDELETE4HECAPABILITYOFHANDLINGABASERELATIONORA DERIVEDRELATIONASASINGLEOPERANDAPPLIESNOTONLYTOTHERETRIEVALOFDATA BUT ALSOTOTHEINSERTION UPDATE ANDDELETIONOFDATA
0HYSICALDATAINDEPENDENCE!PPLICATIONPROGRAMSANDTERMINALACTIVITIESREMAIN LOGICALLYUNIMPAIREDWHENEVERANYCHANGESAREMADEINEITHERSTORAGE REPRESENTATIONSORACCESSMETHODS
,OGICALDATAINDEPENDENCE!PPLICATIONPROGRAMSANDTERMINALACTIVITIESREMAIN LOGICALLYUNIMPAIREDWHENINFORMATION PRESERVINGCHANGESOFANYKINDTHAT THEORETICALLYPERMITUNIMPAIRMENTAREMADETOTHEBASETABLES
)NTEGRITYINDEPENDENCE)NTEGRITYCONSTRAINTSSPECIFICTOAPARTICULARRELATIONAL DATABASEMUSTBEDEFINABLEINTHERELATIONALDATASUBLANGUAGEANDSTORABLEINTHE CATALOG NOTINTHEAPPLICATIONPROGRAMS $ISTRIBUTIONINDEPENDENCE!RELATIONAL$"-3HASDISTRIBUTIONINDEPENDENCE .ONSUBVERSIONRULE)FARELATIONALSYSTEMHASALOW LEVELSINGLERECORDATATIME LANGUAGE THATLOWLEVELCANNOTBEUSEDTOSUBVERTORBYPASSTHEINTEGRITYRULES ANDCONSTRAINTSEXPRESSEDINTHEHIGHER LEVELRELATIONALLANGUAGEMULTIPLERECORDS ATATIME !LTHOUGHTHECONTROVERSYHASLONGSINCEDIEDOUT THERULESAREINTERESTINGFROMA HISTORICALPERSPECTIVE BECAUSETHEYRESOLVEDTHEISSUEONCEANDFORALL ANDTHEYDOOFFERA GOODINFORMALWORKINGDEFINITION2ULEISBASICALLYTHESINGLE SENTENCEFUNDAMENTAL DEFINITIONPRESENTEDEARLIERINTHISCHAPTERTHEOTHERSPROVIDEADDITIONALREFINEMENTAND REQUIREMENTS 2ULESTRESSESTHEIMPORTANCEOFPRIMARYKEYSFORLOCATINGDATAINTHEDATABASE4HE TABLENAMELOCATESTHECORRECTTABLE THECOLUMNNAMEFINDSTHECORRECTCOLUMN ANDTHE PRIMARYKEYVALUEFINDSTHEROWCONTAININGANINDIVIDUALDATAITEMOFINTEREST2ULE REQUIRESSUPPORTFORMISSINGDATATHROUGH.5,,VALUES WHICHAREDESCRIBEDIN#HAPTER 2ULEREQUIRESTHATARELATIONALDATABASEBESELF DESCRIBING THROUGHSYSTEMTABLES WHOSECOLUMNSDESCRIBETHESTRUCTUREOFTHEDATABASEITSELF4HESETABLESAREDESCRIBED IN#HAPTER 2ULEMANDATESUSINGARELATIONALDATABASELANGUAGE SUCHAS31, ALTHOUGH31,ISNOT SPECIFICALLYREQUIRED4HELANGUAGEMUSTBEABLETOSUPPORTALLTHECENTRALFUNCTIONSOFA $"-3 NOTJUSTDATABASEQUERIES 2ULEDEALSWITHVIEWS WHICHAREVIRTUALTABLESUSEDTOGIVEVARIOUSUSERSOFADATABASE DIFFERENTVIEWSOFITSSTRUCTURE6IEWSAREDESCRIBEDIN#HAPTER 2ULESTRESSESTHESET ORIENTEDNATUREOFARELATIONALDATABASE)TREQUIRESTHATROWSBE TREATEDASSETSININSERT DELETE ANDUPDATEOPERATIONS)TPROHIBITSSYSTEMSTHATSUPPORT ONLYROW AT A TIME NAVIGATIONALMODIFICATIONOFTHEDATABASE 2ULEAND2ULEINSULATETHEUSERORAPPLICATIONPROGRAMFROMTHELOW LEVEL IMPLEMENTATIONOFTHEDATABASEANDEVENFROMCHANGESINTHESTRUCTUREOFTHETABLES 2ULESAYSTHATTHEDATABASELANGUAGESHOULDSUPPORTTHEABILITYTODEFINERESTRICTIONS ONTHEDATATHATCANBEENTEREDANDTHEDATABASEMODIFICATIONSTHATCANBEMADE
#HAPTERçç
2ELATIONALç$ATABASESç
3UMMARY 31,ISBASEDONTHERELATIONALDATAMODELTHATORGANIZESTHEDATAINADATABASEASA COLLECTIONOFTABLES s %ACHTABLEHASATABLENAMETHATUNIQUELYIDENTIFIESIT s %ACHTABLEHASONEORMORENAMEDCOLUMNS WHICHAREARRANGEDINASPECIFIC LEFT TO RIGHTORDER s %ACHTABLEHASZEROORMOREROWS EACHCONTAININGASINGLEDATAVALUEINEACH COLUMN4HEROWSAREUNORDERED s !LLDATAVALUESINAGIVENCOLUMNHAVETHESAMEDATATYPEANDAREDRAWNFROMASET OFLEGALVALUESCALLEDTHEDOMAINOFTHECOLUMN 4ABLESARERELATEDTOONEANOTHERBYTHEDATATHEYCONTAIN4HERELATIONALDATAMODEL USESPRIMARYKEYSANDFOREIGNKEYSTOREPRESENTTHESERELATIONSHIPSAMONGTABLES s !PRIMARYKEYISACOLUMNORCOMBINATIONOFCOLUMNSINATABLEWHOSEVALUES UNIQUELYIDENTIFYEACHROWOFTHETABLE!TABLEHASONLYONEPRIMARYKEY s !FOREIGNKEYISACOLUMNORCOMBINATIONOFCOLUMNSINATABLEWHOSEVALUES ARE APRIMARYKEYVALUEFORSOMEOTHERTABLE!TABLECANCONTAINMORETHANONEFOREIGN KEY LINKINGITTOONEORMOREOTHERTABLES s !PRIMARYKEYFOREIGNKEYCOMBINATIONCREATESAPARENTCHILDRELATIONSHIPBETWEEN THETABLESTHATCONTAINTHEM
0!24ç)
2ULESAYSTHATTHEDATABASELANGUAGEMUSTBEABLETOMANIPULATEDISTRIBUTEDDATA LOCATEDONOTHERCOMPUTERSYSTEMSIFTHE$"-3SUPPORTSIT &INALLY 2ULEPREVENTShOTHERPATHSvINTOTHEDATABASETHATMIGHTSUBVERTITSRELATIONAL STRUCTUREANDINTEGRITY
This page intentionally left blank
**
0!24
2ETRIEVINGç$ATA
#(!04%2ç 31,"ASICS #(!04%2ç 3IMPLE1UERIES
1
UERIESARETHEHEARTOF31, ANDMANYPEOPLEUSE31,ASA DATABASEQUERYTOOL4HENEXTFIVECHAPTERSDESCRIBE31, QUERIESINDEPTH#HAPTERDESCRIBESTHEBASIC31,STRUCTURES THATYOUUSETOFORM31,STATEMENTS#HAPTERDISCUSSESSIMPLE QUERIESTHATDRAWDATAFROMASINGLETABLEOFDATA#HAPTEREXPANDS THEDISCUSSIONTOMULTITABLEQUERIES1UERIESTHATSUMMARIZEDATA AREDESCRIBEDIN#HAPTER&INALLY #HAPTEREXPLAINSTHE31, SUBQUERYCAPABILITYTHATISUSEDTOHANDLECOMPLEXQUERIES
#(!04%2ç -ULTITABLE1UERIES*OINS #(!04%2ç 3UMMARY1UERIES #(!04%2ç 3UBQUERIESAND1UERY %XPRESSIONS
This page intentionally left blank
#(!04%2
31,ç"ASICS
4
HISCHAPTERBEGINSADETAILEDDESCRIPTIONOFTHEFEATURESOF31,)TDESCRIBESTHE BASICSTRUCTUREOFA31,STATEMENTANDTHEBASICELEMENTSOFTHELANGUAGE SUCHAS KEYWORDS DATATYPES ANDEXPRESSIONS(OW31,HANDLESMISSINGDATATHROUGH .5,,VALUESISALSODESCRIBED!LTHOUGHTHESEAREBASICFEATURESOF31, THEYHAVESOME SUBTLEDIFFERENCESINTHEWAYTHEYAREIMPLEMENTEDBYVARIOUSPOPULAR31,PRODUCTS AND INMANYCASES THE31,PRODUCTSPROVIDESIGNIFICANTEXTENSIONSTOTHECAPABILITIESSPECIFIED INTHE!.3))3/31,STANDARD4HESEDIFFERENCESANDEXTENSIONSAREALSODESCRIBEDIN THISCHAPTER
3TATEMENTS 4HEMAINBODYOF31,CONSISTSOFABOUTSTATEMENTS4HEMOSTIMPORTANTANDFREQUENTLY USEDSTATEMENTSARESUMMARIZEDIN4ABLE .OTETHATNOTALL31,IMPLEMENTATIONS SUPPORTALLTHESESTATEMENTS %ACHSTATEMENTREQUESTSASPECIFICACTIONFROMTHE$"-3 SUCHASCREATINGANEWTABLE RETRIEVINGDATA ORINSERTINGNEWDATAINTOTHEDATABASE!LL 31,STATEMENTSHAVETHESAMEBASICFORM ILLUSTRATEDIN&IGURE %VERY31,STATEMENTBEGINSWITHAVERB AKEYWORDTHATDESCRIBESWHATTHESTATEMENT DOES#2%!4% ).3%24 $%,%4% AND#/--)4ARETYPICALVERBS4HESTATEMENTCONTINUES WITHONEORMORECLAUSES!CLAUSEMAYSPECIFYTHEDATATOBEACTEDONBYTHESTATEMENTOR PROVIDEMOREDETAILABOUTWHATTHESTATEMENTISSUPPOSEDTODO%VERYCLAUSEALSOBEGINS WITHAKEYWORD SUCHAS7(%2% &2/- ).4/ AND(!6).'3OMECLAUSESAREOPTIONAL OTHERSAREREQUIRED4HESPECIFICSTRUCTUREANDCONTENTVARYFROMONECLAUSETOANOTHER -ANYCLAUSESCONTAINTABLEORCOLUMNNAMESSOMEMAYCONTAINADDITIONALKEYWORDS CONSTANTS OREXPRESSIONS 4HE!.3))3/31,STANDARDSPECIFIESASETOFRESERVEDKEYWORDSANDNONRESERVED KEYWORDSTHATAREUSEDWITHIN31,STATEMENTS!CCORDINGTOTHESTANDARD RESERVED KEYWORDSCANNOTBEUSEDASTHEEXACTNAMEOFDATABASEOBJECTS SUCHASTABLES COLUMNS ANDUSERS-ANY31,IMPLEMENTATIONSRELAXTHISRESTRICTION BUTITSGENERALLYAGOODIDEA
ç
0ARTç))ç
2ETRIEVINGç$ATA
-Ì>ÌiiÌ
iÃVÀ«Ì
$ATAä-ANIPULATION - /
,iÌÀiÛiÃÊ`>Ì>ÊvÀÊÌ
iÊ`>Ì>L>Ãi
- ,/
``ÃÊiÜÊÀÜÃÊvÊ`>Ì>ÊÌÊÌ
iÊ`>Ì>L>Ãi
1* /
`viÃÊiÝÃÌ}Ê`>Ì>L>ÃiÊ`>Ì>
,
`Ì>ÞÊÃiÀÌÃÉÕ«`>ÌiÃÉ`iiÌiÃÊiÜÊ>`ÊiÝÃÌ}ÊÀÜÃ
/
,iÛiÃÊÀÜÃÊvÊ`>Ì>ÊvÀÊÌ
iÊ`>Ì>L>Ãi
$ATAä$EFINITION
, / Ê/
``ÃÊ>ÊiÜÊÌ>LiÊÌÊÌ
iÊ`>Ì>L>Ãi
,"*Ê/
,iÛiÃÊ>ÊÌ>LiÊvÀÊÌ
iÊ`>Ì>L>Ãi
/ ,Ê/
>}iÃÊÌ
iÊÃÌÀÕVÌÕÀiÊvÊ>ÊiÝÃÌ}ÊÌ>Li
, / Ê6 7
``ÃÊ>ÊiÜÊÛiÜÊÌÊÌ
iÊ`>Ì>L>Ãi
,"*Ê6 7
,iÛiÃÊ>ÊÛiÜÊvÀÊÌ
iÊ`>Ì>L>Ãi
, / Ê 8
Õ`ÃÊ>Ê`iÝÊvÀÊ>ÊVÕ
,"*Ê 8
,iÛiÃÊÌ
iÊ`iÝÊvÀÊ>ÊVÕ
, / Ê-
``ÃÊ>ÊiÜÊÃV
i>ÊÌÊÌ
iÊ`>Ì>L>Ãi
,"*Ê-
,iÛiÃÊ>ÊÃV
i>ÊvÀÊÌ
iÊ`>Ì>L>Ãi
, / Ê "
``ÃÊ>ÊiÜÊ`>Ì>ÊÛ>ÕiÊ`>
/ ,Ê "
>}iÃÊ>Ê`>Ê`ivÌ
,"*Ê "
,iÛiÃÊ>Ê`>ÊvÀÊÌ
iÊ`>Ì>L>Ãi
!CCESSä#ONTROL , /
À>ÌÃÊÕÃiÀÊ>VViÃÃÊ«ÀÛi}iÃ
, 6"
,iÛiÃÊÕÃiÀÊ>VViÃÃÊ«ÀÛi}iÃ
, / Ê,"
``ÃÊ>ÊiÜÊÀiÊÌÊÌ
iÊ`>Ì>L>Ãi
, /Ê,"
À>ÌÃÊÀiÊVÌ>}ÊÕÃiÀÊ>VViÃÃÊ«ÀÛi}iÃ
,"*Ê,"
,iÛiÃÊ>ÊÀiÊvÀÊÌ
iÊ`>Ì>L>Ãi
4RANSACTIONä#ONTROL
"/
`ÃÊÌ
iÊVÕÀÀiÌÊÌÀ>Ã>VÌ
,"
LÀÌÃÊÌ
iÊVÕÀÀiÌÊÌÀ>Ã>VÌ
- /Ê/, - /"
iviÃÊ`>Ì>Ê>VViÃÃÊV
>À>VÌiÀÃÌVÃÊvÊÌ
iÊVÕÀÀiÌÊÌÀ>Ã>VÌ
-/,/Ê/, - /"
Ý«VÌÞÊÃÌ>ÀÌÃÊ>ÊiÜÊÌÀ>Ã>VÌ
-6 *" /
ÃÌ>LÃ
iÃÊ>ÊÀiVÛiÀÞÊ«ÌÊvÀÊ>ÊÌÀ>Ã>VÌ
/ Êx£Ê >ÀÊ-+Ê-Ì>ÌiiÌÃ
#HAPTERçç
-Ì>ÌiiÌ
31,ç"ASICSç
iÃVÀ«Ì
0ROGRAMMATICä31, iviÃÊ>ÊVÕÀÃÀÊvÀÊ>ʵÕiÀÞ
8*
iÃVÀLiÃÊÌ
iÊ`>Ì>Ê>VViÃÃÊ«>ÊvÀÊ>ʵÕiÀÞ
"*
"«iÃÊ>ÊVÕÀÃÀÊÌÊÀiÌÀiÛiʵÕiÀÞÊÀiÃÕÌÃ
/
,iÌÀiÛiÃÊ>ÊÀÜÊvʵÕiÀÞÊÀiÃÕÌÃ
"-
ÃiÃÊ>ÊVÕÀÃÀ
*, *,
*Ài«>ÀiÃÊ>Ê-+ÊÃÌ>ÌiiÌÊvÀÊ`Þ>VÊiÝiVÕÌ
8 1/
ÝiVÕÌiÃÊ>Ê-+ÊÃÌ>ÌiiÌÊ`Þ>V>Þ
- ,
iÃVÀLiÃÊ>Ê«Ài«>Ài`ʵÕiÀÞ
/ Êx£Ê >ÀÊ-+Ê-Ì>ÌiiÌÃÊCONTINUED
TOAVOIDTHEKEYWORDSWHENYOUNAMEYOURTABLESANDCOLUMNS4ABLE LISTSTHERESERVED KEYWORDSINCLUDEDINTHE!.3))3/31,STANDARD )TSALSOBESTTOAVOIDTHEUSEOFNONRESERVEDKEYWORDSINNAMINGDATABASEOBJECTS BECAUSETHEYARECANDIDATESFORRESERVEDKEYWORDSINFUTUREREVISIONSOFTHESTANDARD4HE NONRESERVEDKEYWORDSINTHE31,STANDARDARELISTEDIN4ABLE 4HROUGHOUTTHISBOOK THEACCEPTABLEFORMSOFA31,STATEMENTAREILLUSTRATEDBYASYNTAX DIAGRAM SUCHASTHEONESHOWNIN&IGURE !VALID31,STATEMENTORCLAUSEISCONSTRUCTED BYhFOLLOWINGTHELINEvTHROUGHTHESYNTAXDIAGRAMTOTHEDOTTHATMARKSTHEENDOFTHE DIAGRAM+EYWORDSINTHESYNTAXDIAGRAMANDINTHEEXAMPLESSUCHAS$%,%4%AND&2/- IN&IGURE AREALWAYSSHOWNIN500%2#!3% BUTALMOSTALL31,IMPLEMENTATIONSACCEPT BOTHUPPERCASEANDLOWERCASEKEYWORDS ANDITSOFTENMORECONVENIENTTOACTUALLYTYPE THEMINLOWERCASE
1, Êx£Ê /
iÊÃÌÀÕVÌÕÀiÊvÊ>Ê-+ÊÃÌ>ÌiiÌ
0!24ç))
,
ç
0ARTç))ç
2ETRIEVINGç$ATA
-
" /
/ ,
9
,
,,9
-
- -/6
-9 /,
/
/"
1/",Ì>ÊV
>À>VÌiÀÊÃÌÀ}Ã 6>À>Lii}Ì
Ê>Ì>ÊV
>À>VÌiÀÊÃÌÀ}Ã >À}iÊÛ>À>Lii}Ì
Ê>Ì>ÊV
>À>VÌiÀÊ ÃÌÀ}Ã
/LEN®
Ýi`i}Ì
ÊLÌÊÃÌÀ}Ã
/Ê6,9 LEN®
6>À>Lii}Ì
ÊLÌÊÃÌÀ}Ã
/ ,
/
- /
->ÊÌi}iÀÃ
1 , PRECISION]ÊSCALE® PRECISION]ÊSCALE®
Ìi}iÀÃ iV>ÊÕLiÀÃ
iV>ÊÕLiÀÃ
"/PRECISION®
>Ì}Ê«ÌÊÕLiÀÃ
,
Ü«ÀiVÃÊv>Ì}Ê«ÌÊÕLiÀÃ
"1 Ê*, -"
}
«ÀiVÃÊv>Ì}Ê«ÌÊÕLiÀÃ
/
>i`>ÀÊ`>ÌiÃ
/ PRECISION®
VÊÌiÃ
/ Ê7/Ê/ ÊÌiÃÊ>`ÊÌiÃÊÜÌ
ÊÌiÊâiÃ
/ ,6
/iÊÌiÀÛ>Ã
8TYPEäMODIFIERÊQSECONDARYä TYPEäMODIFIERR®
>À>VÌiÀÊ`>Ì>ÊvÀ>ÌÌi`Ê>ÃÊ ÝÌiÃLiÊ >ÀÕ«Ê>}Õ>}iÊ8®
/ Êx{Ê -É-"Ê-+Ê >Ì>Ê/Þ«iÃ
#HAPTERçç
31,ç"ASICSç
$ATETIMEDATAPROVIDESANEXCELLENTEXAMPLEOFTHISPHENOMENONANDTHEDATATYPE VARIATIONSITCREATES$"OFFEREDEARLYDATETIMESUPPORT WITHTHREEDIFFERENTDATETIME DATATYPES s $!4%
3TORESADATELIKE*UNE
s 4)-%
3TORESATIMEOFDAYLIKE0-
s 4)-%34!-0 !SPECIFICINSTANTINHISTORY WITHAPRECISIONDOWNTOTHENANOSECOND
3%,%#4.!-% ()2%?$!4% &2/-3!,%32%03 7(%2%()2%?$!4%gg$!93
31,3ERVERWASINTRODUCEDWITHASINGLEDATETIMEDATATYPE CALLED$!4%4)-% WHICH CLOSELYRESEMBLESTHE$"4)-%34!-0DATATYPE)F()2%?$!4%CONTAINED$!4%4)-%DATA 31,3ERVERCOULDACCEPTTHISVERSIONOFTHEQUERYWITHOUTTHEDATEARITHMETIC 3%,%#4.!-% ()2%?$!4% &2/-3!,%32%03 7(%2%()2%?$!4%gg
3INCENOSPECIFICTIMEON*UNE ISSPECIFIEDINTHEQUERY 31,3ERVERDEFAULTSTO MIDNIGHTONTHATDATE4HE31,3ERVERQUERYTHUSREALLYMEANS 3%,%#4.!-% ()2%?$!4% &2/-3!,%32%03 7(%2%()2%?$!4%g!-g
31,3ERVERALSOSUPPORTSDATEARITHMETICTHROUGHASETOFBUILT INFUNCTIONS4HUS THE $" STYLEQUERYCANALSOBESPECIFIEDINTHISWAY 3%,%#4.!-% ()2%?$!4% &2/-3!,%32%03 7(%2%()2%?$!4%$!4%!$$$!9 gg
WHICHISCONSIDERABLYDIFFERENTFROMTHE$"SYNTAX /RACLEHASLONGSUPPORTEDDATETIMEDATAWITHASINGLEDATATYPECALLED$!4%.OTE HOWEVER THAT/RACLEADDEDSUPPORTFORTHE31,3TANDARD$!4%4)-%AND4)-%34!-0 DATATYPESSTARTINGWITH/RACLEI ,IKE31,3ERVERS$!4%4)-%TYPE AN/RACLE$!4%IS IN FACT ATIMESTAMP!LSOASWITH31,3ERVER THETIMEPARTOFAN/RACLE$!4%VALUEDEFAULTSTO MIDNIGHTIFNOTIMEISEXPLICITLYSPECIFIED4HEDEFAULT/RACLEDATEFORMATISDIFFERENTFROM THE$"AND31,3ERVERFORMATS SOTHE/RACLEVERSIONOFTHEQUERYBECOMES 3%,%#4.!-% ()2%?$!4% &2/-3!,%32%03 7(%2%()2%?$!4%g *5. g
0!24ç))
3PECIFICDATESANDTIMESCANBESPECIFIEDASSTRINGCONSTANTS ANDDATEARITHMETICIS SUPPORTED(EREISANEXAMPLEOFAVALIDQUERYUSING$"DATES ASSUMINGTHATTHE()2%? $!4%COLUMNCONTAINS$!4%DATA
ç
0ARTç))ç
2ETRIEVINGç$ATA
/RACLEALSOSUPPORTSLIMITEDDATEARITHMETIC SOTHE$" STYLEQUERYCANALSOBE SPECIFIED BUTWITHOUTTHE$!93KEYWORD 3%,%#4.!-% ()2%?$!4% &2/-3!,%32%03 7(%2%()2%?$!4%g -!9 g
.OTE HOWEVER THATTHISSTATEMENTREQUIRESTHE$"-3TOIMPLICITLYCONVERTTHESTRINGTO ANAPPROPRIATEDATEDATATYPEBEFOREADDINGTOIT ANDTHATNOTALL31,IMPLEMENTATIONS SUPPORTSUCHCONVERSION/RACLE FOREXAMPLE WILLREPORTANERRORUNLESSAFUNCTIONSUCHAS 4/?$!4%OR#!34CONVERTSTHECHARACTERSTRINGTOAN/RACLE$!4%OR$!4%4)-%TYPE BEFOREATTEMPTINGDATEARITHMETIC &ORTUNATELY WITHTHEADVENTOFTHEYEARCONVERSION MOST$"-3VENDORSADDED UNIVERSALSUPPORTFORDATESIN31,STATEMENTSWITHFOUR DIGITYEARSINASTANDARD9999 -- $$FORMAT WHICHWEUSEFORMOSTOFTHEEXAMPLESINTHISBOOK)N/RACLESCASE THE DEFAULTFORMATISSTILLASSHOWNINTHEPRECEDINGEXAMPLES BUTITCANBECHANGEDATEITHER THEDATABASEORUSERSESSIONWITHASIMPLECOMMAND)FYOUAREUSING/RACLEANDYOUTRY ANYOFTHEEXAMPLESINTHISBOOK SIMPLYENTERTHISCOMMANDTOCHANGEYOURDEFAULTDATE FORMAT !,4%23%33)/.3%4.,3?$!4%?&/2-!4g9999 -- $$g
#AREMUSTBETAKENWHENFORMINGQUERIESTHATSEARCHFOREXACTDATEMATCHESUSINGTHE EQUAL OPERATOR ANDTHEDATESHAVETIMECOMPONENTSSTOREDINTHEM#ONSIDERTHE FOLLOWINGEXAMPLE 3%,%#4.!-% ()2%?$!4% &2/-3!,%32%03 7(%2%()2%?$!4%gg
)FASALESPERSONSHIREDATEWERESTOREDINTHEDATABASEASNOONON*UNE THE SALESPERSONWOULDNOTBEINCLUDEDINTHEQUERYRESULTSFROM/RACLEOR31,3ERVERDATABASES 4HE$"-3WOULDASSUMEATIMEOFMIDNIGHTFORTHESTRINGSUPPLIEDWITHTHE31,STATEMENT ANDSINCEMIDNIGHTISNOTEQUALTONOON THEROWWOULDNOTBESELECTED/NTHEOTHERHAND FORA$"DATABASE WHERETHETIMEISNOTSTOREDWITHA$!4%DATATYPE THEROWWOULD APPEARINTHEQUERYRESULTS &INALLY STARTINGWITH31, THE!.3))3/STANDARDADDEDSUPPORTFORDATETIMEDATA WITHASETOFDATATYPESBASEDON BUTNOTIDENTICALTO THE$"TYPES)NADDITIONTOTHE$!4% 4)-% AND4)-%34!-0DATATYPES THESTANDARDSPECIFIESAN).4%26!,DATATYPE WHICHCAN BEUSEDTOSTOREATIMEINTERVALFOREXAMPLE ATIMESPANMEASUREDINDAYS ORADURATION MEASUREDINHOURS MINUTES ANDSECONDS 4HESTANDARDALSOPROVIDESAVERYELABORATEAND COMPLEXMETHODFORDEALINGWITHDATETIMEARITHMETIC SPECIFYINGTHEPRECISIONOFINTERVALS ADJUSTINGFORTIMEZONEDIFFERENCES ANDSOON-OST31,IMPLEMENTATIONSNOWHAVESUPPORT FORTHESESTANDARDTYPES/NENOTABLEEXCEPTION HOWEVER ISTHAT31,3ERVERHASLONGUSED THE4)-%34!-0DATATYPEFORANENTIRELYDIFFERENTPURPOSE SOSUPPORTINGTHE!.3))3/ SPECIFICATIONFORITPRESENTSAVERYREALCHALLENGE !STHESEEXAMPLESILLUSTRATE THESUBTLEDIFFERENCESINDATATYPESAMONGVARIOUS31, PRODUCTSLEADTOSOMESIGNIFICANTDIFFERENCESIN31,STATEMENTSYNTAX
#HAPTERçç
31,ç"ASICSç
4HEYCANEVENCAUSETHESAME31,QUERYTOPRODUCESLIGHTLYDIFFERENTRESULTSON DIFFERENTDATABASEMANAGEMENTSYSTEMS4HEWIDELYPRAISEDPORTABILITYOF31,ISTHUSTRUE BUTONLYATAGENERALLEVEL!NAPPLICATIONCANBEMOVEDFROMONE31,DATABASETOANOTHER ANDITCANBEHIGHLYPORTABLEIFITUSESONLYTHEMOSTMAINSTREAM BASIC31,CAPABILITIES (OWEVER THESUBTLEVARIATIONSIN31,IMPLEMENTATIONSMEANTHATDATATYPESAND31, STATEMENTSMUSTALMOSTALWAYSBEADJUSTEDSOMEWHATIFTHEYARETOBEMOVEDACROSS$"-3 BRANDS4HEMORECOMPLEXTHEAPPLICATION THEMORELIKELYITISTOBECOMEDEPENDENTON $"-3 SPECIFICFEATURESANDNUANCES ANDTHELESSPORTABLEITWILLBECOME
)NSOME31,STATEMENTS ANUMERIC CHARACTER ORDATEDATAVALUEMUSTBEEXPRESSEDINTEXT FORM&OREXAMPLE INTHIS).3%24STATEMENTWHICHADDSASALESPERSONTOTHEDATABASE ).3%24).4/3!,%32%03%-0,?.5- .!-% 15/4! ()2%?$!4% 3!,%3 6!,5%3 g$ENNIS)RVINGg g g
THEVALUEFOREACHCOLUMNINTHENEWLYINSERTEDROWISSPECIFIEDINTHE6!,5%3CLAUSE #ONSTANTDATAVALUESAREALSOUSEDINEXPRESSIONS SUCHASINTHIS3%,%#4STATEMENT 3%,%#4#)49 &2/-/&&)#%3 7(%2%4!2'%4 3!,%3
4HE!.3))3/31,STANDARDSPECIFIESTHEFORMATOFNUMERICANDSTRINGCONSTANTS OR LITERALS WHICHREPRESENTSPECIFICDATAVALUES4HESECONVENTIONSAREFOLLOWEDBYMOST31, IMPLEMENTATIONS
.UMERICõ#ONSTANTS )NTEGERANDDECIMALCONSTANTSALSOCALLEDEXACTNUMERICLITERALS AREWRITTENASORDINARY DECIMALNUMBERSIN31,STATEMENTS WITHANOPTIONALLEADINGPLUSORMINUSSIGN
9OUMUSTNOTPUTACOMMABETWEENTHEDIGITSOFANUMERICCONSTANT ANDNOTALL31, DIALECTSALLOWTHELEADINGPLUSSIGN SOITSBESTTOAVOIDIT&ORMONEYDATA MOST31, IMPLEMENTATIONSSIMPLYUSEINTEGERORDECIMALCONSTANTS ALTHOUGHSOMEALLOWTHECONSTANT TOBESPECIFIEDWITHACURRENCYSYMBOL
&LOATINGPOINTCONSTANTSALSOCALLEDAPPROXIMATENUMERICLITERALS ARESPECIFIEDUSINGTHE %NOTATIONCOMMONLYFOUNDINPROGRAMMINGLANGUAGESSUCHAS#AND&/242!.(EREARE SOMEVALID31,FLOATINGPOINTCONSTANTS % %% %
4HE%ISREADhTIMESTENTOTHEPOWEROF vSOTHEFIRSTCONSTANTBECOMEShTIMESTENTO THETHIRDPOWER vOR
0!24ç))
#ONSTANTS
ç
0ARTç))ç
2ETRIEVINGç$ATA
3TRINGõ#ONSTANTS 4HE!.3))3/STANDARDSPECIFIESTHAT31,CONSTANTSFORCHARACTERDATABEENCLOSEDINSINGLE QUOTESgg ASINTHESEEXAMPLES g*ONES *OHN*gg.EW9ORKgg7ESTERNg
)FASINGLEQUOTEISTOBEINCLUDEDINTHECONSTANTTEXT ITISWRITTENWITHINTHECONSTANTAS TWOCONSECUTIVESINGLE QUOTECHARACTERS4HUS THISCONSTANTVALUE g)CANggTg
BECOMESTHESEVEN CHARACTERSTRING)CANgT 3OME31,IMPLEMENTATIONS SUCHAS31,3ERVER ACCEPTSTRINGCONSTANTSENCLOSEDIN DOUBLEQUOTES *ONES *OHN*.EW9ORK7ESTERN
5NFORTUNATELY THEDOUBLEQUOTESCANPOSEPORTABILITYPROBLEMSWITHOTHER31, PRODUCTS4HE31,STANDARDPROVIDESTHEADDITIONALCAPABILITYTOSPECIFYSTRINGCONSTANTS FROMASPECIFICNATIONALCHARACTERSETFOREXAMPLE &RENCHOR'ERMAN ORFROMAUSER DEFINEDCHARACTERSET4HEUSER DEFINEDCHARACTERSETCAPABILITIESHAVETYPICALLYNOTBEEN IMPLEMENTEDINMAINSTREAM31,PRODUCTS
$ATEõANDõ4IMEõ#ONSTANTS )N31,PRODUCTSTHATSUPPORTDATETIMEDATA CONSTANTVALUESFORDATES TIMES ANDTIME INTERVALSARESPECIFIEDASSTRINGCONSTANTS4HEFORMATOFTHESECONSTANTSVARIESFROMONE $"-3TOTHENEXT%VENMOREVARIATIONISINTRODUCEDBYTHEDIFFERENCESINTHEWAYDATES ANDTIMESAREWRITTENINDIFFERENTCOUNTRIES )"-S$"SUPPORTSSEVERALDIFFERENTINTERNATIONALFORMATSFORDATE TIME AND TIMESTAMPCONSTANTS ASSHOWNIN4ABLE 4HECHOICEOFFORMATISMADEWHENTHE$"-3 ISINSTALLED$"ALSOSUPPORTSDURATIONSSPECIFIEDASSPECIALCONSTANTS ASINTHISEXAMPLE ()2%?$!4%$!93
.OTETHATADURATIONCANTBESTOREDINTHEDATABASE HOWEVER BECAUSE$"DOESNTHAVE ANEXPLICIT$52!4)/.DATATYPE 31,3ERVERALSOSUPPORTSDATETIMEDATAANDACCEPTSAVARIETYOFDIFFERENTFORMATSFOR DATEANDTIMECONSTANTS4HE$"-3AUTOMATICALLYACCEPTSALLOFTHEALTERNATEFORMATS ANDYOU CANINTERMIXTHEMIFYOULIKE(EREARESOMEEXAMPLESOFLEGAL31,3ERVERDATECONSTANTS -ARCH -AR -!2
À>ÌÊ >i
>ÌiÊÀ>Ì
>ÌiÊ Ý>«i
/iÊÀ>Ì
/iÊ Ý>«i
iÀV>
É``ÉÞÞÞÞ
xÉ£ÉÓään
\Ê>É«
Ó\£nÊ*
ÕÀ«i>
``°°ÞÞÞÞ
£°x°Óään
°°ÃÃ
£{°£n°än
>«>iÃi
ÞÞÞÞ``
Óäänx£
\\ÃÃ
£{\£n\än
-"
ÞÞÞÞ``
Óäänx£
°°ÃÃ
£{°£n°än
/ ÊxxÊ ÓÊ-+Ê >ÌiÊ>`Ê/iÊÀ>ÌÃ
#HAPTERçç
31,ç"ASICSç
ANDHEREARESOMELEGALTIMECONSTANTS 0-PM0-
/RACLEDATESANDTIMESAREALSOWRITTENASSTRINGCONSTANTS USINGTHISFORMAT -!2
9OUCANALSOUSE/RACLESBUILT IN4/?$!4% FUNCTIONTOCONVERTDATECONSTANTSWRITTEN INOTHERFORMATS ASINTHISEXAMPLE
4HE31,STANDARDSPECIFIESAFORMATFORDATEANDTIMECONSTANTS BASEDONTHE)3/ FORMATIN4ABLE EXCEPTTHATTIMECONSTANTSAREWRITTENWITHCOLONSINSTEADOFPERIODS SEPARATINGTHEHOURS MINUTES ANDSECONDS4HE31,3TANDARD4)-%34!-0TYPE NOT SHOWNINTHETABLE HASAFORMATOFYYYY MM DD HHMMSSNNNNNNFOREXAMPLEh vREPRESENTSATROUGHLYPM
3YMBOLICõ#ONSTANTS )NADDITIONTOUSER SUPPLIEDCONSTANTS THE31,INCLUDESSPECIALSYMBOLICCONSTANTSTHAT RETURNDATAVALUESMAINTAINEDBYTHE$"-3ITSELF&OREXAMPLE INSOME$"-3BRANDS THE SYMBOLICCONSTANT#522%.4?$!4%YIELDSTHEVALUEOFTHECURRENTDATEANDCANBEUSEDIN QUERIESSUCHASTHEFOLLOWING WHICHLISTSTHESALESPEOPLEWHOSEHIREDATEISSTILLINTHEFUTURE 3%,%#4.!-% ()2%?$!4% &2/-3!,%32%03 7(%2%()2%?$!4%#522%.4?$!4%
4HE31,STANDARDSPECIFIEDONLYASINGLESYMBOLICCONSTANTTHE53%2CONSTANT DESCRIBEDIN#HAPTER BUTMOST31,PRODUCTSPROVIDEMANYMORE'ENERALLY ASYMBOLIC CONSTANTCANAPPEARINA31,STATEMENTANYWHERETHATANORDINARYCONSTANTOFTHESAME DATATYPECOULDAPPEAR4HE31,STANDARDADOPTEDTHEMOSTUSEFULSYMBOLICCONSTANTS FROMCURRENT31,IMPLEMENTATIONSANDPROVIDESFOR#522%.4?$!4% #522%.4?4)-% AND#522%.4?4)-%34!-0NOTETHEUNDERSCORES ASWELLAS53%2 3%33)/.?53%2 AND 3934%-?53%2 3OME31,PRODUCTS INCLUDING31,3ERVER PROVIDEACCESSTOSYSTEMVALUESTHROUGHBUILT IN FUNCTIONSRATHERTHANSYMBOLICCONSTANTS4HE31,3ERVERVERSIONOFTHEPRECEDINGQUERYIS 3%,%#4.!-% ()2%?$!4% &2/-3!,%32%03 7(%2%()2%?$!4%'%4$!4%
"UILT INFUNCTIONSAREDESCRIBEDLATERINTHISCHAPTER INTHESECTIONh"UILT )N&UNCTIONSv
0!24ç))
3%,%#4.!-% !'% &2/-3!,%32%03 7(%2%()2%?$!4%4/?$!4%g*5.g g-/.$$9999g
ç
0ARTç))ç
2ETRIEVINGç$ATA
%XPRESSIONS %XPRESSIONSAREUSEDINTHE31,TOCALCULATEVALUESTHATARERETRIEVEDFROMADATABASEANDTO CALCULATEVALUESUSEDINSEARCHINGTHEDATABASE&OREXAMPLE THISQUERYCALCULATESTHESALES OFEACHOFFICEASAPERCENTAGEOFITSTARGET 3%,%#4#)49 4!2'%4 3!,%3 3!,%34!2'%4 &2/-/&&)#%3
ANDTHISQUERYLISTSTHEOFFICESWHOSESALESAREMORETHAN OVERTARGET 3%,%#4#)49 &2/-/&&)#%3 7(%2%3!,%34!2'%4
4HE!.3))3/31,STANDARDSPECIFIESFOURARITHMETICOPERATIONSTHATCANBEUSEDIN EXPRESSIONSADDITION89 SUBTRACTION8n9 MULTIPLICATION8 9 ANDDIVISION89 0ARENTHESESCANALSOBEUSEDTOFORMMORECOMPLICATEDEXPRESSIONS LIKETHISONE 3!,%3 4!2'%4
3TRICTLYSPEAKING THEPARENTHESESARENOTREQUIREDINTHISQUERYBECAUSETHE!.3))3/ STANDARDSPECIFIESTHATMULTIPLICATIONANDDIVISIONHAVEAHIGHERPRECEDENCETHANADDITION ANDSUBTRACTION(OWEVER YOUSHOULDALWAYSUSEPARENTHESESTOMAKEYOUREXPRESSIONS UNAMBIGUOUS BECAUSEDIFFERENT31,DIALECTSMAYUSEDIFFERENTRULES4HEPARENTHESESALSO INCREASETHEREADABILITYOFTHESTATEMENTANDMAKEPROGRAMMATIC31,STATEMENTSEASIERTO MAINTAIN 4HE!.3))3/31,STANDARDALSOSPECIFIESAUTOMATICDATATYPECONVERSIONFROMINTEGERS TODECIMALNUMBERS ANDFROMDECIMALNUMBERSTOFLOATINGPOINTNUMBERS ASREQUIRED9OU CANTHUSMIXTHESEDATATYPESINANUMERICEXPRESSION-ANY31,IMPLEMENTATIONSSUPPORT OTHEROPERATORSANDALLOWOPERATIONSONCHARACTERANDDATEDATA4HE31,STANDARDSPECIFIES ASTRINGCONCATENATIONOPERATOR WRITTENASTWOCONSECUTIVEVERTICALBARCHARACTERS\\ WHICHISSUPPORTEDBYMOSTIMPLEMENTATIONS!NOTABLEEXCEPTIONIS31,3ERVER WHICH USESTHEPLUSSIGN INSTEAD )FTWOCOLUMNSNAMED&)234?.!-%AND,!34?.!-% CONTAINTHEVALUESh*IMvANDh*ACKSONv THENTHIS$"EXPRESSION g-R-RSg\\&)234?.!-%\\gg\\,!34?.!-%
PRODUCESTHESTRINGh-R-RS*IM*ACKSONv!SALREADYMENTIONED $"ANDMANYOTHER IMPLEMENTATIONSALSOSUPPORTADDITIONANDSUBTRACTIONOF$!4% 4)-% AND4)-%34!-0 DATA FOROCCASIONSWHENTHOSEOPERATIONSMAKESENSE4HISCAPABILITYHASBEENINCLUDED INTHE31,STANDARD
"UILT )Nõ&UNCTIONS !NUMBEROFUSEFULBUILT INFUNCTIONSARESPECIFIEDIN31,STANDARD ANDMOST31, IMPLEMENTATIONSADDMANYMORE4HESEFACILITIESOFTENPROVIDEDATATYPECONVERSIONFACILITIES &OREXAMPLE $"SBUILT IN-/.4( AND9%!2 FUNCTIONSTAKEA$!4%OR4)-%34!-0 VALUEASTHEIRINPUTANDRETURNANINTEGERTHATISTHEMONTHORYEARPORTIONOFTHEVALUE 4HISQUERYLISTSTHENAMEANDMONTHOFHIREFOREACHSALESPERSONINTHESAMPLEDATABASE 3%,%#4.!-% -/.4(()2%?$!4% &2/-3!,%32%03
#HAPTERçç
31,ç"ASICSç
ANDTHISONELISTSALLSALESPEOPLEHIREDIN 3%,%#4.!-% -/.4(()2%?$!4% &2/-3!,%32%03 7(%2%9%!2()2%?$!4%
"UILT INFUNCTIONSAREALSOOFTENUSEDFORDATAREFORMATTING/RACLESBUILT IN4/?#(!2 FUNCTION FOREXAMPLE TAKESA$!4%DATATYPEANDAFORMATSPECIFICATIONASITSARGUMENTS ANDRETURNSASTRINGCONTAININGAFORMATTEDCHARACTERSTRINGVERSIONOFTHEDATE4HISSAME FUNCTIONISALSOCAPABLEOFCONVERTINGNUMERICVALUESTOFORMATTEDCHARACTERSTRINGS )NTHE RESULTSPRODUCEDBYTHISQUERY
THEHIREDATESWILLALLHAVETHEFORMATh7EDNESDAY*UNE vBECAUSEOFTHEBUILT INFUNCTION )NGENERAL ABUILT INFUNCTIONCANBESPECIFIEDINA31,EXPRESSIONANYWHERETHATA CONSTANTOFTHESAMEDATATYPECANBESPECIFIED4HEBUILT INFUNCTIONSSUPPORTEDBYPOPULAR 31,DIALECTSARETOONUMEROUSTOLISTHERE4HE)"-$"31,DIALECTSINCLUDEABOUTTWO DOZENBUILT INFUNCTIONS /RACLESUPPORTSADIFFERENTSETOFABOUTTWODOZENBUILT INFUNCTIONS AND31,3ERVERHASSEVERALDOZEN4HE31,STANDARDINCORPORATEDTHEMOSTUSEFULBUILT IN FUNCTIONSFROMTHESEIMPLEMENTATIONS INMANYCASESWITHSLIGHTLYDIFFERENTSYNTAX4HESE FUNCTIONSARESUMMARIZEDIN4ABLE ÕVÌ
,iÌÕÀÃ
/Ú /ÊSTRING®
/
iÊÕLiÀÊvÊLÌÃÊÊ>ÊLÌÊÃÌÀ}
-/ÊVALUEÊ-ÊDATA?TYPE®
/
iÊÛ>Õi]ÊVÛiÀÌi`ÊÌÊÌ
iÊëiVvi`Ê`>Ì>ÊÌÞ«iÊi°}°]Ê>Ê`>ÌiÊVÛiÀÌi`ÊÌÊ>Ê V
>À>VÌiÀÊÃÌÀ}®
,Ú /ÊSTRING®
/
iÊi}Ì
ÊvÊ>ÊV
>À>VÌiÀÊÃÌÀ}
" 6 ,/ÊSTRINGÊ1- ÊCONV®
ÊÃÌÀ}ÊVÛiÀÌi`Ê>ÃÊëiVvi`ÊLÞÊ>Ê>i`ÊVÛiÀÃÊvÕVÌ
1,, /Ú /
/
iÊVÕÀÀiÌÊ`>Ìi
1,, /Ú/ ÊPRECISION®
/
iÊVÕÀÀiÌÊÌi]ÊÜÌ
ÊÌ
iÊëiVvi`ÊPRECISION
1,, /Ú/ -/*ÊPRECISION®
/
iÊVÕÀÀiÌÊ`>ÌiÊ>`ÊÌi]ÊÜÌ
ÊÌ
iÊëiVvi`ÊPRECISION
8/, /ÊPARTÊ,"ÊSOURCE®
/
iÊëiVvi`Ê«>ÀÌÊ 9]Ê"1,]ÊiÌV°®ÊvÀÊ>Ê / / ÊÛ>Õi
"7 ,ÊSTRING®
ÊÃÌÀ}ÊVÛiÀÌi`ÊÌÊ>ÊÜiÀV>ÃiÊiÌÌiÀÃ
" / /Ú /ÊSTRING®
/
iÊÕLiÀÊvÊnLÌÊLÞÌiÃÊÊ>ÊV
>À>VÌiÀÊÃÌÀ}
*"-/" ÊTARGETÊ ÊSOURCE®
/
iÊ«ÃÌÊÜ
iÀiÊÌ
iÊTARGETÊÃÌÀ}Ê>««i>ÀÃÊÜÌ
ÊÌ
iÊSOURCEÊÃÌÀ}
-1 -/, ÊSOURCEÊ,"ÊNÊ",ÊLEN®
Ê«ÀÌÊvÊÌ
iÊSOURCEÊÃÌÀ}]ÊLi}}Ê>ÌÊÌ
iÊNÌ
ÊV
>À>VÌiÀ]ÊvÀÊ>Êi}Ì
Ê vÊLEN
/, -/ ÊSTRINGÊ1- ÊTRANS®
ÊÃÌÀ}ÊÌÀ>Ã>Ìi`Ê>ÃÊëiVvi`ÊLÞÊ>Ê>i`ÊÌÀ>Ã>ÌÊvÕVÌ
/,Ê "/ÊCHARÊ,"ÊSTRING®
ÊÃÌÀ}ÊÜÌ
ÊLÌ
Êi>`}Ê>`ÊÌÀ>}ÊVVÕÀÀiViÃÊvÊCHARÊÌÀi`Êvv
/,Ê ÊCHARÊ,"ÊSTRING®
ÊÃÌÀ}ÊÜÌ
Ê>ÞÊi>`}ÊVVÕÀÀiViÃÊvÊCHARÊÌÀi`Êvv
/,Ê/, ÊCHARÊ,"ÊSTRING®
ÊÃÌÀ}ÊÜÌ
Ê>ÞÊÌÀ>}ÊVVÕÀÀiViÃÊvÊCHARÊÌÀi`Êvv
1** ,ÊSTRING®
ÊÃÌÀ}ÊVÛiÀÌi`ÊÌÊ>ÊÕ««iÀV>ÃiÊiÌÌiÀÃ
/ ÊxÈÊ -+Ê-Ì>`>À`Ê ÕÌÊÕVÌÃ
0!24ç))
3%,%#4.!-% 4/?#(!2()2%?$!4% g$!9-/.4($$ 9999g &2/-3!,%32%03
ç
0ARTç))ç
2ETRIEVINGç$ATA
-ISSINGõ$ATAõ.5,,õ6ALUES "ECAUSEADATABASEISUSUALLYAMODELOFAREAL WORLDSITUATION CERTAINPIECESOFDATAARE INEVITABLYMISSING UNKNOWN ORDONTAPPLY)NTHESAMPLEDATABASE FOREXAMPLE THE 15/4!COLUMNINTHE3!,%32%03TABLECONTAINSTHESALESGOALFOREACHSALESPERSON (OWEVER THENEWESTSALESPERSONHASNOTYETBEENASSIGNEDAQUOTATHISDATAISMISSINGFOR THATROWOFTHETABLE9OUMIGHTBETEMPTEDTOPUTAZEROINTHECOLUMNFORTHISSALESPERSON BUTTHATWOULDNOTBEANACCURATEREFLECTIONOFTHESITUATION4HESALESPERSONDOESNOTHAVE AZEROQUOTATHEQUOTAISJUSThNOTYETKNOWNv 3IMILARLY THE-!.!'%2COLUMNINTHE3!,%32%03TABLECONTAINSTHEEMPLOYEENUMBER OFEACHSALESPERSONSMANAGER"UT3AM#LARK THEVICEPRESIDENTOFSALES HASNOMANAGERIN THESALESORGANIZATION4HISCOLUMNDOESNOTAPPLYTO3AM!GAIN YOUMIGHTTHINKABOUT ENTERINGAZERO ORAINTHECOLUMN BUTNEITHEROFTHESEVALUESWOULDREALLYBETHE EMPLOYEENUMBEROF3AMSBOSS.ODATAVALUEISAPPLICABLETOTHISROW 31,SUPPORTSMISSING UNKNOWN ORINAPPLICABLEDATAEXPLICITLY THROUGHTHECONCEPTOF ANULLVALUE!NULLVALUEISANINDICATORTHATTELLS31,ANDTHEUSER THATTHEDATAISMISSING ORNOTAPPLICABLE!SACONVENIENCE AMISSINGPIECEOFDATAISOFTENSAIDTOHAVETHEVALUE .5,,"UTTHE.5,,VALUEISNOTAREALDATAVALUELIKE ORh3AM#LARKv)NSTEAD ITS ASIGNAL ORAREMINDER THATTHEDATAVALUEISMISSINGORUNKNOWN&IGURE SHOWSTHE CONTENTSOFTHE3!,%32%03TABLE.OTETHATTHE15/4!AND2%0?/&&)#%VALUESFOR4OM 3NYDERSROWANDTHE-!.!'%2VALUEFOR3AM#LARKSROWOFTHETABLEALLCONTAIN.5,, VALUES!LSONOTETHAT31,TOOLSDONOTDISPLAYNULLVALUESINQUERYRESULTSINTHESAME WAYWHILEMANYUSETHESTRING.5,,ASSHOWNIN&IGURE OTHERSUSEEMPTYSPACEOR CHARACTERSTRINGS )NMANYSITUATIONS .5,,VALUESREQUIRESPECIALHANDLINGBYTHE$"-3&OREXAMPLE IF THEUSERREQUESTSTHESUMOFTHE15/4!COLUMN HOWSHOULDTHE$"-3HANDLETHEMISSING DATAWHENCOMPUTINGTHESUM4HEANSWERISGIVENBYASETOFSPECIALRULESTHATGOVERN .5,,VALUEHANDLINGINVARIOUS31,STATEMENTSANDCLAUSES"ECAUSEOFTHESERULES SOME LEADINGDATABASEAUTHORITIESFEELSTRONGLYTHAT.5,,VALUESSHOULDNOTBEUSED/THERS INCLUDING4ED#ODD HAVEADVOCATEDTHEUSEOFMULTIPLE.5,,VALUES WITHDISTINCT INDICATORSFORhUNKNOWNvANDhNOTAPPLICABLEvDATA
1, ÊxÎÊ .5,,ÊÛ>ÕiÃÊÊÌ
iÊ- -, *-ÊÌ>Li
#HAPTERçç
31,ç"ASICSç
2EGARDLESSOFTHEACADEMICDEBATES .5,,VALUESAREAWELL ENTRENCHEDPARTOFTHE !.3))3/31,STANDARDANDARESUPPORTEDINVIRTUALLYALLCOMMERCIAL31,PRODUCTS 4HEYALSOPLAYANIMPORTANT PRACTICALROLEINPRODUCTIONOF31,DATABASES4HESPECIAL RULESTHATAPPLYTO.5,,VALUESANDTHECASESWHERE.5,,VALUESAREHANDLED INCONSISTENTLYBYVARIOUS31,PRODUCTS AREPOINTEDOUTTHROUGHOUTTHISBOOK
3UMMARY 4HISCHAPTERDESCRIBEDTHEBASICELEMENTSOF31,4HEBASICSTRUCTUREOF31,CANBE SUMMARIZEDASFOLLOWS
s 31, BASEDDATABASESCANSTOREVARIOUSTYPESOFDATA INCLUDINGTEXT INTEGERS DECIMAL NUMBERS FLOATINGPOINTNUMBERS ANDUSUALLYMANYMOREVENDOR SPECIFICDATATYPES s 31,STATEMENTSCANINCLUDEEXPRESSIONSTHATCOMBINECOLUMNNAMES CONSTANTS AND BUILT INFUNCTIONS USINGARITHMETICANDOTHERVENDOR SPECIFICOPERATORS s 6ARIATIONSINDATATYPES CONSTANTS ANDBUILT INFUNCTIONSMAKEPORTABILITYOF31, STATEMENTSMOREDIFFICULTTHANITMAYSEEMATFIRST s .5,,VALUESPROVIDEASYSTEMATICWAYOFHANDLINGMISSINGORINAPPLICABLEDATAIN THE31,
0!24ç))
s 31,THATISINCOMMONUSEINCLUDESABOUTSTATEMENTS EACHCONSISTINGOFAVERB ANDONEORMORECLAUSES%ACHSTATEMENTPERFORMSASINGLE SPECIFICFUNCTION
This page intentionally left blank
#(!04%2
3IMPLEç1UERIES
)
NMANYWAYS QUERIESARETHEHEARTOF31,4HE3%,%#4STATEMENT WHICHISUSEDTOEXPRESS 31,QUERIES ISTHEMOSTPOWERFULANDCOMPLEXOFTHE31,STATEMENTS$ESPITETHEMANY OPTIONSAFFORDEDBYTHE3%,%#4STATEMENT ITSPOSSIBLETOSTARTSIMPLYANDTHENWORKUPTO MORECOMPLEXQUERIES4HISCHAPTERDISCUSSESTHESIMPLEST31,QUERIESTHOSETHATRETRIEVE DATAFROMINDIVIDUALROWSOFASINGLETABLEINTHEDATABASE)FYOUHAVENOTDONESOALREADY YOU WILLLEARNMOREIFYOUCREATETHESAMPLEDATABASEONYOUROWNSYSTEMANDTRYTHEQUERIESFOR YOURSELFASYOUREAD)NSTRUCTIONSFORTHESAMPLEDATABASEAREIN!PPENDIX!
4HEõ3%,%#4õ3TATEMENT 4HE3%,%#4STATEMENTRETRIEVESDATAFROMADATABASEANDRETURNSITTOYOUINTHEFORMOF QUERYRESULTS!SAREMINDER THEEXACTFORMATOFTHEQUERYRESULTSWILLVARYFROMONE31, PRODUCTTOANOTHER9OUHAVEALREADYSEENMANYEXAMPLESOFTHE3%,%#4STATEMENTINTHE QUICKTOURPRESENTEDIN#HAPTER(EREARESEVERALMORESAMPLEQUERIESTHATRETRIEVE INFORMATIONABOUTSALESOFFICES ,ISTTHESALESOFFICESWITHTHEIRTARGETSANDACTUALSALES 3%,%#4#)49 4!2'%4 3!,%3 &2/-/&&)#%3 #)494!2'%43!,%3
$ENVER .EW9ORK #HICAGO !TLANTA ,OS!NGELES
ç
0ARTç))ç
2ETRIEVINGç$ATA
,ISTTHE%ASTERNREGIONSALESOFFICESWITHTHEIRTARGETSANDSALES 3%,%#4#)49 4!2'%4 3!,%3 &2/-/&&)#%3 7(%2%2%')/.g%ASTERNg #)494!2'%43!,%3
.EW9ORK #HICAGO !TLANTA
,IST%ASTERNREGIONSALESOFFICESWHOSESALESEXCEEDTHEIRTARGETS SORTEDINALPHABETICAL ORDERBYCITY 3%,%#4#)49 4!2'%4 3!,%3 &2/-/&&)#%3 7(%2%2%')/.g%ASTERNg !.$3!,%34!2'%4 /2$%2"9#)49 #)494!2'%43!,%3
!TLANTA .EW9ORK
&ORSIMPLEQUERIES THE%NGLISHLANGUAGEREQUESTANDTHE31,3%,%#4STATEMENTARE VERYSIMILAR7HENTHEREQUESTSBECOMEMORECOMPLEX MOREFEATURESOFTHE3%,%#4 STATEMENTMUSTBEUSEDTOSPECIFYTHEQUERYPRECISELY &IGURE SHOWSTHEFULLFORMOFTHE3%,%#4STATEMENT WHICHCONSISTSOFSIXCLAUSES 4HE3%,%#4AND&2/-CLAUSESOFTHESTATEMENTAREREQUIRED4HEREMAININGFOURCLAUSESARE OPTIONAL9OUINCLUDETHEMINA3%,%#4STATEMENTONLYWHENYOUWANTTOUSETHEFUNCTIONS THEYPROVIDE4HEFOLLOWINGLISTSUMMARIZESTHEFUNCTIONOFEACHCLAUSE s 4HE3%,%#4CLAUSELISTSTHEDATAITEMSTOBERETRIEVEDBYTHE3%,%#4STATEMENT4HE ITEMSMAYBECOLUMNSFROMTHEDATABASE ORCOLUMNSTOBECALCULATEDBY31,ASIT PERFORMSTHEQUERY4HE3%,%#4CLAUSEISDESCRIBEDINTHENEXTSECTION s 4HE&2/-CLAUSELISTSTHETABLESANDVIEWSTHATCONTAINTHEDATATOBERETRIEVEDBY THEQUERY6IEWSAREDISCUSSEDINDETAILIN#HAPTER 1UERIESTHATDRAWTHEIRDATA FROMASINGLETABLEAREDESCRIBEDINTHISCHAPTER-ORECOMPLEXQUERIESTHATCOMBINE DATAFROMTWOORMORETABLESAREDISCUSSEDIN#HAPTER s 4HE7(%2%CLAUSETELLS31,TOINCLUDEONLYCERTAINROWSOFDATAINTHEQUERYRESULTS !SEARCHCONDITIONISUSEDTOSPECIFYTHEDESIREDROWS4HEBASICUSESOFTHE7(%2% CLAUSEAREDESCRIBEDINTHEh2OW3ELECTION7(%2%#LAUSE vSECTIONLATERINTHIS CHAPTER4HOSETHATINVOLVESUBQUERIESAREDISCUSSEDIN#HAPTER s 4HE'2/50"9CLAUSESPECIFIESASUMMARYQUERY)NSTEADOFPRODUCINGONEROWOF QUERYRESULTSFOREACHROWOFDATAINTHEDATABASE ASUMMARYQUERYGROUPS TOGETHERSIMILARROWSANDTHENPRODUCESONESUMMARYROWOFQUERYRESULTSFOREACH GROUP3UMMARYQUERIESAREDESCRIBEDIN#HAPTER
#HAPTERçç
3IMPLEç1UERIESç
1, ÊÈ£Ê Ê 3%,%#4ÊÃÌ>ÌiiÌÊ ÃÞÌ>ÝÊ`>}À>
0!24ç))
s 4HE(!6).'CLAUSETELLS31,TOINCLUDEONLYCERTAINGROUPSPRODUCEDBYTHE'2/50 "9CLAUSEINTHEQUERYRESULTS,IKETHE7(%2%CLAUSE ITUSESASEARCHCONDITIONTO SPECIFYTHEDESIREDGROUPS4HE(!6).'CLAUSEISDESCRIBEDIN#HAPTER s 4HE/2$%2"9CLAUSESORTSTHEQUERYRESULTSBASEDONTHEDATAINONEORMORECOLUMNS )FITISOMITTED THEQUERYRESULTSARENOTSORTED4HE/2$%2"9CLAUSEISDESCRIBEDINTHE h3ORTING1UERY2ESULTS/2$%2"9#LAUSE vSECTIONLATERINTHISCHAPTER
4HEõ3%,%#4õ#LAUSE 4HE3%,%#4CLAUSETHATBEGINSEACH3%,%#4STATEMENTSPECIFIESTHEDATAITEMSTOBE RETRIEVEDBYTHEQUERY4HEITEMSAREUSUALLYSPECIFIEDBYASELECTLIST ALISTOFSELECTITEMS SEPARATEDBYCOMMAS%ACHSELECTITEMINTHELISTGENERATESASINGLECOLUMNOFQUERYRESULTS INLEFT TO RIGHTORDER!SELECTITEMCANBEONEOFTHEFOLLOWING s !COLUMNNAME IDENTIFYINGACOLUMNFROMTHETABLES NAMEDINTHE&2/-CLAUSE7HEN ACOLUMNNAMEAPPEARSASASELECTITEM 31,SIMPLYTAKESTHEVALUEOFTHATCOLUMNFROM EACHROWOFTHEDATABASETABLEANDPLACESITINTHECORRESPONDINGROWOFQUERYRESULTS s !CONSTANT SPECIFYINGTHATTHESAMECONSTANTVALUEISTOAPPEARINEVERYROWOFTHE QUERYRESULTS s !31,EXPRESSION INDICATINGTHAT31,MUSTCALCULATETHEVALUETOBEPLACEDINTOTHE QUERYRESULTS ASSPECIFIEDBYTHEEXPRESSION %ACHTYPEOFSELECTITEMISDESCRIBEDLATERINTHISCHAPTER
ç
0ARTç))ç
2ETRIEVINGç$ATA
4HEõ&2/-õ#LAUSE 4HE&2/-CLAUSECONSISTSOFTHEKEYWORD&2/- FOLLOWEDBYALISTOFTABLESPECIFICATIONS SEPARATEDBYCOMMAS%ACHTABLESPECIFICATIONIDENTIFIESATABLEORVIEWCONTAININGDATATOBE RETRIEVEDBYTHEQUERY4HESETABLESARECALLEDTHESOURCETABLESOFTHEQUERYANDOFTHE3%,%#4 STATEMENT BECAUSETHEYARETHESOURCEOFALLOFTHEDATAINTHEQUERYRESULTS!LLOFTHEQUERIES INTHISCHAPTERHAVEASINGLESOURCETABLE ANDEVERY&2/-CLAUSECONTAINSASINGLETABLENAME
1UERYõ2ESULTS 4HERESULTOFA31,QUERYISALWAYSATABLEOFDATA JUSTLIKETHETABLESINTHEDATABASE)FYOU TYPEA3%,%#4STATEMENTUSINGINTERACTIVE31, THE$"-3DISPLAYSTHEQUERYRESULTS WHICHSOMEVENDORSCALLARESULTSET INTABULARFORMONYOURCOMPUTERSCREEN)FA COMPUTERPROGRAMSENDSAQUERYTOTHE$"-3USINGPROGRAMMATIC31, THETABLEOFQUERY RESULTSISRETURNEDTOTHEPROGRAMFORPROCESSING)NEITHERCASE THEQUERYRESULTSALWAYS HAVETHESAMETABULAR ROWCOLUMNFORMATASTHEACTUALTABLESINTHEDATABASE ASSHOWNIN &IGURE 5SUALLYTHEQUERYRESULTSWILLBEATABLEWITHSEVERALCOLUMNSANDSEVERALROWS &OREXAMPLE THEFOLLOWINGQUERYPRODUCESATABLEOFTHREECOLUMNSBECAUSEITASKSFOR THREEITEMSOFDATA ANDTENROWSBECAUSETHEREARETENSALESPEOPLE ,ISTTHENAMES OFFICES ANDHIREDATESOFALLSALESPEOPLE 3%,%#4.!-% 2%0?/&&)#% ()2%?$!4% &2/-3!,%32%03 .!-%2%0?/&&)#%()2%?$!4%
"ILL!DAMS -ARY*ONES 3UE3MITH 3AM#LARK "OB3MITH $AN2OBERTS 4OM3NYDER.5,, ,ARRY&ITCH 0AUL#RUZ .ANCY!NGELLI
)NCONTRAST THEFOLLOWINGQUERYPRODUCESASINGLEROWBECAUSEONLYONESALESPERSONHAS THEREQUESTEDEMPLOYEENUMBER%VENTHOUGHTHISSINGLEROWOFQUERYRESULTSLOOKSLESS hTABULARvTHANTHEMULTIROWRESULTS 31,STILLCONSIDERSITTOBEATABLEOFTHREECOLUMNSAND ONEROW 7HATARETHENAME QUOTA ANDSALESOFEMPLOYEENUMBER 3%,%#4.!-% 15/4! 3!,%3 &2/-3!,%32%03 7(%2%%-0,?.5- .!-%15/4!3!,%3
.ANCY!NGELLI
#HAPTERçç
3IMPLEç1UERIESç
0!24ç))
1, ÊÈÓÊ /
iÊÌ>LÕ>ÀÊÃÌÀÕVÌÕÀiÊvÊ-+ʵÕiÀÞÊÀiÃÕÌÃ
)NSOMECASESTHEQUERYRESULTSCANBEASINGLEVALUE ASINTHEFOLLOWINGEXAMPLE 7HATARETHEAVERAGESALESOFOURSALESPEOPLE 3%,%#4!6'3!,%3 &2/-3!,%32%03 !6'3!,%3
4HESEQUERYRESULTSARESTILLATABLE ALTHOUGHITSAVERYSMALLONECONSISTINGOFONECOLUMN ANDONEROW &INALLY ITSPOSSIBLEFORAQUERYTOPRODUCEZEROROWSOFQUERYRESULTS ASINTHISEXAMPLE ,ISTTHENAMEANDHIREDATEOFANYONEWITHSALESOVER 3%,%#4.!-% ()2%?$!4% &2/-3!,%32%03 7(%2%3!,%3 .!-%()2%?$!4%
%VENINTHISSITUATION THEQUERYRESULTSARESTILLATABLE4HISONEISANEMPTYTABLEWITH TWOCOLUMNSANDZEROROWS .OTETHAT31,SSUPPORTFORMISSINGDATAEXTENDSTOQUERYRESULTSASWELL)FADATAITEM INTHEDATABASEHASA.5,,VALUE THE.5,,VALUEAPPEARSINTHEQUERYRESULTSWHENTHE
ç
0ARTç))ç
2ETRIEVINGç$ATA
DATAITEMISRETRIEVED&OREXAMPLE THE3!,%32%03TABLECONTAINS.5,,VALUESINITS15/4! AND-!.!'%2COLUMNS4HENEXTQUERYRETURNSTHESE.5,,VALUESINTHESECONDANDTHIRD COLUMNSOFQUERYRESULTS.OTETHATNOTALL31,PRODUCTSDISPLAY.5,,VALUESINTHESAME WAY/RACLEAND$" FOREXAMPLE DISPLAYNOTHINGWHENA.5,,VALUEISENCOUNTERED ,ISTTHESALESPEOPLE THEIRQUOTAS ANDTHEIRMANAGERS 3%,%#4.!-% 15/4! -!.!'%2 &2/-3!,%32%03 .!-%15/4!-!.!'%2
"ILL!DAMS -ARY*ONES 3UE3MITH 3AM#LARK .5,, "OB3MITH $AN2OBERTS 4OM3NYDER.5,, ,ARRY&ITCH 0AUL#RUZ .ANCY!NGELLI
4HEFACTTHATA31,QUERYALWAYSPRODUCESATABLEOFDATAISVERYIMPORTANT)TMEANS THATTHEQUERYRESULTSCANBESTOREDBACKINTOTHEDATABASEASATABLE)TMEANSTHATTHE RESULTSOFTWOSIMILARQUERIESCANBECOMBINEDTOFORMALARGERTABLEOFQUERYRESULTS &INALLY ITMEANSTHATTHEQUERYRESULTSCANTHEMSELVESBETHETARGETOFFURTHERQUERIES! RELATIONALDATABASESTABULARSTRUCTURETHUSHASAVERYSYNERGISTICRELATIONSHIPWITHTHE RELATIONALQUERYFACILITIESOF31,4ABLESCANBEQUERIED ANDQUERIESPRODUCETABLES
3IMPLEõ1UERIES 4HESIMPLEST31,QUERIESREQUESTCOLUMNSOFDATAFROMASINGLETABLEINTHEDATABASE&OR EXAMPLE THISQUERYREQUESTSTHREECOLUMNSFROMTHE/&&)#%3TABLE ,ISTTHELOCATION REGION ANDSALESOFEACHSALESOFFICE 3%,%#4#)49 2%')/. 3!,%3 &2/-/&&)#%3 #)492%')/.3!,%3
$ENVER7ESTERN .EW9ORK%ASTERN #HICAGO%ASTERN !TLANTA%ASTERN ,OS!NGELES7ESTERN
4HE3%,%#4STATEMENTFORSIMPLEQUERIESLIKETHISONEINCLUDESONLYTHETWOREQUIRED CLAUSES4HE3%,%#4CLAUSENAMESTHEREQUESTEDCOLUMNSTHE&2/-CLAUSENAMESTHETABLE ORVIEWTHATCONTAINSTHEM
#HAPTERçç
3IMPLEç1UERIESç
#ONCEPTUALLY 31,PROCESSESTHEQUERYBYGOINGTHROUGHTHETABLENAMEDINTHE&2/- CLAUSE ONEROWATATIME&OREACHROW 31,TAKESTHEVALUESOFTHECOLUMNSREQUESTEDIN THESELECTLISTANDPRODUCESASINGLEROWOFQUERYRESULTS4HEQUERYRESULTSTHUSCONTAINONE ROWOFDATAFOREACHROWINTHETABLE
#ALCULATEDõ#OLUMNS
,ISTTHECITY REGION ANDAMOUNTOVERUNDERTARGETFOREACHOFFICE 3%,%#4#)49 2%')/. 3!,%3 4!2'%4 &2/-/&&)#%3 #)492%')/.3!,%3 4!2'%4
$ENVER7ESTERN .EW9ORK%ASTERN #HICAGO%ASTERN !TLANTA%ASTERN ,OS!NGELES7ESTERN
4OPROCESSTHEQUERY 31,GOESTHROUGHTHEOFFICES GENERATINGONEROWOFQUERYRESULTS FOREACHROWOFTHE/&&)#%3TABLE ASSHOWNIN&IGURE 4HEFIRSTTWOCOLUMNSOFQUERY RESULTSCOMEDIRECTLYFROMTHE/&&)#%3TABLE4HETHIRDCOLUMNOFQUERYRESULTSIS CALCULATED ROWBYROW USINGTHEDATAVALUESFROMTHECURRENTROWOFTHE/&&)#%3TABLE (EREAREOTHEREXAMPLESOFQUERIESTHATUSECALCULATEDCOLUMNS 3HOWTHEVALUEOFTHEINVENTORYFOREACHPRODUCT/NLYTHEFIRSTROWSINTHERESULTSETARESHOWN 3%,%#4-&2?)$ 02/$5#4?)$ $%3#2)04)/. 149?/.?(!.$ 02)#% &2/-02/$5#43 -&2?)$02/$5#4?)$$%3#2)04)/.149?/.?(!.$ 02)#%
2%)!#2ATCHET,INK !#)97IDGET2EMOVER 13!8+2EDUCER ")#0LATE )--# LB"RACE !#)3IZE7IDGET !#)3IZE7IDGET ")#(ANDLE
0!24ç))
)NADDITIONTOCOLUMNSWHOSEVALUESCOMEDIRECTLYFROMTHEDATABASE A31,QUERYCAN INCLUDECALCULATEDCOLUMNSWHOSEVALUESARECALCULATEDFROMTHESTOREDDATAVALUES4O REQUESTACALCULATEDCOLUMN YOUSPECIFYA31,EXPRESSIONINTHESELECTLIST!SDISCUSSEDIN #HAPTER 31,EXPRESSIONSCANINVOLVEADDITION SUBTRACTION MULTIPLICATION ANDDIVISION 9OUCANALSOUSEPARENTHESESTOBUILDMORECOMPLEXEXPRESSIONS/FCOURSETHECOLUMNS REFERENCEDINANARITHMETICEXPRESSIONMUSTHAVEANUMERICTYPE)FYOUTRYTOADD SUBTRACT MULTIPLY ORDIVIDECOLUMNSCONTAININGTEXTDATA 31,WILLREPORTANERROR 4HISQUERYSHOWSASIMPLECALCULATEDCOLUMN
ç
0ARTç))ç
2ETRIEVINGç$ATA
1, ÊÈÎÊ +ÕiÀÞÊ«ÀViÃÃ}ÊÜÌ
Ê>ÊV>VÕ>Ìi`ÊVÕ
3HOWMETHERESULTIF)RAISEDEACHSALESPERSONSQUOTABYPERCENTOFTHEIRYEAR TO DATESALES 3%,%#4.!-% 15/4! 15/4! 3!,%3 &2/-3!,%32%03 .!-%15/4!15/4! 3!,%3
"ILL!DAMS -ARY*ONES 3UE3MITH 3AM#LARK "OB3MITH $AN2OBERTS 4OM3NYDER.5,,.5,, ,ARRY&ITCH 0AUL#RUZ .ANCY!NGELLI
!SMENTIONEDIN#HAPTER MANY31,PRODUCTSPROVIDEADDITIONALARITHMETIC OPERATIONS CHARACTERSTRINGOPERATIONS ANDBUILT INFUNCTIONSTHATCANBEUSEDIN31, EXPRESSIONS4HESECANAPPEARINSELECTLISTEXPRESSIONS ASINTHENEXT$"EXAMPLE WHICH EXTRACTSTHEMONTHANDYEARFROMADATE ,ISTTHENAME MONTH ANDYEAROFHIREFOREACHSALESPERSON&OR/RACLEDATABASES THE4/?#(!2 FUNCTIONMUSTBEUSEDINSTEADOFTHE-/.4(AND9%!2FUNCTIONS 3%,%#4.!-% -/.4(()2%?$!4% 9%!2()2%?$!4% &2/-3!,%32%03
#HAPTERçç
3IMPLEç1UERIESç
31,CONSTANTSCANALSOBEUSEDBYTHEMSELVESASITEMSINASELECTLIST4HISCANBEUSEFUL FORPRODUCINGQUERYRESULTSTHATAREEASIERTOREADANDINTERPRET ASINTHENEXTEXAMPLE ,ISTTHESALESFOREACHCITY
4HEQUERYRESULTSAPPEARTOCONSISTOFASEPARATEhSENTENCEvFOREACHOFFICE BUTTHEYRE REALLYATABLEOFTHREECOLUMNS4HEFIRSTANDTHIRDCOLUMNSCONTAINVALUESFROMTHE /&&)#%3TABLE4HESECONDCOLUMNALWAYSCONTAINSTHESAME CHARACTERTEXTSTRING
3ELECTINGõ!LLõ#OLUMNSõ3%,%#4õ 3OMETIMESITSCONVENIENTTODISPLAYTHECONTENTSOFALLTHECOLUMNSOFATABLE4HISCANBE PARTICULARLYUSEFULWHENYOUFIRSTENCOUNTERANEWDATABASEANDWANTTOGETAQUICK UNDERSTANDINGOFITSSTRUCTUREANDTHEDATAITCONTAINS!SACONVENIENCE 31,LETSYOUUSE ANASTERISK INPLACEOFTHESELECTLISTASANABBREVIATIONFORhALLCOLUMNSv 3HOWMEALLTHEDATAINTHE/&&)#%3TABLE 3%,%#4 &2/-/&&)#%3 /&&)#%#)492%')/.-'24!2'%43!,%3
$ENVER7ESTERN .EW9ORK%ASTERN #HICAGO%ASTERN !TLANTA%ASTERN ,OS!NGELES7ESTERN
4HEQUERYRESULTSCONTAINALLSIXCOLUMNSOFTHE/&&)#%3TABLE INTHESAMELEFT TO RIGHT ORDERASINTHETABLEITSELF 4HEALL COLUMNSSELECTIONISMOSTAPPROPRIATEWHENYOUAREUSINGINTERACTIVE31, CASUALLY)TSHOULDBEAVOIDEDINPROGRAMMATIC31, BECAUSECHANGESINTHEDATABASE STRUCTURECANCAUSEAPROGRAMTOFAIL&OREXAMPLE SUPPOSETHE/&&)#%3TABLEWAS DROPPEDFROMTHEDATABASEANDTHENRE CREATEDWITHITSCOLUMNSREARRANGEDANDANEW SEVENTHCOLUMNADDED31,AUTOMATICALLYTAKESCAREOFTHEDATABASE RELATEDDETAILSOFSUCH CHANGES BUTITCANNOTMODIFYYOURAPPLICATIONPROGRAMFORYOU)FYOURPROGRAMEXPECTSA 3%,%#4 &2/-/&&)#%3QUERYTORETURNSIXCOLUMNSOFQUERYRESULTSWITHCERTAINDATA TYPES ITWILLALMOSTCERTAINLYSTOPWORKINGWHENTHECOLUMNSAREREARRANGEDANDANEW ONEISADDED
0!24ç))
3%,%#4#)49 gHASSALESOFg 3!,%3 &2/-/&&)#%3 #)49(!33!,%3/&3!,%3
$ENVERHASSALESOF .EW9ORKHASSALESOF #HICAGOHASSALESOF !TLANTAHASSALESOF ,OS!NGELESHASSALESOF
ç
0ARTç))ç
2ETRIEVINGç$ATA
4HESEDIFFICULTIESCANBEAVOIDEDIFYOUWRITETHEPROGRAMTOREQUESTTHECOLUMNS ITNEEDSBYNAME&OREXAMPLE THEFOLLOWINGQUERYPRODUCESTHESAMERESULTSAS 3%,%#4 &2/-/&&)#%3)TISALSOIMMUNETOCHANGESINTHEDATABASESTRUCTURE ASLONG ASTHENAMEDCOLUMNSCONTINUETOEXISTINTHE/&&)#%3TABLE 3%,%#4/&&)#% #)49 2%')/. -'2 4!2'%4 3!,%3 &2/-/&&)#%3
$UPLICATEõ2OWSõ$)34).#4 )FAQUERYINCLUDESTHEPRIMARYKEYOFATABLEINITSSELECTLIST THENEVERYROWOFQUERY RESULTSWILLBEUNIQUEBECAUSETHEPRIMARYKEYHASADIFFERENTVALUEINEACHROW )FTHE PRIMARYKEYISNOTINCLUDEDINTHEQUERYRESULTS DUPLICATEROWSCANOCCUR&OREXAMPLE SUPPOSEYOUMADETHISREQUEST ,ISTTHEEMPLOYEENUMBERSOFALLSALESOFFICEMANAGERS 3%,%#4-'2 &2/-/&&)#%3 -'2
4HEQUERYRESULTSHAVEFIVEROWSONEFOREACHOFFICE BUTTWOOFTHEMAREEXACT DUPLICATESOFONEANOTHER7HY"ECAUSE,ARRY&ITCHMANAGESBOTHTHE,OS!NGELESAND $ENVEROFFICES ANDHISEMPLOYEENUMBER APPEARSINBOTHROWSOFTHE/&&)#%3TABLE 4HESEQUERYRESULTSAREPROBABLYNOTEXACTLYWHATYOUHADINMIND)FTHEREAREFOUR DIFFERENTMANAGERS YOUMIGHTHAVEEXPECTEDONLYFOUREMPLOYEENUMBERSINTHEQUERY RESULTS 9OUCANELIMINATEDUPLICATEROWSOFQUERYRESULTSBYINSERTINGTHEKEYWORD$)34).#4 INTHE3%,%#4STATEMENTJUSTBEFORETHESELECTLIST(EREISAVERSIONOFTHEPREVIOUSQUERY THATPRODUCESTHERESULTSYOUWANT ,ISTTHEEMPLOYEENUMBERSOFALLSALESOFFICEMANAGERS 3%,%#4$)34).#4-'2 &2/-/&&)#%3 -'2
#ONCEPTUALLY 31,CARRIESOUTTHISQUERYBYFIRSTGENERATINGAFULLSETOFQUERYRESULTS FIVEROWS ANDTHENELIMINATINGROWSTHATAREEXACTDUPLICATESOFONEANOTHERTOFORMTHE
#HAPTERçç
3IMPLEç1UERIESç
FINALQUERYRESULTS4HE$)34).#4KEYWORDCANBESPECIFIEDREGARDLESSOFTHECONTENTSOF THE3%,%#4LISTWITHCERTAINRESTRICTIONSFORSUMMARYQUERIES ASDESCRIBEDIN#HAPTER "EAWARETHATTHE31,ENGINEMAYHAVETOAPPLYASORTTOIDENTIFYTHEDUPLICATEROWSAND THATSORTSOFLARGENUMBERSOFROWSCANCAUSEPERFORMANCEPROBLEMS )FTHE$)34).#4KEYWORDISOMITTED 31,DOESNOTELIMINATEDUPLICATEROWS9OUCAN ALSOSPECIFYTHEKEYWORD!,,TOEXPLICITLYINDICATETHATDUPLICATEROWSARETOBERETAINED BUTITISUNNECESSARYSINCETHISISTHEDEFAULTBEHAVIOR
2OWõ3ELECTIONõ7(%2%õ#LAUSE
3HOWMETHEOFFICESWHERESALESEXCEEDTARGET 3%,%#4#)49 3!,%3 4!2'%4 &2/-/&&)#%3 7(%2%3!,%34!2'%4 #)493!,%34!2'%4
.EW9ORK !TLANTA ,OS!NGELES
3HOWMETHENAME SALES ANDQUOTAOFEMPLOYEENUMBER 3%,%#4.!-% 3!,%3 15/4! &2/-3!,%32%03 7(%2%%-0,?.5- .!-%3!,%315/4!
"ILL!DAMS
3HOWMETHEEMPLOYEESMANAGEDBY"OB3MITHEMPLOYEE 3%,%#4.!-% 3!,%3 &2/-3!,%32%03 7(%2%-!.!'%2 .!-%3!,%3
"ILL!DAMS $AN2OBERTS 0AUL#RUZ
4HE7(%2%CLAUSECONSISTSOFTHEKEYWORD7(%2%FOLLOWEDBYASEARCHCONDITIONTHAT SPECIFIESTHEROWSTOBERETRIEVED)NTHEPREVIOUSQUERY FOREXAMPLE THESEARCHCONDITIONIS -!.!'%2&IGURE SHOWSHOWTHE7(%2%CLAUSEWORKS#ONCEPTUALLY 31,GOES
0!24ç))
31,QUERIESTHATRETRIEVEALLROWSOFATABLEAREUSEFULFORDATABASEBROWSINGANDREPORTS BUTFORLITTLEELSE5SUALLYYOULLWANTTOSELECTONLYSOMEOFTHEROWSINATABLEANDINCLUDE ONLYTHESEROWSINTHEQUERYRESULTS4HE7(%2%CLAUSEISUSEDTOSPECIFYTHEROWSYOUWANT TORETRIEVE(EREARESOMEEXAMPLESOFSIMPLEQUERIESTHATUSETHE7(%2%CLAUSE
ç
0ARTç))ç
2ETRIEVINGç$ATA
1, ÊÈ{Ê ,ÜÊÃiiVÌÊÜÌ
ÊÌ
iÊ7(%2%ÊV>ÕÃi
THROUGHEACHROWOFTHE3!,%32%03TABLE ONEBYONE ANDAPPLIESTHESEARCHCONDITIONTO THEROW7HENACOLUMNNAMEAPPEARSINTHESEARCHCONDITIONSUCHASTHE-!.!'%2 COLUMNINTHISEXAMPLE 31,USESTHEVALUEOFTHECOLUMNINTHECURRENTROW&OREACHROW THESEARCHCONDITIONCANPRODUCEONEOFTHREERESULTS s )FTHESEARCHCONDITIONIS425% THEROWISINCLUDEDINTHEQUERYRESULTS&OREXAMPLE THEROWFOR"ILL!DAMSHASTHECORRECT-!.!'%2VALUEANDISINCLUDED s )FTHESEARCHCONDITIONIS&!,3% THEROWISEXCLUDEDFROMTHEQUERYRESULTS&OR EXAMPLE THEROWFOR3UE3MITHHASTHEWRONG-!.!'%2VALUEANDISEXCLUDED s )FTHESEARCHCONDITIONHASA.5,,UNKNOWN VALUE THEROWISEXCLUDEDFROMTHE QUERYRESULTS&OREXAMPLE THEROWFOR3AM#LARKHASA.5,,VALUEFORTHE -!.!'%2COLUMNANDISEXCLUDED &IGURE SHOWSANOTHERWAYTOTHINKABOUTTHEROLEOFTHESEARCHCONDITIONINTHE 7(%2%CLAUSE"ASICALLY THESEARCHCONDITIONACTSASAFILTERFORROWSOFTHETABLE2OWSTHAT SATISFYTHESEARCHCONDITIONPASSTHROUGHTHEFILTERANDBECOMEPARTOFTHEQUERYRESULTS 2OWSTHATDONOTSATISFYTHESEARCHCONDITIONARETRAPPEDBYTHEFILTERANDEXCLUDEDFROM THEQUERYRESULTS
1, ÊÈxÊ /
iÊ7(%2%ÊV>ÕÃiÊ>ÃÊ>ÊwÌiÀ
#HAPTERçç
3IMPLEç1UERIESç
3EARCHõ#ONDITIONS 31,OFFERSARICHSETOFSEARCHCONDITIONSTHATALLOWSYOUTOSPECIFYMANYDIFFERENTKINDSOF QUERIESEFFICIENTLYANDNATURALLY&IVEBASICSEARCHCONDITIONSCALLEDPREDICATESINTHE!.3) )3/STANDARD ARESUMMARIZEDHEREANDAREDESCRIBEDINTHESECTIONSTHATFOLLOW s #OMPARISONTEST #OMPARESTHEVALUEOFONEEXPRESSIONWITHTHEVALUEOFANOTHER EXPRESSION5SETHISTESTTOSELECTOFFICESINTHE%ASTERNREGION ORSALESPEOPLEWHOSE SALESAREABOVETHEIRQUOTAS
s 3ETMEMBERSHIPTEST #HECKSWHETHERTHEVALUEOFANEXPRESSIONMATCHESONE OFASETOFVALUES5SETHISTESTTOSELECTOFFICESLOCATEDIN.EW9ORK #HICAGO OR ,OS!NGELES s 0ATTERNMATCHINGTEST #HECKSWHETHERTHEVALUEOFACOLUMNCONTAININGSTRING DATAMATCHESASPECIFIEDPATTERN5SETHISTESTTOSELECTCUSTOMERSWHOSENAMES STARTWITHTHELETTER% s .ULLVALUETEST #HECKSWHETHERACOLUMNHASA.5,,UNKNOWN VALUE5SE THISTESTTOFINDTHESALESPEOPLEWHOHAVENOTYETBEENASSIGNEDTOAMANAGER
4HEõ#OMPARISONõ4ESTõ õ õ õ õ õ 4HEMOSTCOMMONSEARCHCONDITIONUSEDINA31,QUERYISACOMPARISONTEST)NA COMPARISONTEST 31,COMPUTESANDCOMPARESTHEVALUESOFTWO31,EXPRESSIONSFOREACH ROWOFDATA4HEEXPRESSIONSCANBEASSIMPLEASACOLUMNNAMEORACONSTANT ORTHEYCAN BEMORECOMPLEXARITHMETICEXPRESSIONS31,OFFERSSIXDIFFERENTWAYSOFCOMPARINGTHE TWOEXPRESSIONS ASSHOWNIN&IGURE
1, ÊÈÈÊ «>ÀÃÊÌiÃÌÊÃÞÌ>ÝÊ`>}À>
0!24ç))
s 2ANGETEST 4ESTSWHETHERTHEVALUEOFANEXPRESSIONFALLSWITHINASPECIFIEDRANGE OFVALUES5SETHISTESTTOFINDSALESPEOPLEWHOSESALESAREBETWEEN AND
ç
0ARTç))ç
2ETRIEVINGç$ATA
3OMEEXAMPLESOFTYPICALCOMPARISONTESTSFOLLOW &INDSALESPEOPLEHIREDBEFORE 3%,%#4.!-% &2/-3!,%32%03 7(%2%()2%?$!4%g g .!-%
3UE3MITH "OB3MITH $AN2OBERTS 0AUL#RUZ
.OTETHAT31,PRODUCTSDONOTHANDLEDATESINTHESAMEWAY BECAUSEVENDORSWERE PRESSEDTOSUPPORTADATEDATATYPEBEFORETHE31,STANDARDWASWRITTEN4HE9999 -- $$ FORMATSHOWNINTHEPRECEDINGEXAMPLEWORKSFORMOST31,PRODUCTS BUTYOUMAYHAVETO CHANGEITFORSOMEPRODUCTS&OREXAMPLE FOR/RACLE YOUEITHERNEEDTOCHANGETHEDATETOTHE DEFAULT/RACLEFORMATg *!. g ORYOUNEEDTOCHANGETHEDEFAULTDATEFORMATFORYOUR SESSIONUSINGTHECOMMAND!,4%23%33)/.3%4.,3?$!4%?&/2-!4g9999 -- $$g ,ISTTHEOFFICESWHOSESALESFALLBELOWPERCENTOFTARGET 3%,%#4#)49 3!,%3 4!2'%4 &2/-/&&)#%3 7(%2%3!,%3 4!2'%4 #)493!,%34!2'%4
$ENVER
,ISTTHEOFFICESNOTMANAGEDBYEMPLOYEENUMBER 3%,%#4#)49 -'2 &2/-/&&)#%3 7(%2%-'2 #)49-'2
.EW9ORK #HICAGO !TLANTA
!SSHOWNIN&IGURE THEINEQUALITYCOMPARISONTESTISWRITTENAS!"ACCORDINGTO THE!.3))3/31,SPECIFICATION3EVERAL31,IMPLEMENTATIONSSUPPORTALTERNATENOTATIONS SUCHAS!"SUPPORTEDBY31,3ERVER $" /RACLE AND-Y31, )NSOMECASES THESE AREALTERNATIVEFORMSINOTHERS THEYARETHEONLYACCEPTABLEFORMOFTHEINEQUALITYTEST
#HAPTERçç
3IMPLEç1UERIESç
7HEN31,COMPARESTHEVALUESOFTHETWOEXPRESSIONSINTHECOMPARISONTEST THREE RESULTSCANOCCUR s )FTHECOMPARISONISTRUE THETESTYIELDSA425%RESULT s )FTHECOMPARISONISFALSE THETESTYIELDSA&!,3%RESULT s )FEITHEROFTHETWOEXPRESSIONSPRODUCESA.5,,IE UNKNOWNORMISSING VALUE THECOMPARISONYIELDSA.5,,RESULT
3INGLE 2OWõ2ETRIEVAL
2ETRIEVETHENAMEANDCREDITLIMITOFCUSTOMERNUMBER 3%,%#4#/-0!.9 #2%$)4?,)-)4 &2/-#534/-%23 7(%2%#534?.5- #/-0!.9#2%$)4?,)-)4
!CE)NTERNATIONAL
4HISTYPEOFQUERYISTHEFOUNDATIONOFFORMS BASEDDATABASERETRIEVALONWEBPAGES 4HEUSERENTERSACUSTOMERNUMBERINTOTHEFORM ANDTHEPROGRAMBEHINDTHEPAGEUSES THENUMBERTOCONSTRUCTANDEXECUTEAQUERY)TTHENDISPLAYSTHERETRIEVEDDATAINTHEFORM .OTETHATTHE31,STATEMENTSFORRETRIEVINGASPECIFICCUSTOMERBYNUMBER ASINTHIS EXAMPLE ANDRETRIEVINGALLCUSTOMERSWITHACERTAINCHARACTERISTICSUCHASTHOSEWITHCREDIT LIMITSOVER BOTHHAVEEXACTLYTHESAMEFORMAT
.5,,õ6ALUEõ#ONSIDERATIONS 4HEBEHAVIOROF.5,,VALUESINCOMPARISONTESTSCANREVEALSOMEhOBVIOUSLYTRUEvNOTIONS ABOUT31,QUERIESTOBE INFACT NOTNECESSARILYTRUE&OREXAMPLE ITWOULDSEEMTHATEVERY ROWOFTHE3!,%32%03TABLEWOULDAPPEARINTHERESULTSOFONEOFTHESETWOQUERIES AND NOTINTHEOTHER ,ISTSALESPEOPLEWHOAREOVERQUOTA 3%,%#4.!-% &2/-3!,%32%03 7(%2%3!,%315/4! .!-%
"ILL!DAMS -ARY*ONES 3UE3MITH 3AM#LARK $AN2OBERTS ,ARRY&ITCH 0AUL#RUZ
0!24ç))
4HEMOSTCOMMONCOMPARISONTESTISONETHATCHECKSWHETHERACOLUMNSVALUEISEQUALTO SOMECONSTANT7HENTHECOLUMNISAPRIMARYKEY THETESTISOLATESASINGLEROWOFTHETABLE PRODUCINGASINGLEROWOFQUERYRESULTS ASINTHISEXAMPLE
ç
0ARTç))ç
2ETRIEVINGç$ATA
,ISTSALESPEOPLEWHOAREUNDERORATQUOTA 3%,%#4.!-% &2/-3!,%32%03 7(%2%3!,%315/4! .!-%
"OB3MITH .ANCY!NGELLI
(OWEVER THEQUERIESPRODUCESEVENANDTWOROWS RESPECTIVELY FORATOTALOFNINEROWS WHILETHEREARETENROWSINTHE3!,%32%03TABLE4OM3NYDERSROWHASA.5,,VALUEINTHE 15/4!COLUMNBECAUSEHEHASNOTYETBEENASSIGNEDAQUOTA4HISROWISNOTLISTEDBYEITHER QUERYIThVANISHESvINTHECOMPARISONTEST,OGICALLY THEDATABASECANNOTDETERMINE WHETHERTHEUNKNOWN3!,%3VALUEISOVER UNDER OREQUALTOTHEKNOWN15/4!VALUE SO THEROWISABSENTFROMBOTHQUERYRESULTS !STHISEXAMPLESHOWS YOUNEEDTOTHINKABOUT.5,,VALUEHANDLINGWHENYOUSPECIFY ASEARCHCONDITION)N31,STHREE VALUEDLOGIC ASEARCHCONDITIONCANYIELDA425% &!,3% OR.5,,RESULT/NLYROWSWHERETHESEARCHCONDITIONYIELDSA425%RESULTAREINCLUDEDIN THEQUERYRESULTS4HEHANDLINGOF.5,,VALUESISDISCUSSEDALITTLELATERINTHISCHAPTER
4HEõ2ANGEõ4ESTõ"%47%%. 31,PROVIDESADIFFERENTFORMOFSEARCHCONDITIONWITHTHERANGETEST"%47%%. SHOWNIN &IGURE 4HERANGETESTCHECKSWHETHERADATAVALUELIESBETWEENTWOSPECIFIEDVALUES)T INVOLVESTHREE31,EXPRESSIONS4HEFIRSTEXPRESSIONDEFINESTHEVALUETOBETESTEDTHE SECONDANDTHIRDEXPRESSIONSDEFINETHELOWANDHIGHENDSOFTHERANGETOBECHECKED4HE DATATYPESOFTHETHREEEXPRESSIONSMUSTBECOMPARABLE 4HISEXAMPLESHOWSATYPICALRANGETEST &INDORDERSPLACEDINTHELASTQUARTEROF 3%,%#4/2$%2?.5- /2$%2?$!4% -&2 02/$5#4 !-/5.4 &2/-/2$%23 7(%2%/2$%2?$!4%"%47%%.g g!.$g g /2$%2?.5-/2$%2?$!4%-&202/$5#4!-/5.4
2%)!, !#) !#) !#) !#): !#) 2%)!' !#)9
4HE"%47%%.TESTINCLUDESTHEENDPOINTSOFTHERANGE SOORDERSPLACEDON/CTOBEROR $ECEMBERAREINCLUDEDINTHEQUERYRESULTS(EREISANOTHEREXAMPLEOFARANGETEST
#HAPTERçç
3IMPLEç1UERIESç
1, ÊÈÇÊ ,>}iÊÌiÃÌÊ"%47%%.®ÊÃÞÌ>ÝÊ`>}À>
&INDTHEORDERSTHATFALLINTOVARIOUSAMOUNTRANGES
4HENEGATEDVERSIONOFTHERANGETEST./4"%47%%. CHECKSFORVALUESTHATFALLOUTSIDE THERANGE ASINTHISEXAMPLE ,ISTSALESPEOPLEWHOSESALESARENOTBETWEENPERCENTANDPERCENTOFQUOTA 3%,%#4.!-% 3!,%3 15/4! &2/-3!,%32%03 7(%2%3!,%3./4"%47%%. 15/4! !.$ 15/4! .!-%3!,%315/4!
-ARY*ONES 3UE3MITH "OB3MITH .ANCY!NGELLI
0!24ç))
3%,%#4/2$%2?.5- !-/5.4 &2/-/2$%23 7(%2%!-/5.4"%47%%.!.$ /2$%2?.5-!-/5.4
3%,%#4/2$%2?.5- !-/5.4 &2/-/2$%23 7(%2%!-/5.4"%47%%.!.$ /2$%2?.5-!-/5.4
3%,%#4/2$%2?.5- !-/5.4 &2/-/2$%23 7(%2%!-/5.4"%47%%.!.$ /2$%2?.5-!-/5.4
ç
0ARTç))ç
2ETRIEVINGç$ATA
4HETESTEXPRESSIONSPECIFIEDINTHE"%47%%.TESTCANBEANYVALID31,EXPRESSION BUT INPRACTICE ITSUSUALLYJUSTACOLUMNNAME ASINTHEPREVIOUSEXAMPLES 4HE!.3))3/STANDARDDEFINESRELATIVELYCOMPLEXRULESFORTHEHANDLINGOF.5,, VALUESINTHE"%47%%.TEST s )FTHETESTEXPRESSIONPRODUCESA.5,,VALUE ORIFBOTHEXPRESSIONSDEFININGTHE RANGEPRODUCE.5,,VALUES THENTHE"%47%%.TESTRETURNSA.5,,RESULT s )FTHEEXPRESSIONDEFININGTHELOWERENDOFTHERANGEPRODUCESA.5,,VALUE THEN THE"%47%%.TESTRETURNS&!,3%IFTHETESTVALUEISGREATERTHANTHEUPPERBOUND AND.5,,OTHERWISE s )FTHEEXPRESSIONDEFININGTHEUPPERENDOFTHERANGEPRODUCESA.5,,VALUE THEN THE"%47%%.TESTRETURNS&!,3%IFTHETESTVALUEISLESSTHANTHELOWERBOUND AND .5,,OTHERWISE "EFORERELYINGONTHISBEHAVIOR ITSAGOODIDEATOEXPERIMENTWITHYOUR$"-3 )TSWORTHNOTINGTHATTHE"%47%%.TESTDOESNTREALLYADDTOTHEEXPRESSIVEPOWEROF 31, BECAUSEITCANBEEXPRESSEDASTWOCOMPARISONTESTS4HERANGETEST !"%47%%."!.$#
ISCOMPLETELYEQUIVALENTTO !" !.$!#
(OWEVER THE"%47%%.TESTISASIMPLERWAYTOEXPRESSASEARCHCONDITIONWHENYOURE THINKINGOFITINTERMSOFARANGEOFVALUES
4HEõ3ETõ-EMBERSHIPõ4ESTõ). !NOTHERCOMMONSEARCHCONDITIONISTHESETMEMBERSHIPTEST). SHOWNIN&IGURE )T TESTSWHETHERADATAVALUEMATCHESONEOFALISTOFTARGETVALUES(EREARESEVERALQUERIES THATUSETHESETMEMBERSHIPTEST ,ISTTHESALESPEOPLEWHOWORKIN.EW9ORK !TLANTA OR$ENVER 3%,%#4.!-% 15/4! 3!,%3 &2/-3!,%32%03 7(%2%2%0?/&&)#%). .!-%15/4!3!,%3
"ILL!DAMS -ARY*ONES 3AM#LARK .ANCY!NGELLI
1, ÊÈnÊ -iÌÊiLiÀÃ
«Ê).®ÊÃÞÌ>ÝÊ`>}À>
#HAPTERçç
3IMPLEç1UERIESç
&INDALLORDERSPLACEDONA&RIDAYIN*ANUARY 3%,%#4/2$%2?.5- /2$%2?$!4% !-/5.4 &2/-/2$%23 7(%2%/2$%2?$!4%).g g g g g g g g /2$%2?.5-/2$%2?$!4%!-/5.4
3%,%#4/2$%2?.5- 2%0 !-/5.4 &2/-/2$%23 7(%2%2%0). /2$%2?.5-2%0!-/5.4
9OUCANCHECKWHETHERTHEDATAVALUEDOESNOTMATCHANYOFTHETARGETVALUESBYUSING THE./4).FORMOFTHESETMEMBERSHIPTEST4HETESTEXPRESSIONINAN).TESTCANBEANY 31,EXPRESSION BUTITSUSUALLYJUSTACOLUMNNAME ASINTHEPRECEDINGEXAMPLES)FTHETEST EXPRESSIONPRODUCESA.5,,VALUE THE).TESTRETURNS.5,,!LLOFTHEITEMSINTHELISTOF TARGETVALUESMUSTHAVETHESAMEDATATYPE ANDTHATTYPEMUSTBECOMPARABLETOTHEDATA TYPEOFTHETESTEXPRESSION ,IKETHE"%47%%.TEST THE).TESTDOESNTADDTOTHEEXPRESSIVEPOWEROF31, BECAUSE THESEARCHCONDITION 8).! " #
ISCOMPLETELYEQUIVALENTTO 8! /28" /28#
(OWEVER THE).TESTOFFERSAMUCHMOREEFFICIENTWAYOFEXPRESSINGTHESEARCHCONDITION ESPECIALLYIFTHESETCONTAINSMORETHANAFEWVALUES4HE!.3))3/31,STANDARDDOESNT SPECIFYAMAXIMUMLIMITTOTHENUMBEROFITEMSTHATCANAPPEARINTHEVALUELIST ANDMOST
0!24ç))
&INDALLORDERSPLACEDWITHFOURSPECIFICSALESPEOPLE
ç
0ARTç))ç
2ETRIEVINGç$ATA
COMMERCIALIMPLEMENTATIONSDONOTSTATEANEXPLICITUPPERLIMITEITHER&ORPORTABILITY REASONS ITSGENERALLYAGOODIDEATOAVOIDLISTSWITHONLYASINGLEITEM SUCHASTHISONE #)49).g.EW9ORKg
ANDREPLACETHEMWITHASIMPLECOMPARISONTEST #)49g.EW9ORKg
4HEõ0ATTERNõ-ATCHINGõ4ESTõ,)+% 9OUCANUSEASIMPLECOMPARISONTESTTORETRIEVEROWSWHERETHECONTENTSOFATEXTCOLUMN MATCHSOMEPARTICULARTEXT&OREXAMPLE THISQUERYRETRIEVESAROWOFTHE#534/-%23TABLE BYNAME 3HOWTHECREDITLIMITFOR3MITHSON#ORP 3%,%#4#/-0!.9 #2%$)4?,)-)4 &2/-#534/-%23 7(%2%#/-0!.9g3MITHSON#ORPg
(OWEVER YOUMIGHTEASILYFORGETWHETHERTHECOMPANYSNAMEWASh3MITH vh3MITHSON v ORh3MITHSONIANv9OUCANUSE31,SPATTERNMATCHINGTESTTORETRIEVETHEDATABASEDONA PARTIALMATCHOFTHECUSTOMERSNAME 4HEPATTERNMATCHINGTEST,)+% SHOWNIN&IGURE CHECKSTOSEEWHETHERTHEDATA VALUEINACOLUMNMATCHESASPECIFIEDPATTERN4HEPATTERNISASTRINGTHATMAYINCLUDEONE ORMOREWILDCARDCHARACTERS4HESECHARACTERSAREINTERPRETEDINASPECIALWAY
7ILDCARDõ#HARACTERS 4HEPERCENTSIGN WILDCARDCHARACTERMATCHESANYSEQUENCEOFZEROORMORECHARACTERS (ERESAMODIFIEDVERSIONOFTHEPREVIOUSQUERYTHATUSESTHEPERCENTSIGNFORPATTERNMATCHING 3%,%#4#/-0!.9 #2%$)4?,)-)4 &2/-#534/-%23 7(%2%#/-0!.9,)+%g3MITH#ORPg
4HE,)+%KEYWORDTELLS31,TOCOMPARETHE.!-%COLUMNTOTHEPATTERN3MITH #ORP!NYOFTHEFOLLOWINGNAMESWOULDMATCHTHEPATTERN 3MITH#ORP3MITHSON#ORP3MITHSEN#ORP3MITHSONIAN#ORP
BUTTHESENAMESWOULDNOT 3MITH#ORP3MITHSON)NC
1, ÊÈÊ *>ÌÌiÀÊ>ÌV
}ÊÌiÃÌÊ,)+%®ÊÃÞÌ>ÝÊ`>}À>
#HAPTERçç
3IMPLEç1UERIESç
4HEUNDERSCORE? WILDCARDCHARACTERMATCHESANYSINGLECHARACTER)FYOUARESURETHAT THECOMPANYSNAMEISEITHERh3MITHSONvORh3MITHSEN vFOREXAMPLE YOUCANUSETHIS QUERY 3%,%#4#/-0!.9 #2%$)4?,)-)4 &2/-#534/-%23 7(%2%#/-0!.9,)+%g3MITHS?N#ORPg
)NTHISCASE ANYOFTHESENAMESWILLMATCHTHEPATTERN 3MITHSON#ORP3MITHSEN#ORP3MITHSUN#ORP
3MITHSOON#ORP3MITHSN#ORP
7ILDCARDCHARACTERSCANAPPEARANYWHEREINTHEPATTERNSTRING ANDSEVERALWILDCARD CHARACTERSCANBEWITHINASINGLESTRING4HISQUERYALLOWSEITHERTHEh3MITHSONvOR h3MITHSENvSPELLINGANDWILLALSOACCEPTh#ORP vh)NC vORANYOTHERENDINGONTHE COMPANYNAME 3%,%#4#/-0!.9 #2%$)4?,)-)4 &2/-#534/-%23 7(%2%#/-0!.9,)+%g3MITHS?Ng
9OUCANLOCATESTRINGSTHATDONOTMATCHAPATTERNBYUSINGTHE./4,)+%FORMOFTHE PATTERNMATCHINGTEST4HE,)+%TESTMUSTBEAPPLIEDTOACOLUMNWITHASTRINGDATATYPE )FTHEDATAVALUEINTHECOLUMNIS.5,, THE,)+%TESTRETURNSA.5,,RESULT )FYOUHAVEUSEDCOMPUTERSTHROUGHACOMMAND LINEINTERFACESUCHASTHE5.)8SHELL YOUVEPROBABLYSEENSTRINGPATTERNMATCHINGBEFORE&REQUENTLY THEASTERISK ISUSED INSTEADOFTHE31,PERCENTSIGN ANDTHEQUESTIONMARK ISUSEDINSTEADOFTHE31, UNDERSCORE? BUTTHEPATTERNMATCHINGCAPABILITIESTHEMSELVESARESIMILARINMOST SITUATIONSWHEREACOMPUTERAPPLICATIONOFFERSTHECAPABILITYTOMATCHSELECTEDPARTSOFA WORDORTEXT
%SCAPEõ#HARACTERS
/NEOFTHEPROBLEMSWITHSTRINGPATTERNMATCHINGISHOWTOMATCHTHEWILDCARDCHARACTERS THEMSELVESASLITERALCHARACTERS4OTESTFORTHEPRESENCEOFAPERCENTSIGNCHARACTERINA COLUMNOFTEXTDATA FOREXAMPLE YOUCANTSIMPLYINCLUDETHEPERCENTSIGNINTHEPATTERN BECAUSE31,WILLTREATITASAWILDCARD7ITHSOMESIMPLER31,PRODUCTS YOUCANNOT LITERALLYMATCHTHETWOWILDCARDCHARACTERS4HISUSUALLYDOESNTPOSESERIOUSPROBLEMS BECAUSETHEWILDCARDCHARACTERSDONTFREQUENTLYAPPEARINNAMES PRODUCTNUMBERS AND OTHERTEXTDATAOFTHESORTTHATISUSUALLYSTOREDINADATABASE 4HE!.3))3/31,STANDARDDOESSPECIFYAWAYTOLITERALLYMATCHWILDCARDCHARACTERS USINGASPECIALESCAPECHARACTER7HENTHEESCAPECHARACTERAPPEARSINTHEPATTERN THE CHARACTERIMMEDIATELYFOLLOWINGITISTREATEDASALITERALCHARACTERRATHERTHANASAWILDCARD CHARACTER4HELATTERCHARACTERISSAIDTOBEESCAPED 4HEESCAPEDCHARACTERCANBEEITHEROF THETWOWILDCARDCHARACTERS ORTHEESCAPECHARACTERITSELF WHICHHASNOWTAKENONASPECIAL MEANINGWITHINTHEPATTERN
0!24ç))
BUTTHESENAMESWILLNOT
ç
0ARTç))ç
2ETRIEVINGç$ATA
4HEESCAPECHARACTERISSPECIFIEDASAONE CHARACTERCONSTANTSTRINGINTHE%3#!0%CLAUSE OFTHESEARCHCONDITION ASSHOWNIN&IGURE (EREISANEXAMPLEUSINGADOLLARSIGN AS THEESCAPECHARACTER &INDPRODUCTSWHOSEPRODUCT)$SSTARTWITHTHEFOURLETTERSh!"#v 3%,%#4/2$%2?.5- 02/$5#4 &2/-/2$%23 7(%2%02/$5#4,)+%g!"#g%3#!0%gg
4HEFIRSTPERCENTSIGNINTHEPATTERN WHICHFOLLOWSANESCAPECHARACTER ISTREATEDASA LITERALPERCENTSIGNTHESECONDFUNCTIONSASAWILDCARD 4HEUSEOFESCAPECHARACTERSISVERYCOMMONINPATTERNMATCHINGAPPLICATIONS WHICHIS WHYTHE!.3))3/STANDARDSPECIFIEDIT(OWEVER ITWASNOTAPARTOFTHEEARLY31, IMPLEMENTATIONS ANDSOMEDATABASESYSTEMSHAVEIMPLEMENTEDOTHERPATTERN MATCHING SCHEMES4OENSUREPORTABILITY THE%3#!0%CLAUSESHOULDBEAVOIDED
4HEõ.ULLõ6ALUEõ4ESTõ)3õ.5,, .5,,VALUESCREATEATHREE VALUEDLOGICFOR31,SEARCHCONDITIONS&ORANYGIVENROW THE RESULTOFASEARCHCONDITIONMAYBE425%OR&!,3% ORITMAYBE.5,,BECAUSEONEOFTHE COLUMNSUSEDINEVALUATINGTHESEARCHCONDITIONCONTAINSA.5,,VALUE3OMETIMESITS USEFULTOCHECKEXPLICITLYFOR.5,,VALUESINASEARCHCONDITIONANDHANDLETHEMDIRECTLY 31,PROVIDESASPECIAL.5,,VALUETEST)3.5,, SHOWNIN&IGURE TOHANDLETHISTASK 4HISQUERYUSESTHE.5,,VALUETESTTOFINDTHESALESPERSONINTHESAMPLEDATABASEWHO HASNOTYETBEENASSIGNEDTOANOFFICE &INDTHESALESPERSONNOTYETASSIGNEDTOANOFFICE 3%,%#4.!-% &2/-3!,%32%03 7(%2%2%0?/&&)#%)3.5,, .!-%
4OM3NYDER
4HENEGATEDFORMOFTHE.5,,VALUETEST)3./4.5,, FINDSROWSTHATDONOTCONTAINA .5,,VALUE ,ISTTHESALESPEOPLEWHOHAVEBEENASSIGNEDTOANOFFICE 3%,%#4.!-% &2/-3!,%32%03 7(%2%2%0?/&&)#%)3./4.5,,
1, ÊÈ£äÊ .5,,ÊÛ>ÕiÊÌiÃÌÊ)3.5,,®ÊÃÞÌ>ÝÊ`>}À>
#HAPTERçç
3IMPLEç1UERIESç
.!-%
"ILL!DAMS -ARY*ONES 3UE3MITH 3AM#LARK "OB3MITH $AN2OBERTS ,ARRY&ITCH 0AUL#RUZ .ANCY!NGELLI
3%,%#4.!-% &2/-3!,%32%03 7(%2%2%0?/&&)#%.5,,
4HE.5,,KEYWORDCANTBEUSEDHEREBECAUSEITISNTREALLYAVALUEITSJUSTASIGNALTHAT THEVALUEISUNKNOWN%VENIFTHECOMPARISONTEST 2%0?/&&)#%.5,,
WERELEGAL THERULESFORHANDLING.5,,VALUESINCOMPARISONSWOULDCAUSEITTOBEHAVE DIFFERENTLYFROMWHATYOUMIGHTEXPECT7HEN31,ENCOUNTEREDAROWWHERETHE2%0? /&&)#%COLUMNWAS.5,, THESEARCHCONDITIONWOULDTEST .5,,.5,,
)STHERESULT425%OR&!,3%"ECAUSETHEVALUESONBOTHSIDESOFTHEEQUALSIGNARE UNKNOWN 31,CANTTELL SOTHERULESOF31,LOGICSAYTHATTHESEARCHCONDITIONITSELFMUST YIELDA.5,,RESULT"ECAUSETHESEARCHCONDITIONDOESNTPRODUCEATRUERESULT THEROWIS EXCLUDEDFROMTHEQUERYRESULTSPRECISELYTHEOPPOSITEOFWHATYOUWANTEDTOHAPPEN!S ARESULTOFTHEWAY31,HANDLES.5,,SINCOMPARISONS YOUMUSTEXPLICITLYUSETHE.5,, VALUETESTTOCHECKFOR.5,,VALUES
#OMPOUNDõ3EARCHõ#ONDITIONSõ!.$ õ/2 õANDõ./4 4HESIMPLESEARCHCONDITIONSDESCRIBEDINTHEPRECEDINGSECTIONSRETURNAVALUEOF425% &!,3% OR.5,,WHENAPPLIEDTOAROWOFDATA5SINGTHERULESOFLOGIC YOUCANCOMBINE THESESIMPLE31,SEARCHCONDITIONSTOFORMMORECOMPLEXONES ASSHOWNIN&IGURE
1, ÊÈ££Ê 7(%2%ÊV>ÕÃiÊÃÞÌ>ÝÊ`>}À>
0!24ç))
5NLIKETHEPREVIOUSLYDESCRIBEDSEARCHCONDITIONS THE.5,,VALUETESTCANNOTYIELDA .5,,RESULT)TISALWAYSEITHER425%OR&!,3% )TMAYSEEMSTRANGETHATYOUCANTJUSTTESTFORA.5,,VALUEUSINGASIMPLECOMPARISON SEARCHCONDITION SUCHASTHIS
ç
0ARTç))ç
2ETRIEVINGç$ATA
.OTETHATTHESEARCHCONDITIONSCOMBINEDWITH!.$ /2 AND./4MAYTHEMSELVESBE COMPOUNDSEARCHCONDITIONS 4HEKEYWORD/2ISUSEDTOCOMBINETWOSEARCHCONDITIONSWHENONEORTHEOTHEROR BOTH MUSTBETRUE &INDSALESPEOPLEWHOAREUNDERQUOTAORWITHSALESUNDER 3%,%#4.!-% 15/4! 3!,%3 &2/-3!,%32%03 7(%2%3!,%315/4! /23!,%3 .!-%15/4!3!,%3
3AM#LARK "OB3MITH 4OM3NYDER.5,, 0AUL#RUZ .ANCY!NGELLI
9OUCANALSOUSETHEKEYWORD!.$TOCOMBINETWOSEARCHCONDITIONSTHATMUSTBOTHBETRUE &INDSALESPEOPLEWHOAREUNDERQUOTAANDWITHSALESUNDER 3%,%#4.!-% 15/4! 3!,%3 &2/-3!,%32%03 7(%2%3!,%315/4! !.$3!,%3 .!-%15/4!3!,%3
"OB3MITH .ANCY!NGELLI
&INALLY YOUCANUSETHEKEYWORD./4TOSELECTROWSWHEREASEARCHCONDITIONISFALSE &INDALLSALESPEOPLEWHOAREUNDERQUOTA BUTWHOSESALESARENOTUNDER 3%,%#4.!-% 15/4! 3!,%3 &2/-3!,%32%03 7(%2%3!,%315/4! !.$./43!,%3 .!-%15/4!3!,%3
.ANCY!NGELLI
5SINGTHELOGICAL!.$ /2 AND./4KEYWORDSANDPARENTHESESTOGROUPTHESEARCH CRITERIA YOUCANBUILDVERYCOMPLEXSEARCHCRITERIA SUCHASTHEONEINTHISQUERY &INDALLSALESPEOPLEWHOA WORKIN$ENVER .EW9ORK OR#HICAGOORB HAVENOMANAGERANDWERE HIREDSINCE*UNEORC AREOVERQUOTA BUTHAVESALESOF ORLESS
#HAPTERçç
3IMPLEç1UERIESç
3%,%#4.!-% &2/-3!,%32%03 7(%2%2%0?/&&)#%). /2-!.!'%2)3.5,,!.$()2%?$!4%g g /23!,%315/4!!.$./43!,%3
3!,%3 15/4! )35.+./7.
!.$
425%
&!,3%
.5,,
425%
425%
&!,3%
.5,,
&!,3%
&!,3%
&!,3%
&!,3%
.5,,
.5,,
&!,3%
.5,,
/ ÊÈ£Ê /
iÊ!.$Ê/ÀÕÌ
Ê/>Li
/2
425%
&!,3%
.5,,
425%
425%
425%
425%
&!,3%
425%
&!,3%
.5,,
.5,,
425%
.5,,
.5,,
425%
&!,3%
.5,,
&!,3%
425%
.5,,
/ ÊÈÓÊ /
iÊ/2Ê/ÀÕÌ
Ê/>Li
./4
/ ÊÈÎÊ /
iÊ./4Ê/ÀÕÌ
Ê/>Li
0!24ç))
%XACTLYWHYYOUMIGHTWANTTOSEETHISPARTICULARLISTOFNAMESISAMYSTERY BUTTHE EXAMPLEDOESILLUSTRATEAREASONABLYCOMPLEXQUERY !SWITHSIMPLESEARCHCONDITIONS .5,,VALUESINFLUENCETHEOUTCOMEOFCOMPOUND SEARCHCONDITIONS ANDTHERESULTSARESUBTLE)NPARTICULAR THERESULTOF.5,,/2425% IS 425% NOT.5,, ASYOUMIGHTEXPECT4ABLES AND SPECIFYTRUTHTABLESFOR!.$ /2 AND./4 RESPECTIVELY ANDSHOWTHEIMPACTOF.5,,VALUES 7HENMORETHANTWOSEARCHCONDITIONSARECOMBINEDWITH!.$ /2 AND./4 THE!.3) )3/STANDARDSPECIFIESTHAT./4HASTHEHIGHESTPRECEDENCE FOLLOWEDBY!.$ANDTHEN/2 4OENSUREPORTABILITY ITSALWAYSAGOODIDEATOUSEPARENTHESESANDREMOVEANYPOSSIBLE AMBIGUITY 4HE31,ALSOKNOWNAS31, AND31, STANDARDADDEDANOTHERLOGICALSEARCH CONDITION THE)3TEST TOTHELOGICPROVIDEDBY!.$ /2 AND./4&IGURE SHOWSTHE SYNTAXOFTHE)3TEST WHICHCHECKSTOSEEWHETHERTHELOGICALVALUEOFANEXPRESSIONOR COMPARISONTESTIS425% &!,3% OR5.+./7..5,, &OREXAMPLE THE)3TEST
ç
0ARTç))ç
2ETRIEVINGç$ATA
1, ÊÈ£ÓÊ /
iÊ)3ÊÌiÃÌÊÃÞÌ>ÝÊ`>}À>
CANBEUSEDTOFINDROWSWHERETHECOMPARISONCANNOTBEDONEBECAUSEEITHER3!,%3OR 15/4!HASA.5,,VALUE3IMILARLY THE)3TEST 3!,%3 15/4! )3&!,3%
WILLSELECTROWSWHERE3!,%3ARENOTSIGNIFICANTLYABOVE15/4!!STHISEXAMPLESHOWS THE )3TESTDOESNTREALLYADDTOTHEEXPRESSIVEPOWEROF31, SINCETHETESTCOULDJUSTASEASILY HAVEBEENWRITTEN ./43!,%3 15/4!
!LTHOUGHTHE)3TESTHASBEENINCLUDEDINTHE31,3TANDARDSINCE VERYFEW31, PRODUCTSPROVIDESUPPORTFORIT4HEREFORE FORMAXIMUMPORTABILITY ITSAGOODIDEATO AVOIDTHETESTANDTOWRITETHEEXPRESSIONSUSINGONLY!.$ /2 AND./4(OWEVER ITSNOT ALWAYSPOSSIBLETOAVOIDTHE)35.+./7.FORMOFTHETEST
3ORTINGõ1UERYõ2ESULTSõ/2$%2õ"9õ#LAUSE ,IKETHEROWSOFATABLEINTHEDATABASE THEROWSOFQUERYRESULTSARENOTARRANGEDINANY PARTICULARORDER9OUCANASK31,TOSORTTHERESULTSOFAQUERYBYINCLUDINGTHE/2$%2"9 CLAUSEINTHE3%,%#4STATEMENT4HE/2$%2"9CLAUSE SHOWNIN&IGURE CONSISTSOFTHE KEYWORDS/2$%2"9 FOLLOWEDBYALISTOFSORTSPECIFICATIONSSEPARATEDBYCOMMAS&OR EXAMPLE THERESULTSOFTHISQUERYARESORTEDONTWOCOLUMNS 2%')/.AND#)49 3HOWTHESALESFOREACHOFFICE SORTEDINALPHABETICALORDERBYREGION ANDWITHINEACHREGIONBYCITY 3%,%#4#)49 2%')/. 3!,%3 &2/-/&&)#%3 /2$%2"92%')/. #)49 #)492%')/.3!,%3
!TLANTA%ASTERN #HICAGO%ASTERN .EW9ORK%ASTERN $ENVER7ESTERN ,OS!NGELES7ESTERN
4HEFIRSTSORTSPECIFICATION2%')/. ISTHEMAJORSORTKEYTHOSETHATFOLLOW#)49 IN THISCASE AREPROGRESSIVELYMOREMINORSORTKEYS USEDAShTIEBREAKERSvWHENTWOROWSOF QUERYRESULTSHAVETHESAMEVALUESFORTHEMOREMAJORKEYS5SINGTHE/2$%2"9CLAUSE
#HAPTERçç
3IMPLEç1UERIESç
1, ÊÈ£ÎÊ /
iÊ/2$%2"9ÊV>ÕÃiÊÃÞÌ>ÝÊ`>}À>
,ISTTHEOFFICES SORTEDINDESCENDINGORDERBYSALES SOTHATTHEOFFICESWITHTHELARGESTSALESAPPEAR FIRST 3%,%#4#)49 2%')/. 3!,%3 &2/-/&&)#%3 /2$%2"93!,%3$%3# #)492%')/.3!,%3
,OS!NGELES7ESTERN #HICAGO%ASTERN .EW9ORK%ASTERN !TLANTA%ASTERN $ENVER7ESTERN
!SINDICATEDIN&IGURE YOUCANALSOUSETHEKEYWORD!3#TOSPECIFYANASCENDING SORT BUTBECAUSETHATSTHEDEFAULTSORTINGSEQUENCE THEKEYWORDISUSUALLYOMITTED )FTHECOLUMNOFQUERYRESULTSTOBEUSEDFORSORTINGISACALCULATEDCOLUMN ITHASNO COLUMNNAMETOBEUSEDINASORTSPECIFICATION)NTHISCASE YOUMUSTEITHERSPECIFYA COLUMNNUMBERINSTEADOFACOLUMNNAME ORREPEATTHECOLUMNEXPRESSIONINTHE/2$%2 "9CLAUSE ASINTHEFOLLOWINGEXAMPLE.OTETHATTHEUSEOFCOLUMNNUMBERSISANOLDER WAYOFWRITING31, ANDITISNOLONGERRECOMMENDED BECAUSEITISMOREPRONETOERROR WHENSOMEONESUBSEQUENTLYCHANGESTHECOLUMNORDERINTHE3%,%#4CLAUSE NOTNOTICING THECOLUMNNUMBERREFERENCESINTHE/2$%2"9CLAUSE ,ISTTHEOFFICES SORTEDINDESCENDINGORDERBYSALESPERFORMANCE SOTHATTHEOFFICESWITHTHEBEST PERFORMANCEAPPEARFIRST 3%,%#4#)49 2%')/. 3!,%3 4!2'%4 &2/-/&&)#%3 /2$%2"9$%3#
OR 3%,%#4#)49 2%')/. 3!,%3n4!2'%4 &2/-/&&)#%3 /2$%2"93!,%3n4!2'%4 $%3#
0!24ç))
YOUCANREQUESTSORTINGINANASCENDINGORDESCENDINGSEQUENCE ANDYOUCANSORTONANY ITEMINTHESELECTLISTOFTHEQUERY "YDEFAULT 31,SORTSDATAINASCENDINGSEQUENCE4OREQUESTSORTINGINDESCENDING SEQUENCE THEKEYWORD$%3#ISINCLUDEDINTHESORTSPECIFICATION ASINTHENEXTEXAMPLE
ç
0ARTç))ç
2ETRIEVINGç$ATA
#)492%')/.3!,%3 4!2'%4
.EW9ORK%ASTERN ,OS!NGELES7ESTERN !TLANTA%ASTERN #HICAGO%ASTERNn $ENVER7ESTERNn
4HESEQUERYRESULTSARESORTEDONTHETHIRDCOLUMN WHICHISTHECALCULATEDDIFFERENCE BETWEENTHE3!,%3AND4!2'%4FOREACHOFFICE"YCOMBININGCOLUMNNUMBERS COLUMN NAMES ASCENDINGSORTS ANDDESCENDINGSORTS YOUCANSPECIFYQUITECOMPLEXSORTINGOFTHE QUERYRESULTS ASINTHEFOLLOWINGFINALEXAMPLE ,ISTTHEOFFICES SORTEDINALPHABETICALORDERBYREGION ANDWITHINEACHREGIONINDESCENDINGORDERBY SALESPERFORMANCE 3%,%#4#)49 2%')/. 3!,%3 4!2'%4 &2/-/&&)#%3 /2$%2"92%')/.!3# $%3# #)492%')/.3!,%3 4!2'%4
.EW9ORK%ASTERN !TLANTA%ASTERN #HICAGO%ASTERNn ,OS!NGELES7ESTERN $ENVER7ESTERNn
4HE31,STANDARDALLOWSYOUTOCONTROLTHESORTINGORDEROFTHEINDIVIDUALCHARACTERS WITHINACHARACTERSET OFTENCALLEDTHECOLLATINGSEQUENCEOFTHECHARACTERS4HISCANBEIMPORTANT WHENWORKINGWITHINTERNATIONALCHARACTERSETSFOREXAMPLE TOSPECIFYHOWDIACRITICALMARKS SUCHASACCENTSORUMLAUTSORCOMPOUNDLETTERSSHOULDBESORTED ORTOENSUREPORTABILITY BETWEEN!3#))AND%"#$)#CHARACTERSETSYSTEMS(OWEVER THISAREAOFTHE31,STANDARDIS QUITECOMPLEX ANDINPRACTICE MANY31,IMPLEMENTATIONSEITHERIGNORESORTINGSEQUENCE ISSUES ORUSETHEIROWNPROPRIETARYSCHEMEFORUSERCONTROLOFTHESORTINGSEQUENCE
2ULESõFORõ3INGLE 4ABLEõ1UERYõ0ROCESSING 3INGLE TABLEQUERIESAREGENERALLYSIMPLE ANDITSUSUALLYEASYTOUNDERSTANDTHEMEANING OFAQUERYJUSTBYREADINGTHE3%,%#4STATEMENT!SQUERIESBECOMEMORECOMPLEX HOWEVER ITSIMPORTANTTOHAVEAMOREPRECISEhDEFINITIONvOFTHEQUERYRESULTSTHATWILLBE PRODUCEDBYAGIVEN3%,%#4STATEMENT4HEFOLLOWINGSTEPSDESCRIBETHEPROCEDUREFOR GENERATINGTHERESULTSOFA31,QUERYTHATINCLUDESTHECLAUSESDESCRIBEDINTHISCHAPTER !STHESESTEPSSHOW THEQUERYRESULTSPRODUCEDBYA3%,%#4STATEMENTARESPECIFIEDBY APPLYINGEACHOFITSCLAUSES ONEBYONE4HE&2/-CLAUSEISAPPLIEDFIRSTSELECTINGTHETABLE ORVIEWCONTAININGDATATOBERETRIEVED 4HE7(%2%CLAUSEISAPPLIEDNEXTSELECTINGSPECIFIC ROWSFROMTHETABLE 4HE3%,%#4CLAUSEISAPPLIEDNEXTGENERATINGTHESPECIFICCOLUMNSOF QUERYRESULTSANDELIMINATINGDUPLICATEROWS IFREQUESTED &INALLY THE/2$%2"9CLAUSEIS APPLIEDTOSORTTHEQUERYRESULTS
#HAPTERçç
3IMPLEç1UERIESç
4OGENERATETHEQUERYRESULTSFORASINGLE TABLE3%,%#4STATEMENT FOLLOWTHESESTEPS 3TARTWITHTHETABLENAMEDINTHE&2/-CLAUSE
)FTHEREISA7(%2%CLAUSE APPLYITSSEARCHCONDITIONTOEACHROWOFTHETABLE RETAININGTHOSEROWSFORWHICHTHESEARCHCONDITIONIS425% ANDDISCARDINGTHOSE ROWSFORWHICHITIS&!,3%OR.5,,
&OREACHREMAININGROW CALCULATETHEVALUEOFEACHITEMINTHESELECTLISTTOPRODUCE ASINGLEROWOFQUERYRESULTS&OREACHCOLUMNREFERENCE USETHEVALUEOFTHE COLUMNINTHECURRENTROW
)F3%,%#4$)34).#4ISSPECIFIED ELIMINATEANYDUPLICATEROWSOFQUERYRESULTSTHAT WEREPRODUCED
)FTHEREISAN/2$%2"9CLAUSE SORTTHEQUERYRESULTSASSPECIFIED
4HEROWSGENERATEDBYTHISPROCEDURECOMPRISETHEQUERYRESULTS 4HESEhRULESvFOR31,QUERYPROCESSINGWILLBEEXPANDEDSEVERALTIMESINTHENEXTTHREE CHAPTERSTOINCLUDETHEREMAININGCLAUSESOFTHE3%,%#4STATEMENT
#OMBININGõ1UERYõ2ESULTSõ5.)/.
/CCASIONALLY ITSCONVENIENTTOCOMBINETHERESULTSOFTWOORMOREQUERIESINTOASINGLETABLEOF QUERYRESULTS31,SUPPORTSTHISCAPABILITYTHROUGHTHE5.)/.FEATUREOFTHE3%,%#4STATEMENT &IGURE ILLUSTRATESHOWTOUSETHE5.)/.OPERATIONTOSATISFYTHEFOLLOWINGREQUEST ,ISTALLTHEPRODUCTSWHERETHEPRICEOFTHEPRODUCTEXCEEDS ORWHEREMORETHAN OF THEPRODUCTHASBEENORDEREDINASINGLEORDER
1, ÊÈ£{Ê 1Ã}Ê5.)/.ÊÌÊVLiʵÕiÀÞÊÀiÃÕÌÃ
0!24ç))
ç
0ARTç))ç
2ETRIEVINGç$ATA
4HEFIRSTPARTOFTHEREQUESTCANBESATISFIEDWITHTHETOPQUERYINTHEFIGURE ,ISTALLTHEPRODUCTSWHOSEPRICEEXCEEDS 3%,%#4-&2?)$ 02/$5#4?)$ &2/-02/$5#43 7(%2%02)#% -&2?)$02/$5#4?)$
!#)9 2%)!, !#): 2%)!2
3IMILARLY THESECONDPARTOFTHEREQUESTCANBESATISFIEDWITHTHEBOTTOMQUERYINTHE FIGURE ,ISTALLTHEPRODUCTSWHEREMORETHAN OFTHEPRODUCTHASBEENORDEREDINASINGLEORDER 3%,%#4$)34).#4-&2 02/$5#4 &2/-/2$%23 7(%2%!-/5.4 -&202/$5#4
)--# 2%)!, 2%)!2
!SSHOWNIN&IGURE THE5.)/.OPERATIONPRODUCESASINGLETABLEOFQUERYRESULTS THATCOMBINESTHEROWSOFTHETOPQUERYRESULTSWITHTHEROWSOFTHEBOTTOMQUERYRESULTS 4HE3%,%#4STATEMENTTHATSPECIFIESTHE5.)/.OPERATIONLOOKSLIKETHIS ,ISTALLTHEPRODUCTSWHERETHEPRICEOFTHEPRODUCTEXCEEDS ORWHEREMORETHAN OFTHE PRODUCTHASBEENORDEREDINASINGLEORDER 3%,%#4-&2?)$ 02/$5#4?)$ &2/-02/$5#43 7(%2%02)#% 5.)/. 3%,%#4$)34).#4-&2 02/$5#4 &2/-/2$%23 7(%2%!-/5.4 !#)9 !#): )--# 2%)!, 2%)!2
4HEREARESEVERERESTRICTIONSONTHETABLESTHATCANBECOMBINEDBYA5.)/.OPERATION s 4HETWO3%,%#4CLAUSESMUSTCONTAINTHESAMENUMBEROFCOLUMNS
#HAPTERçç
3IMPLEç1UERIESç
s 4HEDATATYPEOFEACHCOLUMNSELECTEDFROMTHEFIRSTTABLEMUSTBETHESAMEASTHE DATATYPEOFTHECORRESPONDINGCOLUMNSELECTEDFROMTHESECONDTABLE s .EITHEROFTHETWOTABLESCANBESORTEDWITHTHE/2$%2"9CLAUSE(OWEVER THE COMBINEDQUERYRESULTSCANBESORTED ASDESCRIBEDINTHEFOLLOWINGSECTION
5NIONSõANDõ$UPLICATEõ2OWS
"ECAUSETHE5.)/.OPERATIONCOMBINESTHEROWSFROMTWOSETSOFQUERYRESULTS ITWOULD TENDTOPRODUCEQUERYRESULTSCONTAININGDUPLICATEROWS&OREXAMPLE INTHEQUERYOF &IGURE PRODUCT2%) !,SELLSFOR SOITAPPEARSINTHETOPSETOFQUERY RESULTS4HEREISALSOANORDERFOR WORTHOFTHISPRODUCTINTHE/2$%23TABLE SOIT ALSOAPPEARSINTHEBOTTOMSETOFQUERYRESULTS"YDEFAULT THE5.)/.OPERATIONELIMINATES DUPLICATEROWSASPARTOFITSPROCESSING4HUS THECOMBINEDSETOFQUERYRESULTSCONTAINS ONLYONEROWFORPRODUCT2%) !, )FYOUWANTTORETAINDUPLICATEROWSINA5.)/.OPERATION YOUCANSPECIFYTHE!,, KEYWORDIMMEDIATELYFOLLOWINGTHEWORD5.)/.4HISFORMOFTHEQUERYPRODUCESTWO DUPLICATEROWSFORPRODUCT2%) !, ,ISTALLTHEPRODUCTSWHERETHEPRICEOFTHEPRODUCTEXCEEDS ORWHEREMORETHAN OFTHE PRODUCTHASBEENORDEREDINASINGLEORDER 3%,%#4-&2?)$ 02/$5#4?)$ &2/-02/$5#43 7(%2%02)#% 5.)/.!,, 3%,%#4$)34).#4-&2 02/$5#4 &2/-/2$%23 7(%2%!-/5.4 !#)9 2%)!, !#): 2%)!2 )--# 2%)!, 2%)!2
0!24ç))
.OTETHATTHECOLUMNNAMESOFTHETWOQUERIESCOMBINEDBY5.)/.DONOTHAVETOBE IDENTICAL)NTHEPRECEDINGEXAMPLE THEFIRSTTABLEOFQUERYRESULTSHASCOLUMNSNAMED-&2? )$AND02/$5#4?)$ WHILETHESECONDTABLEOFQUERYRESULTSHASCOLUMNSNAMED-&2AND 02/$5#4"ECAUSETHECOLUMNSINTHETWOTABLESCANHAVEDIFFERENTNAMES THECOLUMNSOF QUERYRESULTSPRODUCEDBYTHE5.)/.OPERATIONAREUNNAMED 4HEORIGINAL!.3))3/31,STANDARDSPECIFIEDAFURTHERRESTRICTIONONA3%,%#4 STATEMENTTHATPARTICIPATESINA5.)/.OPERATION)TPERMITSONLYCOLUMNNAMESORANALL COLUMNSSPECIFICATION3%,%#4 INTHESELECTLISTANDPROHIBITSEXPRESSIONSINTHESELECT LIST-OSTCOMMERCIAL31,IMPLEMENTATIONSRELAXTHISRESTRICTIONANDPERMITSIMPLE EXPRESSIONSINTHESELECTLIST(OWEVER MANY31,IMPLEMENTATIONSDONOTALLOWTHE 3%,%#4STATEMENTSTOINCLUDETHE'2/50"9OR(!6).'CLAUSES ANDSOMEDONOTALLOW COLUMNFUNCTIONSINTHESELECTLISTPROHIBITINGSUMMARYQUERIESASDESCRIBEDIN#HAPTER )NFACT SOMESIMPLE31,IMPLEMENTATIONSDONOTSUPPORTTHE5.)/.OPERATIONATALL
ç
0ARTç))ç
2ETRIEVINGç$ATA
.OTETHATTHEDEFAULTDUPLICATEROWHANDLINGFORTHE5.)/.OPERATIONANDFORTHE SIMPLE3%,%#4STATEMENTISEXACTLYOPPOSITE&ORTHE3%,%#4STATEMENT 3%,%#4!,, DUPLICATESRETAINED ISTHEDEFAULT4OELIMINATEDUPLICATEROWS YOUMUSTEXPLICITLYSPECIFY 3%,%#4$)34).#4&ORTHE5.)/.OPERATION 5.)/.DUPLICATESELIMINATED ISTHEDEFAULT 4ORETAINDUPLICATEROWS YOUMUSTEXPLICITLYSPECIFY5.)/.!,, $ATABASEEXPERTSHAVECRITICIZEDTHEHANDLINGOFDUPLICATEROWSIN31,ANDPOINTTOTHIS INCONSISTENCYASANEXAMPLEOFTHEPROBLEMS4HEREASONFORTHEINCONSISTENCYISTHATTHE 31,DEFAULTSWERECHOSENTOPRODUCETHECORRECTBEHAVIORMOSTOFTHETIME s )NPRACTICE MOSTSIMPLE3%,%#4STATEMENTSDONOTPRODUCEDUPLICATEROWS SOTHE DEFAULTISNODUPLICATEELIMINATION s )NPRACTICE MOST5.)/.OPERATIONSWOULDPRODUCEUNWANTEDDUPLICATEROWS SOTHE DEFAULTISDUPLICATEELIMINATION %LIMINATINGDUPLICATEROWSFROMQUERYRESULTSISAVERYTIME CONSUMINGPROCESS ESPECIALLY IFTHEQUERYRESULTSCONTAINALARGENUMBEROFROWS)FYOUKNOW BASEDONTHEINDIVIDUAL QUERIESINVOLVED THATA5.)/.OPERATIONCANNOTPRODUCEDUPLICATEROWS YOUSHOULD SPECIFICALLYUSETHE5.)/.!,,OPERATIONBECAUSETHEQUERYWILLEXECUTEMUCHMOREQUICKLY
5NIONSõANDõ3ORTING
4HE/2$%2"9CLAUSECANNOTAPPEARINEITHEROFTHETWO3%,%#4STATEMENTSCOMBINED BYA5.)/.OPERATION)TWOULDNTMAKEMUCHSENSETOSORTTHETWOSETSOFQUERYRESULTS ANYWAY BECAUSETHEYAREFEDDIRECTLYINTOTHE5.)/.OPERATIONANDARENEVERVISIBLETO THEUSER(OWEVER THECOMBINEDSETOFQUERYRESULTSPRODUCEDBYTHE5.)/.OPERATIONCAN BESORTEDBYSPECIFYINGAN/2$%2"9CLAUSEAFTERTHESECOND3%,%#4STATEMENT3INCETHE COLUMNSPRODUCEDBYTHE5.)/.OPERATIONARENOTNAMED THE/2$%2"9CLAUSESPECIFIES THECOLUMNSBYCOLUMNNUMBER(OWEVER MANY31,PRODUCTS INCLUDING/RACLE 31, 3ERVERAND-Y31, USETHECOLUMNNAMESFROMTHEFIRST3%,%#4STATEMENT ANDTHEREFORE ALLOWYOUTOUSETHOSECOLUMNNAMESINTHE/2$%2"9CLAUSE (EREISTHESAMEPRODUCTSQUERYASTHATSHOWNIN&IGURE WITHTHEQUERYRESULTS SORTEDBYMANUFACTURERANDPRODUCTNUMBER ,ISTALLTHEPRODUCTSWHERETHEPRICEOFTHEPRODUCTEXCEEDS ORWHEREMORETHAN OFTHE PRODUCTHASBEENORDEREDINASINGLEORDER SORTEDBYMANUFACTURERANDPRODUCTNUMBER 3%,%#4-&2?)$ 02/$5#4?)$ &2/-02/$5#43 7(%2%02)#% 5.)/. 3%,%#4$)34).#4-&2 02/$5#4 &2/-/2$%23 7(%2%!-/5.4 /2$%2"9 !#)9 !#): )--# 2%)!, 2%)!2
#HAPTERçç
3IMPLEç1UERIESç
-ULTIPLEõ5.)/.S
9OUCANUSETHE5.)/.OPERATIONREPEATEDLYTOCOMBINETHREEORMORESETSOFQUERYRESULTS ASSHOWNIN&IGURE 4HEUNIONOF4ABLE"AND4ABLE#INTHEFIGUREPRODUCESASINGLE COMBINEDTABLE4HISTABLEISTHENCOMBINEDWITH4ABLE!INANOTHER5.)/.OPERATION4HE QUERYINTHEFIGUREISWRITTENTHISWAY
4HEPARENTHESESINTHEQUERYINDICATEWHICH5.)/.OPERATIONSHOULDBEPERFORMED FIRST)NFACT IFALLOFTHE5.)/.SINTHESTATEMENTELIMINATEDUPLICATEROWS ORIFALLOFTHEM RETAINDUPLICATEROWS THEORDERINWHICHTHEYAREPERFORMEDISUNIMPORTANT4HESETHREE EXPRESSIONSARECOMPLETELYEQUIVALENT !5.)/."5.)/.# !5.)/." 5.)/.# !5.)/.# 5.)/."
1, ÊÈ£xÊ
iÃÌi`Ê5.)/.Ê«iÀ>ÌÃ
0!24ç))
3%,%#4 &2/-! 5.)/.3%,%#4 &2/-" 5.)/. 3%,%#4 &2/-# "ILL -ARY 'EORGE &RED 3UE *ULIA (ARRY
ç
0ARTç))ç
2ETRIEVINGç$ATA
ANDPRODUCESEVENROWSOFQUERYRESULTS3IMILARLY THEFOLLOWINGTHREEEXPRESSIONSARE COMPLETELYEQUIVALENTANDPRODUCEROWSOFQUERYRESULTS BECAUSETHEDUPLICATESARERETAINED !5.)/.!,,"5.)/.!,,# !5.)/.!,," 5.)/.!,,# !5.)/.!,,# 5.)/.!,,"
(OWEVER IFTHE5.)/.SINVOLVEAMIXTUREOF5.)/.AND5.)/.!,, THEORDEROF EVALUATIONMATTERS)FTHISEXPRESSION !5.)/.!,,"5.)/.#
ISINTERPRETEDAS !5.)/.!,,"5.)/.#
THENITPRODUCESTENROWSOFQUERYRESULTSSIXFROMTHEINNER5.)/. PLUSFOURROWSFROM 4ABLE! (OWEVER IFITISINTERPRETEDAS !5.)/.!,," 5.)/.#
THENITPRODUCESONLYFOURROWS BECAUSETHEOUTER5.)/.ELIMINATESALLDUPLICATEROWS &ORTHISREASON ITSALWAYSAGOODIDEATOUSEPARENTHESESIN5.)/.SOFTHREEORMORETABLES TOSPECIFYTHEORDEROFEVALUATIONINTENDED
3UMMARY 4HISCHAPTERISTHEFIRSTOFFOURCHAPTERSABOUT31,QUERIES)TDESCRIBEDTHEFOLLOWINGQUERY FEATURES s 4HE3%,%#4STATEMENTISUSEDTOEXPRESSA31,QUERY%VERY3%,%#4STATEMENT PRODUCESATABLEOFQUERYRESULTSCONTAININGONEORMORECOLUMNSANDZEROOR MOREROWS s 4HE&2/-CLAUSESPECIFIESTHETABLES CONTAININGTHEDATATOBERETRIEVEDBYAQUERY s 4HE3%,%#4CLAUSESPECIFIESTHECOLUMNS OFDATATOBEINCLUDEDINTHEQUERY RESULTS WHICHCANBECOLUMNSOFDATAFROMTHEDATABASE ORCALCULATEDCOLUMNS s 4HE7(%2%CLAUSESELECTSTHEROWSTOBEINCLUDEDINTHEQUERYRESULTSBYAPPLYINGA SEARCHCONDITIONTOROWSOFTHEDATABASE s !SEARCHCONDITIONCANSELECTROWSBYCOMPARINGVALUES BYCHECKINGAVALUEAGAINSTA RANGEORSETOFVALUES BYMATCHINGASTRINGPATTERN ANDBYCHECKINGFOR.5,,VALUES s 3IMPLESEARCHCONDITIONSCANBECOMBINEDWITH!.$ /2 AND./4TOFORMMORE COMPLEXSEARCHCONDITIONS s 4HE/2$%2"9CLAUSESPECIFIESTHATTHEQUERYRESULTSSHOULDBESORTEDINASCENDING ORDESCENDINGORDER BASEDONTHEVALUESOFONEORMORECOLUMNS s 4HE5.)/.OPERATIONCANBEUSEDWITHINA3%,%#4STATEMENTTOCOMBINETWOOR MORESETSOFQUERYRESULTSINTOASINGLESET
#(!04%2
-ULTITABLEç1UERIESç*OINS
-
OSTUSEFULQUERIESREQUESTDATAFROMTWOORMORETABLESINADATABASE&OREXAMPLE THESEREQUESTSFORDATAINTHESAMPLEDATABASEDRAWDATAFROMTWO THREE ANDFOUR TABLESRESPECTIVELY
s ,ISTTHESALESPEOPLEANDTHEOFFICESWHERETHEYWORK3!,%32%03AND/&&)#%3 TABLES s ,ISTEACHORDERPLACEDLASTWEEK SHOWINGTHEORDERAMOUNT THENAMEOFTHE CUSTOMERWHOPLACEDIT ANDTHENAMEOFTHEPRODUCTORDERED/2$%23 #534/-%23 AND02/$5#43TABLES s 3HOWALLORDERSTAKENBYSALESPEOPLEINTHE%ASTERNREGION SHOWINGTHEPRODUCT DESCRIPTIONANDSALESPERSON/2$%23 3!,%32%03 /&&)#%3 AND02/$5#43TABLES 31,ALLOWSYOUTORETRIEVEDATATHATANSWERSTHESEREQUESTSTHROUGHMULTITABLEQUERIES THATJOINDATAFROMTWOORMORETABLES4HESEQUERIESANDTHE31,JOINFACILITYAREDESCRIBEDIN THISCHAPTER7EBEGINWITHTHEJOINCAPABILITIESTHATHAVEBEENAPARTOF31,FROMTHEEARLIEST DAYSANDAREFOUNDINALL31,PRODUCTSTODAY4HELATERSECTIONSDESCRIBEADDITIONALJOIN CAPABILITIESTHATFIRSTAPPEAREDIN31,STANDARDANDAREFOUNDINMOSTMAINSTREAMPRODUCTS
!õ4WO 4ABLEõ1UERYõ%XAMPLE 4HEBESTWAYTOUNDERSTANDTHEFACILITIESTHAT31,PROVIDESFORMULTITABLEQUERIESISTOSTART WITHASIMPLEREQUESTTHATCOMBINESDATAFROMTWODIFFERENTTABLES h,ISTALLORDERS SHOWINGTHEORDERNUMBERANDAMOUNT ANDTHENAMEANDCREDITLIMITOFTHE CUSTOMERWHOPLACEDITv 4HEFOURSPECIFICDATAITEMSREQUESTEDARECLEARLYSTOREDINTWODIFFERENTTABLES AS SHOWNIN&IGURE s 4HE/2$%23TABLECONTAINSTHEORDERNUMBERANDAMOUNTOFEACHORDER BUTDOESNT HAVECUSTOMERNAMESORCREDITLIMITS s 4HE#534/-%23TABLECONTAINSTHECUSTOMERNAMESANDCREDITLIMITS BUTITLACKS ANYINFORMATIONABOUTORDERS
ç
0ARTç))ç
2ETRIEVINGç$ATA
%&,) $! $
3 3 3
!
#
!
! %&,) ! $! # 3 3 3 /,-%.(+1 +.',%+0 *0))"%2+.)1 3 3 3
! $
$
1, ÊÇ£Ê ÊÀiµÕiÃÌÊÌ
>ÌÊë>ÃÊÌÜÊÌ>LiÃ
4HEREISALINKBETWEENTHESETWOTABLES HOWEVER)NEACHROWOFTHE/2$%23TABLE THE #534COLUMNCONTAINSTHECUSTOMERNUMBEROFTHECUSTOMERWHOPLACEDTHEORDER WHICH MATCHESTHEVALUEINTHE#534?.5-COLUMNINONEOFTHEROWSINTHE#534/-%23TABLE #LEARLY THE3%,%#4STATEMENTTHATHANDLESTHEREQUESTMUSTSOMEHOWUSETHISLINK BETWEENTHETABLESTOGENERATEITSQUERYRESULTS "EFOREEXAMININGTHE3%,%#4STATEMENTFORTHEQUERY ITSINSTRUCTIVETOTHINKABOUT HOWYOUWOULDMANUALLYHANDLETHEREQUEST USINGPAPERANDPENCIL&IGURE SHOWS WHATYOUWOULDPROBABLYDO
3TARTBYWRITINGDOWNTHEFOURCOLUMNNAMESFORTHEQUERYRESULTS4HENMOVETO THE/2$%23TABLE ANDSTARTWITHTHEFIRSTORDER
,OOKACROSSTHEROWTOFINDTHEORDERNUMBER ANDTHEORDERAMOUNT ANDCOPYBOTHVALUESTOTHEFIRSTROWOFQUERYRESULTS
,OOKACROSSTHEROWTOFINDTHENUMBEROFTHECUSTOMERWHOPLACEDTHEORDER ANDMOVETOTHE#534/-%23TABLETOFINDCUSTOMERNUMBERBY SEARCHINGTHE#534?.5-COLUMN
-OVEACROSSTHEROWOFTHE#534/-%23TABLETOFINDTHECUSTOMERSNAMEh*0 3INCLAIRv ANDCREDITLIMIT ANDCOPYTHEMTOTHEQUERYRESULTSTABLE
9OUVEGENERATEDAROWOFQUERYRESULTS-OVEBACKTOTHE/2$%23TABLE ANDGOTO THENEXTROW2EPEATTHEPROCESS STARTINGWITH3TEP UNTILYOURUNOUTOFORDERS
#HAPTERçç
! %&,) ! $! # 5 5 5 /,-%.(+1 +.',%+0 *0))"%4+.)1 5 5 5
! $
$
!
#
!
!#)13,21 $! 5 5 5
!
#
+.',%+0
0!24ç))
%&,) $! $ 5 5 5
-ULTITABLEç1UERIESç*OINS ç
$
1, ÊÇÓÊ >Õ>ÞÊ«ÀViÃÃ}Ê>ÊÕÌÌ>LiʵÕiÀÞ
/FCOURSETHISISNTTHEONLYWAYTOGENERATETHEQUERYRESULTS BUTREGARDLESSOFHOW YOUDOIT TWOTHINGSWILLBETRUE s %ACHROWOFQUERYRESULTSDRAWSITSDATAFROMASPECIFICPAIROFROWS ONEFROMTHE /2$%23TABLEANDONEFROMTHE#534/-%23TABLE s 4HEPAIRSOFROWSAREFOUNDBYMATCHINGTHEDATAVALUESINCORRESPONDINGCOLUMNS FROMTHETABLES
3IMPLEõ*OINSõ%QUI *OINS 4HEPROCESSOFFORMINGPAIRSOFROWSBYMATCHINGTHECONTENTSOFRELATEDCOLUMNSISCALLED JOININGTHETABLES4HERESULTINGTABLECONTAININGDATAFROMBOTHOFTHEORIGINALTABLES IS CALLEDAJOINBETWEENTHETWOTABLES!JOINBASEDONANEXACTMATCHBETWEENTWOCOLUMNS ISMOREPRECISELYCALLEDANEQUI JOIN*OINSCANALSOBEBASEDONOTHERKINDSOFCOLUMN COMPARISONS ASDESCRIBEDLATERINTHISCHAPTER
ç
0ARTç))ç
2ETRIEVINGç$ATA
*OINSARETHEFOUNDATIONOFMULTITABLEQUERYPROCESSINGIN31,!LLOFTHEDATAINA RELATIONALDATABASEISSTOREDINITSCOLUMNSASEXPLICITDATAVALUES SOALLPOSSIBLERELATIONSHIPS BETWEENTABLESCANBEFORMEDBYMATCHINGTHECONTENTSOFRELATEDCOLUMNS*OINSTHUSPROVIDE APOWERFULFACILITYFOREXERCISINGTHEDATARELATIONSHIPSINADATABASE)NFACT BECAUSERELATIONAL DATABASESDONOTCONTAINPOINTERSOROTHERMECHANISMSFORRELATINGROWSTOONEANOTHER JOINS ARETHEONLYMECHANISMFOREXERCISINGCROSS TABLEDATARELATIONSHIPS "ECAUSE31,HANDLESMULTITABLEQUERIESBYMATCHINGCOLUMNS ITSHOULDCOMEASNO SURPRISETHATTHE3%,%#4STATEMENTFORAMULTITABLEQUERYCONTAINSASEARCHCONDITIONTHAT SPECIFIESTHECOLUMNMATCH(EREISA3%,%#4STATEMENTFORTHEQUERYTHATWASPERFORMED MANUALLYIN&IGURE ,ISTALLORDERSSHOWINGORDERNUMBER AMOUNT CUSTOMERNAMEhCOMPANYv ANDTHECUSTOMERS CREDITLIMIT 3%,%#4/2$%2?.5- !-/5.4 #/-0!.9 #2%$)4?,)-)4 &2/-/2$%23 #534/-%23 7(%2%#534#534?.5- /2$%2?.5-!-/5.4#/-0!.9#2%$)4?,)-)4
*ONES-FG &IRST#ORP !CME-FG !CME-FG !CME-FG !CME-FG &RED,EWIS#ORP &RED,EWIS#ORP !CE)NTERNATIONAL !CE)NTERNATIONAL (OLM,ANDIS (OLM,ANDIS (OLM,ANDIS
2ECALLTHATDIFFERENT31,TOOLSFORMATRESULTSINDIFFERENTWAYS SOYOURRESULTSMAYVARY PARTICULARLYFORTHEDOLLARAMOUNTSSHOWNINTHEEXAMPLE4HISQUERYLOOKSJUSTLIKETHE QUERIESFROMTHEPREVIOUSCHAPTER WITHTWONEWFEATURES&IRST THE&2/-CLAUSELISTSTWO TABLESINSTEADOFJUSTONE3ECOND THESEARCHCONDITION #534#534?.5-
COMPARESCOLUMNSFROMTWODIFFERENTTABLES7ECALLTHESETWOCOLUMNSTHEMATCHING COLUMNSFORTHETWOTABLES,IKEALLSEARCHCONDITIONS THISONERESTRICTSTHEROWSTHATAPPEAR INTHEQUERYRESULTS"ECAUSETHISISATWO TABLEQUERY THESEARCHCONDITIONRESTRICTSTHEPAIRS OFROWSTHATGENERATETHEQUERYRESULTS)NFACT THESEARCHCONDITIONSPECIFIESTHESAME MATCHINGCOLUMNSYOUUSEDINTHEPAPER AND PENCILQUERYPROCESSING)TACTUALLYCAPTURES THESPIRITOFTHEMANUALCOLUMNMATCHINGVERYWELL SAYING
#HAPTERçç
-ULTITABLEç1UERIESç*OINS ç
h'ENERATEQUERYRESULTSONLYFORPAIRSOFROWSWHERETHECUSTOMERNUMBER#534 INTHE /2$%23TABLEMATCHESTHECUSTOMERNUMBER#534?.5- INTHE#534/-%23TABLEv .OTICETHATTHE3%,%#4STATEMENTDOESNTSAYANYTHINGABOUTHOWTHE$"-3SHOULD EXECUTETHEQUERY4HEREISNOMENTIONOFhSTARTINGWITHORDERSvORhSTARTINGWITH CUSTOMERSv)NSTEAD THEQUERYTELLSTHE$"-3WHATTHEQUERYRESULTSSHOULDLOOKLIKEAND LEAVESITUPTOTHE$"-3TODECIDEHOWTOGENERATETHEM
0ARENT#HILDõ1UERIES
,ISTEACHSALESPERSONANDTHECITYANDREGIONWHERETHEYWORK 3%,%#4.!-% #)49 2%')/. &2/-3!,%32%03 /&&)#%3 7(%2%2%0?/&&)#%/&&)#% .!-%#)492%')/.
-ARY*ONES.EW9ORK%ASTERN 3AM#LARK.EW9ORK%ASTERN "OB3MITH#HICAGO%ASTERN 0AUL#RUZ#HICAGO%ASTERN $AN2OBERTS#HICAGO%ASTERN "ILL!DAMS!TLANTA%ASTERN 3UE3MITH,OS!NGELES7ESTERN ,ARRY&ITCH,OS!NGELES7ESTERN .ANCY!NGELLI$ENVER7ESTERN
4HE3!,%32%03CHILD TABLECONTAINS2%0?/&&)#% AFOREIGNKEYFORTHE/&&)#%3 PARENT TABLE4HISRELATIONSHIPISUSEDTOFINDTHECORRECT/&&)#%3ROWFOREACH SALESPERSON SOTHATTHECORRECTCITYANDREGIONCANBEINCLUDEDINTHEQUERYRESULTS (ERESANOTHERQUERYINVOLVINGTHESAMETWOTABLES BUTWITHTHEPARENTANDCHILDROLES REVERSED ASSHOWNIN&IGURE
0!24ç))
4HEMOSTCOMMONMULTITABLEQUERIESINVOLVETWOTABLESTHATHAVEANATURALPARENTCHILD RELATIONSHIP4HEQUERYABOUTORDERSANDCUSTOMERSINTHEPRECEDINGSECTIONISANEXAMPLE OFSUCHAQUERY%ACHORDERCHILD HASANASSOCIATEDCUSTOMERPARENT ANDEACHCUSTOMER PARENT CANHAVEMANYASSOCIATEDORDERSCHILDREN 4HEPAIRSOFROWSTHATGENERATETHE QUERYRESULTSAREPARENTCHILDROWCOMBINATIONS 9OUMAYRECALLFROM#HAPTERTHATFOREIGNKEYSANDPRIMARYKEYSCREATETHEPARENT CHILDRELATIONSHIPINA31,DATABASE4HETABLECONTAININGTHEFOREIGNKEYISTHECHILDINTHE RELATIONSHIPTHETABLEWITHTHEPRIMARYKEYISTHEPARENT4OEXERCISETHEPARENTCHILD RELATIONSHIPINAQUERY YOUSPECIFYASEARCHCONDITIONTHATCOMPARESTHEFOREIGNKEYANDTHE PRIMARYKEY(EREISANOTHEREXAMPLEOFAQUERYTHATEXERCISESAPARENTCHILDRELATIONSHIP SHOWNIN&IGURE
ç
0ARTç))ç
2ETRIEVINGç$ATA
&'/*
$
*18*4 *9$24. ,-(&+2 6/&16& 251+*/*5
&'/* %!
#*56*41 &56*41 &56*41 &56*41 ! #*56*41
%
-//)&05 &4:21*5 7*0-6, &0/&4. 2'0-6, &12'*465 201:)*4 &44:-6(, &7/47; &1(:1+*//-
!
7*4:*57/65 $
&/*5*3 &/*5*3 &/*5*3 "&/*5 &/*5+4 &/*5*3 &/*5*3 &/*5+4 &/*5*3 &/*5*3
1, ÊÇÎÊ Ê«>ÀiÌÉV
`ʵÕiÀÞÊÜÌ
ÊÌ
iÊ/&&)#%3Ê>`Ê3!,%32%03ÊÌ>LiÃ
&'/* %! -//)&05 &4:21*5 7*0-6, &0/&4. 2'0-6, &12'*465 201:)*4 &44:-6(, &7/47; &1(:1+*//-
&'/* $
*18*4 *9$24. ,-(&+2 6/&16& 251+*/*5
%
!
&/*5*3 &/*5*3 &/*5*3 "&/*5 &/*5+4 &/*5*3 &/*5*3 &/*5+4 &/*5*3 &/*5*3
7*4:*57/65 $
#*56*41 &56*41 &56*41 &56*41 ! #*56*41
1, ÊÇ{Ê Ê`vviÀiÌÊ«>ÀiÌÉV
`ʵÕiÀÞÊÜÌ
ÊÌ
iÊ/&&)#%3Ê>`Ê3!,%32%03ÊÌ>LiÃ
#HAPTERçç
-ULTITABLEç1UERIESç*OINS ç
,ISTTHEOFFICESANDTHENAMESANDTITLESOFTHEIRMANAGERS
4HE/&&)#%3CHILD TABLECONTAINS-'2 AFOREIGNKEYFORTHE3!,%32%03PARENT TABLE4HISRELATIONSHIPISUSEDTOFINDTHECORRECT3!,%32%03ROWFOREACHSALESPERSON SO THATTHECORRECTNAMEANDTITLEOFTHEMANAGERCANBEINCLUDEDINTHEQUERYRESULTS 31,DOESNOTREQUIRETHATTHEMATCHINGCOLUMNSBEINCLUDEDINTHERESULTSOFAMULTITABLE QUERY4HEYAREOFTENOMITTEDINPRACTICE ASINTHETWOPRECEDINGEXAMPLES4HATSBECAUSE PRIMARYKEYSANDFOREIGNKEYSAREOFTEN)$NUMBERSSUCHASTHEOFFICENUMBERSAND EMPLOYEENUMBERSINTHEEXAMPLES WHICHHUMANSFINDHARDTOREMEMBER WHILETHE ASSOCIATEDNAMESCITIES REGIONS NAMES TITLES AREEASIERTOUNDERSTAND)TSQUITECOMMON FOR)$NUMBERSTOBEUSEDINTHE7(%2%CLAUSETOJOINTWOTABLES ANDFORMOREDESCRIPTIVE NAMESTOBESPECIFIEDINTHE3%,%#4CLAUSETOGENERATECOLUMNSOFQUERYRESULTS
!Nõ!LTERNATIVEõ7AYõTOõ3PECIFYõ*OINS 4HESIMPLESTWAYTOSPECIFYTHETABLESTOBEJOINEDINAMULTITABLEQUERYISTONAMETHEM INACOMMA SEPARATEDLIST INTHE&2/-CLAUSEOFTHE3%,%#4STATEMENT ASSHOWNINTHE PREVIOUSEXAMPLES4HISMETHODFORSPECIFYINGJOINEDTABLESAPPEAREDINTHEEARLIEST)"- 31,IMPLEMENTATIONS)TWASINCLUDEDINTHEORIGINAL31,STANDARDANDISSUPPORTEDBY ALL31, BASEDDATABASES 3UBSEQUENTVERSIONSOFTHESTANDARDSIGNIFICANTLYEXPANDEDTHEJOINCAPABILITYAND ADDEDNEWOPTIONSTOTHE&2/-CLAUSE5SINGTHENEWERFORM THEPREVIOUSTWOQUERY EXAMPLESCOULDALSOBEWRITTENLIKETHIS ,ISTEACHSALESPERSONANDTHECITYANDREGIONWHERETHEYWORK 3%,%#4.!-% #)49 2%')/. &2/-3!,%32%03*/)./&&)#%3 /.2%0?/&&)#%/&&)#% .!-%#)492%')/.
-ARY*ONES.EW9ORK%ASTERN 3AM#LARK.EW9ORK%ASTERN "OB3MITH#HICAGO%ASTERN 0AUL#RUZ#HICAGO%ASTERN $AN2OBERTS#HICAGO%ASTERN "ILL!DAMS!TLANTA%ASTERN 3UE3MITH,OS!NGELES7ESTERN ,ARRY&ITCH,OS!NGELES7ESTERN .ANCY!NGELLI$ENVER7ESTERN
0!24ç))
3%,%#4#)49 .!-% 4)4,% &2/-/&&)#%3 3!,%32%03 7(%2%-'2%-0,?.5- #)49.!-%4)4,%
#HICAGO"OB3MITH3ALES-GR !TLANTA"ILL!DAMS3ALES2EP .EW9ORK3AM#LARK603ALES $ENVER,ARRY&ITCH3ALES-GR ,OS!NGELES,ARRY&ITCH3ALES-GR
ç
0ARTç))ç
2ETRIEVINGç$ATA
,ISTTHEOFFICESANDTHENAMESANDTITLESOFTHEIRMANAGERS 3%,%#4#)49 .!-% 4)4,% &2/-/&&)#%3*/).3!,%32%03 /.-'2%-0,?.5- #)49.!-%4)4,%
#HICAGO"OB3MITH3ALES-GR !TLANTA"ILL!DAMS3ALES2EP .EW9ORK3AM#LARK603ALES $ENVER,ARRY&ITCH3ALES-GR ,OS!NGELES,ARRY&ITCH3ALES-GR
)NSTEADOFACOMMA SEPARATEDLISTOFTABLENAMES THE&2/-CLAUSEINTHESEEXAMPLESUSES THE*/).KEYWORDTOSPECIFICALLYDESCRIBETHEJOINOPERATION!LSO THEMATCHINGCOLUMNSTO BEUSEDINTHEJOINARESPECIFIEDINTHE/.CLAUSE WHICHOCCURSATTHEENDOFTHE&2/-CLAUSE &ORTHESESIMPLEEXAMPLES THEEXPANDEDSTANDARD31,SYNTAXADDSVERYLITTLETOTHEOLDER FORMOFTHE3%,%#4STATEMENT"UTTHERANGEOFJOINSTHATCANBEEXPRESSEDUSINGTHE EXPANDEDFORMISMUCHBROADER ASDESCRIBEDINLATERSECTIONSOFTHISCHAPTER-ANYOFTHE MAJOR$"-3VENDORSAREENCOURAGINGTHEUSEOFTHISNEW*/).CLAUSEFORTHATREASON
*OINSõWITHõ2OWõ3ELECTIONõ#RITERIA 4HESEARCHCONDITIONTHATSPECIFIESTHEMATCHINGCOLUMNSINAMULTITABLEQUERYCANBE COMBINEDWITHOTHERSEARCHCONDITIONSTOFURTHERRESTRICTTHECONTENTSOFTHEQUERYRESULTS 3UPPOSEYOUWANTTORERUNTHEPRECEDINGQUERY SHOWINGONLYOFFICESWITHLARGESALESTARGETS ,ISTTHEOFFICESWITHATARGETOVER ANDTHEIRMANAGERINFORMATION 3%,%#4#)49 .!-% 4)4,% &2/-/&&)#%3 3!,%32%03 7(%2%-'2%-0,?.5- !.$4!2'%4 #)49.!-%4)4,%
#HICAGO"OB3MITH3ALES-GR ,OS!NGELES,ARRY&ITCH3ALES-GR
7ITHTHEADDITIONALSEARCHCONDITION THEROWSTHATAPPEARINTHEQUERYRESULTSAREFURTHER RESTRICTED4HEFIRSTTEST-'2%-0,?.5- SELECTSONLYPAIRSOF/&&)#%3AND3!,%32%03 ROWSTHATHAVETHEPROPERPARENTCHILDRELATIONSHIPTHESECONDTESTFURTHERSELECTSONLY THOSEPAIRSOFROWSWHERETHEOFFICETARGETISABOVE )NTHISFORMOFTHEQUERY THE MATCHINGCONDITIONFORTHEJOINANDTHESEARCHCONDITIONTHATRESTRICTSWHICHOFFICESARE SELECTEDBOTHAPPEARINTHE7(%2%CLAUSE5SINGTHENEWERSTANDARD31,SYNTAX THE MATCHINGCONDITIONAPPEARSINTHE/.CLAUSE ANDTHESEARCHCONDITIONAPPEARSINTHE7(%2% CLAUSE WHICHMAKESTHEQUERYSLIGHTLYEASIERTOUNDERSTAND
#HAPTERçç
-ULTITABLEç1UERIESç*OINS ç
,ISTTHEOFFICESWITHATARGETOVER ANDTHEIRMANAGERINFORMATION 3%,%#4#)49 .!-% 4)4,% &2/-/&&)#%3*/).3!,%32%03 /.-'2%-0,?.5- 7(%2%4!2'%4 #)49.!-%4)4,%
#HICAGO"OB3MITH3ALES-GR ,OS!NGELES,ARRY&ITCH3ALES-GR
4HE/2$%23TABLEANDTHE02/$5#43TABLEINTHESAMPLEDATABASEARERELATEDBYA COMPOSITEFOREIGNKEYPRIMARYKEYPAIR4HE-&2AND02/$5#4COLUMNSOFTHE/2$%23 TABLETOGETHERFORMAFOREIGNKEYFORTHE02/$5#43TABLE MATCHINGITS-&2?)$AND 02/$5#4?)$COLUMNS RESPECTIVELY4OJOINTHETABLESBASEDONTHISPARENTCHILD RELATIONSHIP YOUMUSTSPECIFYBOTHPAIRSOFMATCHINGCOLUMNS ASSHOWNINTHISEXAMPLE ,ISTALLTHEORDERS SHOWINGAMOUNTSANDPRODUCTDESCRIPTIONS 3%,%#4/2$%2?.5- !-/5.4 $%3#2)04)/. &2/-/2$%23 02/$5#43 7(%2%-&2-&2?)$ !.$02/$5#402/$5#4?)$ /2$%2?.5-!-/5.4$%3#2)04)/.
3IZE7IDGET 3IZE7IDGET 3IZE7IDGET 3IZE7IDGET 3IZE7IDGET 3IZE7IDGET 7IDGET!DJUSTER 7IDGET!DJUSTER
4HESEARCHCONDITIONINTHEQUERYTELLS31,THATTHERELATEDPAIRSOFROWSFROMTHE/2$%23 AND02/$5#43TABLESARETHOSEWHEREBOTHPAIRSOFMATCHINGCOLUMNSCONTAINTHESAME VALUES4HEALTERNATIVEFORMOFTHEQUERYSPECIFIESTHEMATCHINGCOLUMNSINTHESAMEWAY 3%,%#4/2$%2?.5- !-/5.4 $%3#2)04)/. &2/-/2$%23*/).02/$5#43 /.-&2-&2?)$ !.$02/$5#402/$5#4?)$
-ULTICOLUMNJOINSAREUSUALLYFOUNDINQUERIESINVOLVINGCOMPOUNDFOREIGNKEYSSUCHAS THISONE4HEREISNO31,RESTRICTIONONTHENUMBEROFCOLUMNSTHATAREINVOLVEDINTHE MATCHINGCONDITION BUTJOINSNORMALLYMIRRORTHEREAL WORLDRELATIONSHIPSBETWEENENTITIES REPRESENTEDINTHEDATABASETABLES ANDTHOSERELATIONSHIPSAREUSUALLYEMBODIEDINONEOR JUSTAFEWCOLUMNSOFTHETABLES
0!24ç))
-ULTIPLEõ-ATCHINGõ#OLUMNS
ç
0ARTç))ç
2ETRIEVINGç$ATA
.ATURALõ*OINS /FTENTHEMATCHINGCOLUMNORCOLUMNSTHATWILLBEUSEDTOJOINTWOTABLESHAVETHESAME NAMEINBOTHTABLES4HISISNTTRUEINTHESAMPLEDATABASE WHERETHEPRIMARYKEYSAND RELATEDFOREIGNKEYSHAVEBEENGIVENSLIGHTLYDIFFERENTNAMESSOTHATTHEYCANBEEASILY DISTINGUISHEDINOUREXAMPLES"UTINPRACTICE ADATABASECREATORWILLOFTENUSETHESAME NAMEFORACOLUMNTHATCONTAINSACUSTOMER)$ORANEMPLOYEENUMBERACROSSALLOFTHE TABLESTHATCONTAINSUCHDATA 3UPPOSETHATTHEMANUFACTURER)$ANDPRODUCT)$WERECALLED-&2AND02/$5#4INBOTH THE/2$%23TABLEANDTHE02/$5#43TABLEINTHESAMPLEDATABASE)FTHATWERETRUE THENTHE MOSTNATURALJOINBETWEENTHETWOTABLESWOULDBEANEQUI JOINBASEDONALLOFTHECOLUMN NAMESTHATAPPEARINBOTHTABLES3UCHAJOINIS INFACT CALLEDANATURALJOININ31,STANDARD 4HESTANDARDJOINSYNTAXALLOWSYOUTOEASILYINDICATETHATYOUWANTANATURALJOIN 3%,%#4/2$%2?.5- !-/5.4 $%3#2)04)/. &2/-/2$%23.!452!,*/).02/$5#43
4HISSTATEMENTTELLSTHE$"-3TOJOINTHE/2$%23AND02/$5#43TABLESONALLOFTHE COLUMNSTHATHAVETHESAMENAMESINBOTHTABLES)NTHISEXAMPLE THATWOULDBETHE-&2 AND02/$5#4COLUMNS 9OUCANALSOEXPLICITLYNAMETHECOLUMNSTOBEMATCHEDINTHISSITUATIONWITHTHIS ALTERNATIVEFORMOFTHEJOINSPECIFICATION 3%,%#4/2$%2?.5- !-/5.4 $%3#2)04)/. &2/-/2$%23*/).02/$5#43 53).'-&2 02/$5#4
4HECOLUMNSTOBEMATCHEDFORTHEJOINWHICHHAVETHESAMENAMEINBOTHTABLES ARE LISTED ENCLOSEDINPARENTHESES INTHE53).'CLAUSE.OTETHATTHE53).'CLAUSEISAMORE COMPACTALTERNATIVETOTHE/.CLAUSE BUTTHEPRECEDINGQUERYWOULDBECOMPLETELY EQUIVALENTTOTHISONESTILLASSUMINGTHATTHECOLUMNSHAVETHESAMENAMESINBOTHTABLES 3%,%#4/2$%2?.5- !-/5.4 $%3#2)04)/. &2/-/2$%23*/).02/$5#43 /./2$%23-&202/$5#43-&2 !.$/2$%2302/$5#402/$5#4302/$5#4
)NMANYCASES THEFORMOFTHEJOINWITHTHE53).'CLAUSEISPREFERABLETOSPECIFYINGANEXPLICIT .!452!,*/).)FTWODIFFERENTADMINISTRATORSARERESPONSIBLEFORMAINTAININGTHE/2$%23 AND02/$5#43TABLE FOREXAMPLECOMPLETELYPLAUSIBLEINALARGEPRODUCTIONDATABASE ITS POSSIBLETHATTHEYMIGHTBOTHACCIDENTALLYCHOOSETHESAMENAMEFORANEWCOLUMNTOBEADDED TOTHEIRTABLE EVENTHOUGHTHECOLUMNSHAVENOTHINGTODOWITHONEANOTHER)NTHISSITUATION THE.!452!,*/).FORMOFTHESTATEMENTWOULDPICKUPTHENEWCOLUMNSWITHMATCHING NAMESANDATTEMPTTOUSETHEMWHENJOININGTHETABLES PROBABLYRESULTINGINANERROR4HE 53).'CLAUSEINSULATESTHEQUERYFROMTHISTYPEOFACCIDENTALCONSEQUENCEOFDATABASE STRUCTURECHANGES)NADDITION THE53).'CLAUSEALLOWSYOUTOSELECTWHICHINDIVIDUALCOLUMNS AREUSEDTOJOINTHETABLES WHILETHE.!452!,*/).AUTOMATICALLYUSESALLCOLUMNSWITH MATCHINGNAMES&INALLY IFTHEREARENOMATCHINGCOLUMNNAMES AQUERYUSINGTHE.!452!, */).MIGHTRETURNA#ARTESIANPRODUCTDESCRIBEDLATERINTHISCHAPTER ORITMIGHTRETURNAN ERROR DEPENDINGONTHE$"-3HOWEVER AQUERYFORMEDWITHTHE53).'CLAUSEWILLALWAYS RETURNANERRORIFTHENAMEDCOLUMNSDONOTAPPEARINBOTHTABLES
#HAPTERçç
-ULTITABLEç1UERIESç*OINS ç
1UERIESõWITHõ4HREEõORõ-OREõ4ABLES 31,CANCOMBINEDATAFROMTHREEORMORETABLESUSINGTHESAMEBASICTECHNIQUESUSEDFOR TWO TABLEQUERIES(EREISASIMPLEEXAMPLEOFATHREE TABLEJOIN ,ISTORDERSOVER INCLUDINGTHENAMEOFTHESALESPERSONWHOTOOKTHEORDERANDTHENAMEOF THECUSTOMERWHOPLACEDIT
0!24ç))
3%,%#4/2$%2?.5- !-/5.4 #/-0!.9 .!-% &2/-/2$%23 #534/-%23 3!,%32%03 7(%2%#534#534?.5- !.$2%0%-0,?.5- !.$!-/5.4 /2$%2?.5-!-/5.4#/-0!.9.!-%
!CME-FG"ILL!DAMS #HEN!SSOCIATES.ANCY!NGELLI :ETACORP,ARRY&ITCH *03INCLAIR3AM#LARK
4HISQUERYUSESTWOFOREIGNKEYSINTHE/2$%23TABLE ASSHOWNIN&IGURE 4HE#534 COLUMNISAFOREIGNKEYFORTHE#534/-%23TABLE LINKINGEACHORDERTOTHECUSTOMERWHO PLACEDIT4HE2%0COLUMNISAFOREIGNKEYFORTHE3!,%32%03TABLE LINKINGEACHORDERTO THESALESPERSONWHOTOOKIT)NFORMALLYSPEAKING THEQUERYLINKSEACHORDERTOITSASSOCIATED CUSTOMERANDSALESPERSON 4HEALTERNATIVEFORMOFTHISQUERYSPECIFIESEACHJOINANDITSMATCHINGCOLUMNSMORE EXPLICITLY 3%,%#4/2$%2?.5- !-/5.4 #/-0!.9 .!-% &2/-/2$%23*/).#534/-%23/.#534#534?.5- */).3!,%32%03/.2%0%-0,?.5- 7(%2%!-/5.4
" ! !%&.) " !$" 8 8 8
!%&.)
#
" !$
!$!
$"
0' -345132 '/)*+
8 8 8
-..(%/4 %3710)4 6) /-5,
$
6)37)46.54
!%&.) $"
$!
" !
!#
"!
8 8 8
1, ÊÇxÊ ÊÌ
ÀiiÌ>LiÊ
$"
"!
#
ç
0ARTç))ç
2ETRIEVINGç$ATA
(EREISANOTHERTHREE TABLEQUERYTHATUSESADIFFERENTARRANGEMENTOFPARENTCHILD RELATIONSHIPS ,ISTTHEORDERSOVER SHOWINGTHENAMEOFTHECUSTOMERWHOPLACEDTHEORDERANDTHENAMEOF THESALESPERSONASSIGNEDTOTHATCUSTOMER 3%,%#4/2$%2?.5- !-/5.4 #/-0!.9 .!-% &2/-/2$%23 #534/-%23 3!,%32%03 7(%2%#534#534?.5- !.$#534?2%0%-0,?.5- !.$!-/5.4 /2$%2?.5-!-/5.4#/-0!.9.!-%
!CME-FG"ILL!DAMS #HEN!SSOCIATES0AUL#RUZ :ETACORP,ARRY&ITCH *03INCLAIR3AM#LARK
&IGURE SHOWSTHERELATIONSHIPSEXERCISEDBYTHISQUERY4HEFIRSTRELATIONSHIPAGAIN USESTHE#534COLUMNFROMTHE/2$%23TABLEASAFOREIGNKEYTOTHE#534/-%23TABLE
$%,' #! 7 7 7
$115+3&* $4,146 $.&5.)',,+
#
! $%,' ! #! 7 7 7
"
! #
.& +123/10 &-'()
#
4'15'24,32
$%,' #!
#
!
"
7 7 7
!
1, ÊÇÈÊ ÊÌ
ÀiiÌ>LiÊÊÜÌ
ÊV>ÃV>`i`Ê«>ÀiÌÉV
`ÊÀi>ÌÃ
«Ã
#HAPTERçç
-ULTITABLEç1UERIESç*OINS ç
,ISTTHEORDERSOVER SHOWINGTHENAMEOFTHECUSTOMERWHOPLACEDTHEORDER THECUSTOMERS SALESPERSON ANDTHEOFFICEWHERETHESALESPERSONWORKS 3%,%#4/2$%2?.5- !-/5.4 #/-0!.9 .!-% #)49 &2/-/2$%23 #534/-%23 3!,%32%03 /&&)#%3 7(%2%#534#534?.5- !.$#534?2%0%-0,?.5- !.$2%0?/&&)#%/&&)#% !.$!-/5.4 /2$%2?.5-!-/5.4#/-0!.9.!-%#)49
!CME-FG"ILL!DAMS!TLANTA #HEN!SSOCIATES0AUL#RUZ#HICAGO :ETACORP,ARRY&ITCH,OS!NGELES *03INCLAIR3AM#LARK.EW9ORK
&IGURE SHOWSTHEPARENTCHILDRELATIONSHIPSINTHISQUERY,OGICALLY ITEXTENDSTHE JOINSEQUENCEOFTHEPREVIOUSEXAMPLEONEMORESTEP LINKINGANORDERTOITSCUSTOMER THE CUSTOMERTOTHEIRSALESPERSON ANDTHESALESPERSONTOTHEIROFFICE
/THERõ%QUI *OINS 4HEVASTMAJORITYOFMULTITABLEQUERIESAREBASEDONPARENTCHILDRELATIONSHIPS BUT31, DOESNOTREQUIRETHATTHEMATCHINGCOLUMNSBERELATEDASAFOREIGNKEYANDPRIMARYKEY !NYPAIROFCOLUMNSFROMTWOTABLESCANSERVEASMATCHINGCOLUMNS PROVIDEDTHEYHAVE
0!24ç))
4HESECONDUSESTHE#534?2%0COLUMNFROMTHE#534/-%23TABLEASAFOREIGNKEYTOTHE 3!,%32%03TABLE)NFORMALLYSPEAKING THISQUERYLINKSEACHORDERTOITSCUSTOMER AND EACHCUSTOMERTOTHEIRSALESPERSON .OTETHATTHEORDEROFTHEJOINSINTHESEMULTITABLEQUERIESDOESNTMATTER4HE$"-3 CANJOINTHE/2$%23TABLETOTHE#534/-%23TABLE ANDTHENJOINTHERESULTTOTHE 3!,%32%03TABLE!LTERNATIVELY ITCANJOINTHE#534/-%23TABLETOTHE3!,%32%03TABLE FIRST ANDTHENJOINTHERESULTTOTHE/2$%23TABLE%ITHERWAY THERESULTSWILLBEEXACTLYTHE SAME SOTHE$"-3CANPERFORMTHEJOINSINTHEORDERTHATISMOSTEFFICIENT(OWEVER SOME OFTHEMOREADVANCEDJOINSDESCRIBEDLATERINTHISCHAPTERARESENSITIVETOTHESEQUENCEOF THEINDIVIDUALJOINS/NEOFTHEADVANTAGESOFTHENEWERSTANDARD31,JOINSYNTAXISTHATIT ALLOWSYOUTOSPECIFYTHEJOINORDERINTHESECASES )TSNOTUNCOMMONTOFINDQUERIESTHATJOINTHREEORMORETABLESINPRODUCTION31, APPLICATIONS ANDBUSINESSINTELLIGENCEQUERIESAGAINSTALARGEDATAWAREHOUSECANEASILY GROWTOINVOLVEATLEASTADOZENTABLES%VENWITHINTHECONFINESOFTHESMALL FIVE TABLE SAMPLEDATABASE ITSNOTTOOHARDTOFINDAFOUR TABLEQUERYTHATMAKESSENSE
ç
0ARTç))ç
2ETRIEVINGç$ATA
COMPARABLEDATATYPESORDATATYPESTHATCANBECONVERTEDTOCOMPATIBLETYPES 4HIS EXAMPLESHOWSAQUERYTHATUSESAPAIROFDATESASMATCHINGCOLUMNS &INDALLORDERSRECEIVEDONADAYWHENANEWSALESPERSONWASHIRED 3%,%#4/2$%2?.5- !-/5.4 /2$%2?$!4% .!-% &2/-/2$%23 3!,%32%03 7(%2%/2$%2?$!4%()2%?$!4% /2$%2?.5-!-/5.4/2$%2?$!4%.!-%
/#4 -ARY*ONES /#4 -ARY*ONES /#4 -ARY*ONES /#4 ,ARRY&ITCH /#4 ,ARRY&ITCH /#4 ,ARRY&ITCH %&.(
#
(07(3 (8#13+,'%*1 5.%05% 140*(.(4
"(45(30 %45(30 %45(30
%45(30 ! "(45(30
%&.( $! ; ; ;
%339,5'+ %6.36: %0'90*(..,
$
%.(4*3 %.(4(2 %.(4(2
! %&.( ! $! ; ; ;
#
! $
0' ,345132 '/()*
$
6(39(46.54
%&.( $!
$
!
; ; ;
1, ÊÇÇÊ ÊvÕÀÌ>LiÊ
!
#HAPTERçç
-ULTITABLEç1UERIESç*OINS ç
"#+& !
"#+& ! )++ %",0 "/3.-&0 2&,)1( ",+"/* .#,)1( "-.#&/10 .,-3%&/ "//3)1$( "2+/24 "-$3 -'&++)
1, ÊÇnÊ ÊÊÌÊÛÛ}Ê«À>ÀÞÊ>`ÊvÀi}ÊiÞÃ
4HERESULTSOFTHISQUERYCOMEFROMPAIRSOFROWSINTHE/2$%23AND3!,%32%03TABLES WHERETHE/2$%2?$!4%HAPPENSTOMATCHTHE()2%?$!4%FORTHESALESPERSON ASSHOWNIN &IGURE .EITHEROFTHESECOLUMNSISAFOREIGNKEYORAPRIMARYKEY ANDTHERELATIONSHIP BETWEENTHEPAIRSOFROWSISADMITTEDLYASTRANGEONETHEONLYTHINGTHEMATCHEDORDERS ANDSALESPEOPLEHAVEINCOMMONISTHATTHEYHAPPENTOHAVETHESAMEDATES(OWEVER 31, HAPPILYJOINSTHETABLESANYWAY -ATCHINGCOLUMNSLIKETHEONESINTHISEXAMPLEGENERATEAMANY TO MANYRELATIONSHIP BETWEENTHETWOTABLES-ANYORDERSCANSHAREASINGLESALESPERSONSHIREDATE ANDMORE THANONESALESPERSONMAYHAVEBEENHIREDONTHESAMEDATE&OREXAMPLE NOTETHATTHREE DIFFERENTORDERS AND WERERECEIVEDON/CTOBER ANDTWO DIFFERENTSALESPEOPLE,ARRY&ITCHAND-ARY*ONES WEREHIREDTHATSAMEDAY4HETHREE ORDERS EACHMATCHEDTOBOTHOFTHETWOSALESPEOPLE PRODUCESIXROWSOFQUERYRESULTS 4HISMANY TO MANYRELATIONSHIPISDIFFERENTFROMTHEONE TO MANYRELATIONSHIPCREATED BYPRIMARYKEYFOREIGNKEYMATCHINGCOLUMNS4HESITUATIONCANBESUMMARIZEDASFOLLOWS s *OINSTHATMATCHPRIMARYKEYSTOFOREIGNKEYSALWAYSCREATEONE TO MANY PARENT CHILDRELATIONSHIPS s /THERJOINSMAYALSOGENERATEONE TO MANYRELATIONSHIPSIFTHEMATCHINGCOLUMNIN ATLEASTONEOFTHETABLESHASUNIQUEVALUESFORALLROWSOFTHETABLE s )NGENERAL JOINSONARBITRARYMATCHINGCOLUMNSGENERATEMANY TO MANYRELATIONSHIPS .OTETHATTHESETHREEDIFFERENTSITUATIONSHAVENOTHINGTODOWITHHOWYOUWRITETHE 3%,%#4STATEMENTTHATEXPRESSESTHEJOIN!LLTHREETYPESOFJOINSAREWRITTENTHESAME WAYBYINCLUDINGACOMPARISONTESTFORTHEMATCHINGCOLUMNPAIRSINTHE7(%2%CLAUSEOR INTHE/.CLAUSE.ONETHELESS ITSUSEFULTOTHINKABOUTJOINSINTHISWAYTOUNDERSTANDHOW TOTURNAN%NGLISH LANGUAGEREQUESTINTOTHECORRECT3%,%#4STATEMENT
0!24ç))
!
5 5 5 5 5 5
5 5 5 5 5 5
!
ç
0ARTç))ç
2ETRIEVINGç$ATA
.ON %QUI *OINS 4HETERMJOINAPPLIESTOANYQUERYTHATCOMBINESDATAFROMTWOTABLESBYCOMPARINGTHE VALUESINAPAIROFCOLUMNSFROMTHETABLES!LTHOUGHJOINSBASEDONEQUALITYBETWEEN MATCHINGCOLUMNSEQUI JOINS AREBYFARTHEMOSTCOMMONJOINS 31,ALSOALLOWSYOUTO JOINTABLESBASEDONOTHERCOMPARISONOPERATORS(ERESANEXAMPLEWHEREAGREATER THAN COMPARISONTESTISUSEDASTHEBASISFORAJOIN ,ISTALLCOMBINATIONSOFSALESPEOPLEANDOFFICESWHERETHESALESPERSONSQUOTAISMORETHANTHATOFFICES TARGET REGARDLESSOFWHETHERTHESALESPERSONWORKSTHERE 3%,%#4.!-% 15/4! #)49 4!2'%4 &2/-3!,%32%03 /&&)#%3 7(%2%15/4!4!2'%4 .!-%15/4!#)494!2'%4
"ILL!DAMS $ENVER 3UE3MITH $ENVER ,ARRY&ITCH $ENVER
!SINALLTWO TABLEQUERIES EACHROWOFTHEQUERYRESULTSCOMESFROMAPAIROFROWS IN THISCASEFROMTHE3!,%32%03AND/&&)#%3TABLES4HESEARCHCONDITION 15/4!4!2'%4
SELECTSPAIRSOFROWSWHERETHE15/4!COLUMNFROMTHE3!,%32%03ROWEXCEEDSTHE 4!2'%4COLUMNFROMTHE/&&)#%3ROW.OTETHATTHEPAIRSOF3!,%32%03AND/&&)#%3 ROWSSELECTEDARERELATEDONLYINTHISWAYITISSPECIFICALLYNOTREQUIREDTHATTHE3!,%32%03 ROWREPRESENTSOMEONEWHOWORKSINTHEOFFICEREPRESENTEDBYTHE/&&)#%3ROW !DMITTEDLY THEEXAMPLEISABITFARFETCHED ANDITILLUSTRATESWHYJOINSBASEDONINEQUALITIES ARENOTVERYCOMMON(OWEVER THEYCANBEUSEFULINDECISION SUPPORTAPPLICATIONSAND OTHERAPPLICATIONSTHATEXPLOREMORECOMPLEXINTERRELATIONSHIPSINTHEDATABASE
31,õ#ONSIDERATIONSõFORõ-ULTITABLEõ1UERIES 4HEMULTITABLEQUERIESDESCRIBEDTHUSFARHAVENOTREQUIREDANYSPECIAL31,SYNTAXOR LANGUAGEFEATURESBEYONDTHOSEDESCRIBEDFORSINGLE TABLEQUERIES(OWEVER SOMEMULTITABLE QUERIESCANNOTBEEXPRESSEDWITHOUTSOMEADDITIONAL31,FEATURES3PECIFICALLY s 1UALIFIEDCOLUMNNAMESARESOMETIMESNEEDEDINMULTITABLEQUERIESTOELIMINATE AMBIGUOUSCOLUMNREFERENCES s !LL COLUMNSELECTIONS3%,%#4 HAVEASPECIALMEANINGFORMULTITABLEQUERIES s 3ELF JOINSCANBEUSEDTOCREATEAMULTITABLEQUERYTHATRELATESATABLETOITSELF s 4ABLEALIASESCANBEUSEDINTHE&2/-CLAUSETOSIMPLIFYQUALIFIEDCOLUMNNAMESAND TOALLOWUNAMBIGUOUSCOLUMNREFERENCESINSELF JOINS
#HAPTERçç
-ULTITABLEç1UERIESç*OINS ç
1UALIFIEDõ#OLUMNõ.AMES 4HESAMPLEDATABASEINCLUDESSEVERALINSTANCESWHERETWOTABLESCONTAINCOLUMNSWITHTHE SAMENAME4HE/&&)#%3TABLEANDTHE3!,%32%03TABLE FOREXAMPLE BOTHHAVEACOLUMN NAMED3!,%34HECOLUMNINTHE/&&)#%3TABLECONTAINSYEAR TO DATESALESFOREACHOFFICE THEONEINTHE3!,%32%03TABLECONTAINSYEAR TO DATESALESFOREACHSALESPERSON.ORMALLY THEREISNOCONFUSIONBETWEENTHETWOCOLUMNS BECAUSETHE&2/-CLAUSEDETERMINESWHICH OFTHEMISAPPROPRIATEINANYGIVENQUERY ASINTHESEEXAMPLES 3HOWTHECITIESWHERESALESEXCEEDTARGET
3HOWALLSALESPEOPLEWITHSALESOVER 3%,%#4.!-% 3!,%3 &2/-3!,%32%03 7(%2%3!,%3
(OWEVER HEREISAQUERYWHERETHEDUPLICATENAMESCAUSEAPROBLEM 3HOWTHENAME SALES ANDOFFICEFOREACHSALESPERSON 3%,%#4.!-% 3!,%3 #)49 &2/-3!,%32%03 /&&)#%3 7(%2%2%0?/&&)#%/&&)#% %RROR!MBIGUOUSCOLUMNNAME3!,%3
!LTHOUGHTHE%NGLISHDESCRIPTIONOFTHEQUERYIMPLIESTHATYOUWANTTHE3!,%3COLUMNIN THE3!,%32%03TABLE THE31,QUERYISAMBIGUOUS4HE$"-3HASNOWAYOFKNOWING WHETHERYOUWANTTHE3!,%3COLUMNFROMTHE3!,%32%03TABLEORTHEONEFROMTHE/&&)#%3 TABLE SINCEBOTHTABLESARECONTRIBUTINGDATATOTHEQUERYRESULTS4OELIMINATETHEAMBIGUITY YOUMUSTUSEAQUALIFIEDCOLUMNNAMETOIDENTIFYTHECOLUMN2ECALLFROM#HAPTERTHATA QUALIFIEDCOLUMNNAMESPECIFIESTHENAMEOFACOLUMNANDTHETABLECONTAININGTHECOLUMN 4HEQUALIFIEDNAMESOFTHETWO3!,%3COLUMNSINTHESAMPLEDATABASEARE /&&)#%33!,%3AND3!,%32%033!,%3
!QUALIFIEDCOLUMNNAMECANBEUSEDINA3%,%#4STATEMENTANYWHERETHATACOLUMN NAMEISPERMITTED4HETABLESPECIFIEDINTHEQUALIFIEDCOLUMNNAMEMUST OFCOURSE MATCHONEOFTHETABLESSPECIFIEDINTHE&2/-LIST(EREISACORRECTEDVERSIONOFTHEPREVIOUS QUERYTHATUSESAQUALIFIEDCOLUMNNAME
0!24ç))
3%,%#4#)49 3!,%3 &2/-/&&)#%3 7(%2%3!,%34!2'%4
ç
0ARTç))ç
2ETRIEVINGç$ATA
3HOWTHENAME SALES ANDOFFICEFOREACHSALESPERSON 3%,%#4.!-% 3!,%32%033!,%3 #)49 &2/-3!,%32%03 /&&)#%3 7(%2%2%0?/&&)#%/&&)#% .!-%3!,%32%033!,%3#)49
-ARY*ONES .EW9ORK 3AM#LARK .EW9ORK "OB3MITH #HICAGO 0AUL#RUZ #HICAGO $AN2OBERTS #HICAGO "ILL!DAMS !TLANTA 3UE3MITH ,OS!NGELES ,ARRY&ITCH ,OS!NGELES .ANCY!NGELLI $ENVER
5SINGQUALIFIEDCOLUMNNAMESINAMULTITABLEQUERYISALWAYSAGOODIDEA4HEDISADVANTAGE OFCOURSE ISTHATTHEYMAKETHEQUERYTEXTLONGER7HENUSINGINTERACTIVE31, YOUMAYWANT TOFIRSTTRYAQUERYWITHUNQUALIFIEDCOLUMNNAMESANDLET31,FINDANYAMBIGUOUSCOLUMNS )F31,REPORTSANERROR YOUCANEDITYOURQUERYTOQUALIFYTHEAMBIGUOUSCOLUMNS
!LL #OLUMNõ3ELECTIONS !SDISCUSSEDIN#HAPTER 3%,%#4 CANBEUSEDTOSELECTALLCOLUMNSOFTHETABLENAMEDIN THE&2/-CLAUSE)NAMULTITABLEQUERY THEASTERISKSELECTSALLCOLUMNSOFALLTABLESINTHE&2/- CLAUSE4HEFOLLOWINGQUERY FOREXAMPLE WOULDPRODUCECOLUMNSOFQUERYRESULTSTHE NINECOLUMNSFROMTHE3!,%32%03TABLEFOLLOWEDBYTHESIXCOLUMNSFROMTHE/&&)#%3TABLE 4ELLMEALLABOUTSALESPEOPLEANDTHEOFFICESWHERETHEYWORK 3%,%#4 &2/-3!,%32%03 /&&)#%3 7(%2%2%0?/&&)#%/&&)#%
/BVIOUSLY THE3%,%#4 FORMOFAQUERYBECOMESMUCHLESSPRACTICALWHENTHEREARE TWO THREE ORMORETABLESINTHE&2/-CLAUSE -ANY31,DIALECTSTREATTHEASTERISKASASPECIALKINDOFWILDCARDCOLUMNNAMETHATIS EXPANDEDINTOALISTOFCOLUMNS)NTHESEDIALECTS THEASTERISKCANBEQUALIFIEDWITHATABLENAME JUSTLIKEAQUALIFIEDCOLUMNREFERENCE)NTHEFOLLOWINGQUERY THESELECTITEM3!,%32%03 IS EXPANDEDINTOALISTCONTAININGONLYTHECOLUMNSFOUNDINTHE3!,%32%03TABLE 4ELLMEALLABOUTSALESPEOPLEANDTHEPLACESWHERETHEYWORK 3%,%#43!,%32%03 #)49 2%')/. &2/-3!,%32%03 /&&)#%3 7(%2%2%0?/&&)#%/&&)#%
#HAPTERçç
-ULTITABLEç1UERIESç*OINS ç
4HEQUERYWOULDPRODUCECOLUMNSOFQUERYRESULTSTHENINECOLUMNSOFTHE3!,%32%03 TABLE FOLLOWEDBYTHETWOOTHERCOLUMNSEXPLICITLYREQUESTEDFROMTHE/&&)#%3TABLE4HIS TYPEOFhQUALIFIEDALL COLUMNSvSELECTITEMWASINTRODUCEDINTHE31,VERSIONOFTHE!.3))3/ STANDARD)TISSUPPORTEDINTHEMAINSTREAM31,PRODUCTS BUTNOTINSOMELOW ENDSYSTEMS
3ELF *OINS
3%,%#4.!-% .!-% &2/-3!,%32%03 3!,%32%03 7(%2%-!.!'%2%-0,?.5-
4HIS3%,%#4STATEMENTISILLEGALBECAUSEOFTHEDUPLICATEREFERENCETOTHE3!,%32%03 TABLEINTHE&2/-CLAUSE9OUMIGHTALSOTRYELIMINATINGTHESECONDREFERENCETOTHE 3!,%32%03TABLE 3%,%#4.!-% .!-% &2/-3!,%32%03 7(%2%-!.!'%2%-0,?.5-
4HISQUERYISLEGAL BUTITWONTDOWHATYOUWANTITTODO)TSASINGLE TABLEQUERY SO 31,GOESTHROUGHTHE3!,%32%03TABLEONEROWATATIME APPLYINGTHESEARCHCONDITION -!.!'%2%-0,?.5-
4HEROWSTHATSATISFYTHISCONDITIONARETHOSEWHERETHETWOCOLUMNSHAVETHESAME VALUETHATIS ROWSWHEREASALESPERSONISTHEIROWNMANAGER4HEREARENOSUCHROWS SO THEQUERYWOULDPRODUCENORESULTSWHICHISQUITEDIFFERENTFROMTHEDATATHATTHE %NGLISH LANGUAGESTATEMENTOFTHEQUERYREQUESTED 4OUNDERSTANDHOW31,SOLVESTHISPROBLEM IMAGINETHEREWERETWOIDENTICALCOPIESOF THE3!,%32%03TABLE ONENAMED%-03 CONTAININGEMPLOYEES ANDONENAMED-'23 CONTAININGMANAGERS ASSHOWNIN&IGURE 4HE-!.!'%2COLUMNOFTHE%-03TABLE WOULDTHENBEAFOREIGNKEYFORTHE-'23TABLE ANDTHEFOLLOWINGQUERYWOULDWORK ,ISTTHENAMESOFSALESPEOPLEANDTHEIRMANAGERS 3%,%#4%-03.!-% -'23.!-% &2/-%-03 -'23 7(%2%%-03-!.!'%2-'23%-0,?.5-
"ECAUSETHECOLUMNSINTHETWOTABLESHAVEIDENTICALNAMES ALLOFTHECOLUMNREFERENCES AREQUALIFIED/THERWISE THISLOOKSLIKEANORDINARYTWO TABLEQUERY
0!24ç))
3OMEMULTITABLEQUERIESINVOLVEARELATIONSHIPTHATATABLEHASWITHITSELF&OREXAMPLE SUPPOSEYOUWANTTOLISTTHENAMESOFALLSALESPEOPLEANDTHEIRMANAGERS%ACHSALESPERSON APPEARSASAROWINTHE3!,%32%03TABLE ANDTHE-!.!'%2COLUMNCONTAINSTHEEMPLOYEE NUMBEROFTHESALESPERSONSMANAGER)TWOULDAPPEARTHATTHE-!.!'%2COLUMNSHOULDBE AFOREIGNKEYFORTHETABLETHATHOLDSDATAABOUTMANAGERS)NFACTITISITSAFOREIGNKEYFOR THE3!,%32%03TABLEITSELF )FYOUTRIEDTOEXPRESSTHISQUERYLIKEANYOTHERTWO TABLEQUERYINVOLVINGAFOREIGN KEYPRIMARYKEYMATCH ITWOULDLOOKLIKETHIS
ç
0ARTç))ç
2ETRIEVINGç$ATA
'2382* %&/) $! $
'2382* %&/) $! $
-//(%05 %4821)5 7)0-6, %0/%4. 2&0-6, %12&)465 2018()4 %448-6', %7/479 %1'81+)//-
!
%/)5)3 %/)5)3 %/)5)3 "%/)5 %/)5+4 %/)5)3 %/)5)3 %/)5+4 %/)5)3 %/)5)3
-//(%05 %4821)5 7)0-6, %0/%4. 2&0-6, %12&)465 2018()4 %448-6', %7/479 %1'81+)//-
$
!
# "
!
!
1, ÊÇÊ ÊÃivÊvÊÌ
iÊ3!,%32%03ÊÌ>Li
31,USESEXACTLYTHIShIMAGINARYDUPLICATETABLEvAPPROACHTOJOINATABLETOITSELF )NSTEADOFACTUALLYDUPLICATINGTHECONTENTSOFTHETABLE 31,LETSYOUSIMPLYREFERTOITBY ADIFFERENTNAME CALLEDATABLEALIAS(ERESTHESAMEQUERY WRITTENUSINGTHEALIASES%-03 AND-'23FORTHE3!,%32%03TABLE ,ISTTHENAMESOFSALESPEOPLEANDTHEIRMANAGERS 3%,%#4%-03.!-% -'23.!-% &2/-3!,%32%03%-03 3!,%32%03-'23 7(%2%%-03-!.!'%2-'23%-0,?.5- %-03.!-%-'23.!-%
4OM3NYDER$AN2OBERTS "ILL!DAMS"OB3MITH $AN2OBERTS"OB3MITH 0AUL#RUZ"OB3MITH -ARY*ONES3AM#LARK "OB3MITH3AM#LARK ,ARRY&ITCH3AM#LARK 3UE3MITH,ARRY&ITCH .ANCY!NGELLI,ARRY&ITCH
#HAPTERçç
-ULTITABLEç1UERIESç*OINS ç
4HE&2/-CLAUSEASSIGNSADIFFERENTALIASTOEACHOFTHETWOhVIRTUALCOPIESvOFTHE 3!,%32%03TABLETHATAREINVOLVEDINTHEQUERYBYSPECIFYINGTHEALIASNAMEIMMEDIATELY AFTERTHEACTUALTABLENAME!STHEEXAMPLESHOWS WHENA&2/-CLAUSECONTAINSATABLE ALIAS THEALIASMUSTBEUSEDTOIDENTIFYTHETABLEINQUALIFIEDCOLUMNREFERENCES/FCOURSE ITSREALLYONLYNECESSARYTOUSEANALIASFORONEOFTHETWOTABLEOCCURRENCESINTHISQUERY)T COULDJUSTASEASILYHAVEBEENWRITTEN 3%,%#43!,%32%03.!-% -'23.!-% &2/-3!,%32%03 3!,%32%03-'23 7(%2%3!,%32%03-!.!'%2-'23%-0,?.5-
,ISTSALESPEOPLEWITHAHIGHERQUOTATHANTHEIRMANAGER 3%,%#43!,%32%03.!-% 3!,%32%0315/4! -'2315/4! &2/-3!,%32%03 3!,%32%03-'23 7(%2%3!,%32%03-!.!'%2-'23%-0,?.5- !.$3!,%32%0315/4!-'2315/4! 3!,%32%03.!-%3!,%32%0315/4!-'2315/4!
"ILL!DAMS $AN2OBERTS 0AUL#RUZ -ARY*ONES ,ARRY&ITCH
,ISTSALESPEOPLEWHOWORKINDIFFERENTOFFICESTHANTHEIRMANAGER SHOWINGTHENAMEANDOFFICEWHERE EACHWORKS 3%,%#4%-03.!-% %-0?/&&)#%#)49 -'23.!-% -'2?/&&)#%#)49 &2/-3!,%32%03%-03 3!,%32%03-'23 /&&)#%3%-0?/&&)#% /&&)#%3-'2?/&&)#% 7(%2%%-032%0?/&&)#%%-0?/&&)#%/&&)#% !.$-'232%0?/&&)#%-'2?/&&)#%/&&)#% !.$%-03-!.!'%2-'23%-0,?.5- !.$%-032%0?/&&)#%-'232%0?/&&)#% %-03.!-%%-0?/&&)#%#)49-'23.!-%-'2?/&&)#%#)49
"OB3MITH#HICAGO3AM#LARK.EW9ORK "ILL!DAMS!TLANTA"OB3MITH#HICAGO ,ARRY&ITCH,OS!NGELES3AM#LARK.EW9ORK .ANCY!NGELLI$ENVER,ARRY&ITCH,OS!NGELES
4ABLEõ!LIASES !SDESCRIBEDINTHEPREVIOUSSECTION TABLEALIASESAREREQUIREDINQUERIESINVOLVINGSELF JOINS (OWEVER YOUCANUSEANALIASINANYQUERY&OREXAMPLE IFAQUERYREFERSTOANOTHERUSERS TABLE ORIFTHENAMEOFATABLEISVERYLONG THETABLENAMECANBECOMETEDIOUSTOTYPEASA
0!24ç))
(ERETHEALIAS-'23ISASSIGNEDTOONEhVIRTUALCOPYvOFTHETABLE WHILETHETABLESOWN NAMEISUSEDFORTHEOTHERCOPY (EREARESOMEADDITIONALEXAMPLESOFSELF JOINS
ç
0ARTç))ç
2ETRIEVINGç$ATA
COLUMNQUALIFIER4HISQUERY WHICHREFERENCESTHE")24($!93TABLEOWNEDBYTHEUSER NAMED3!- ,ISTNAMES QUOTAS ANDBIRTHDAYSOFSALESPEOPLE 3%,%#43!,%32%03.!-% 15/4! 3!-")24($!93")24(?$!4% &2/-3!,%32%03 3!-")24($!93 7(%2%3!,%32%03.!-%3!-")24($!93.!-%
BECOMESEASIERTOREADANDTYPEWHENTHEALIASES3AND"AREUSEDFORTHETWOTABLES ,ISTNAMES QUOTAS ANDBIRTHDAYSOFSALESPEOPLE 3%,%#43.!-% 315/4! "")24(?$!4% &2/-3!,%32%033 3!-")24($!93" 7(%2%3.!-%".!-%
&IGURE SHOWSTHEBASICFORMOFTHE&2/-CLAUSEFORAMULTITABLE3%,%#4STATEMENT COMPLETEWITHTABLEALIASES4HECLAUSEHASTWOIMPORTANTFUNCTIONS s 4HE&2/-CLAUSEIDENTIFIESALLOFTHETABLESTHATCONTRIBUTEDATATOTHEQUERYRESULTS !NYCOLUMNSREFERENCEDINTHE3%,%#4STATEMENTMUSTCOMEFROMONEOFTHETABLES NAMEDINTHE&2/-CLAUSE4HEREISANEXCEPTIONFOROUTERREFERENCESCONTAINEDINA SUBQUERY ASDESCRIBEDIN#HAPTER s 4HE&2/-CLAUSESPECIFIESTHETAGTHATISUSEDTOIDENTIFYTHETABLEINQUALIFIED COLUMNREFERENCESWITHINTHE3%,%#4STATEMENT)FATABLEALIASISSPECIFIED IT BECOMESTHETABLETAGOTHERWISE THETABLESNAME EXACTLYASITAPPEARSINTHE&2/- CLAUSE BECOMESTHETAG 4HEONLYREQUIREMENTFORTABLETAGSINTHE&2/-CLAUSEISTHATALLOFTHETABLETAGSINA GIVEN&2/-CLAUSEMUSTBEDISTINCTFROMEACHOTHER%VENIFYOUDONTUSETABLEALIASESIN 31,QUERIESTHATYOUWRITE YOUARELIKELYTOENCOUNTERTHEMIFYOUEXAMINETHE31, GENERATEDBYREPORT WRITINGORBUSINESSANALYSISTOOLS4HESETOOLSTYPICALLYPRESENTA GRAPHICALINTERFACETHATALLOWSYOUTOEASILYCHOOSETHECOLUMNS TABLES MATCHINGCOLUMNS SEARCHCONDITIONS ANDOTHERELEMENTSOFYOURQUERY ANDTHEYAUTOMATICALLYGENERATETHE CORRESPONDING31,STATEMENTSTHATAREPASSEDTOTHE$"-34HETOOLWILLALMOSTALWAYSUSE TABLETAGSTYPICALLYUSINGTAGSLIKE4 4 4 ETC INTHE&2/-CLAUSEOFTHEGENERATED31, ALLOWINGITTOEASILYANDUNAMBIGUOUSLYSPECIFYTHERESTOFTHEQUERY REGARDLESSOFTHE ACTUALNAMESOFTHETABLES COLUMNS ANDOTHERDATABASEELEMENTS 4HE31,STANDARDOPTIONALLYALLOWSTHEKEYWORD!3TOAPPEARBETWEENATABLENAME ANDTABLEALIAS)TALSOUSESTHETERMCORRELATIONNAMETOREFERTOWHATWEHAVECALLEDA TABLEALIAS4HEFUNCTIONANDMEANINGOFACORRELATIONNAMEAREEXACTLYASDESCRIBEDHERE
1, ÊÇ£äÊ /
iÊ&2/-ÊV>ÕÃiÊÃÞÌ>ÝÊ`>}À>
#HAPTERçç
-ULTITABLEç1UERIESç*OINS ç
MANY31,PRODUCTSUSETHETERMALIAS ANDITISMOREDESCRIPTIVEOFTHEFUNCTIONTHATA TABLEALIASPERFORMS4HE31,STANDARDSPECIFIESASIMILARTECHNIQUEFORDESIGNATING ALTERNATECOLUMNNAMES ANDINTHATSITUATIONTHECOLUMNALIASNAMEISACTUALLYCALLEDAN ALIASINTHESTANDARD
-ULTITABLEõ1UERYõ0ERFORMANCE
s 4HEUSERENTERSACUSTOMERNUMBERINTOAFORM ANDTHE$"-3RETRIEVESTHE CUSTOMERSCREDITLIMIT ACCOUNTBALANCE ANDOTHERDATAASINGLE TABLEQUERY s !CASHREGISTERSCANSAPRODUCTNUMBERFROMAPACKAGEANDRETRIEVESTHEPRODUCTS NAMEANDPRICEFROMTHEDATABASEASINGLE TABLEQUERY s 4HEUSERENTERSASALESPERSONSNAME ANDTHEPROGRAMLISTSTHECURRENTORDERSFOR THATSALESPERSONATWO TABLEINQUIRY )NDECISION SUPPORTAPPLICATIONS BYCONTRAST ITSCOMMONFORAQUERYTOINVOLVEMANY DIFFERENTTABLESANDTOEXERCISECOMPLEXRELATIONSHIPSINTHEDATABASE)NTHESEAPPLICATIONS THEQUERYRESULTSAREOFTENUSEDTOHELPMAKEEXPENSIVEDECISIONS SOAQUERYTHATREQUIRES SEVERALMINUTESOREVENMANYHOURSTOCOMPLETEISPERFECTLYACCEPTABLE(EREARESOME TYPICALDECISION SUPPORTQUERIESFORTHESAMPLEDATABASE s 4HEUSERENTERSANOFFICENAME ANDTHEPROGRAMLISTSTHELARGESTORDERSTAKENBY SALESPEOPLEINTHATOFFICEATHREE TABLEQUERY s !REPORTSUMMARIZESSALESBYPRODUCTTYPEFOREACHSALESPERSON SHOWINGWHICH SALESPEOPLEARESELLINGWHICHPRODUCTSATHREE TABLEQUERY s !MANAGERCONSIDERSOPENINGANEW3EATTLESALESOFFICEANDRUNSAQUERYANALYZING THEIMPACTONORDERS PRODUCTS CUSTOMERS ANDTHESALESPEOPLEWHOCALLONTHEM AFOUR TABLEQUERY )NTHESMALLTABLESOFTHESAMPLEDATABASE EVENTHESEQUERIESWOULDREQUIREONLYSECONDSTO COMPLETEONLOW COSTCOMPUTERHARDWARE"UTIFTHETABLESCONTAINEDTENSOFMILLIONSOF ROWS THETIMETOEXECUTETHEQUERIESWOULDLIKELYBEMUCHLONGER4HEPERFORMANCEOF MULTITABLEJOINSCANBEHIGHLYDEPENDENTONTHEINDEXSTRUCTURESANDOTHERINTERNALDATA STRUCTURESTHATTHE$"-3USESTOORGANIZETHEDATATHATITSTORES)NGENERAL QUERIESTHAT EXERCISEPRIMARYFOREIGNKEYRELATIONSHIPSWILLPERFORMFAIRLYWELL BECAUSETHE$"-3 TENDSTOOPTIMIZEFORTHOSE
0!24ç))
!STHENUMBEROFTABLESINAQUERYGROWS THEAMOUNTOFEFFORTREQUIREDTOCARRYOUTTHEQUERY INCREASESRAPIDLY4HE31,ITSELFPLACESNOLIMITONTHENUMBEROFTABLESJOINEDBYAQUERY 3OMELOW ENDANDEMBEDDED31,PRODUCTSDOLIMITTHENUMBEROFTABLES WITHALIMITOF ABOUTEIGHTTABLESBEINGFAIRLYCOMMON4HEHIGHPROCESSINGCOSTOFQUERIESTHATJOINMANY TABLESIMPOSESANEVENLOWERPRACTICALLIMITINMANYAPPLICATIONS )NONLINETRANSACTIONPROCESSING/,40 APPLICATIONS ITSCOMMONFORAQUERYTOINVOLVE ONLYONEORTWOTABLES)NTHESEAPPLICATIONS RESPONSETIMEISCRITICALTHEUSERTYPICALLY ENTERSONEORTWOITEMSOFDATAANDNEEDSARESPONSEFROMTHEDATABASEWITHINASECONDOR TWO(EREARESOMETYPICAL/,40QUERIESFORTHESAMPLEDATABASE
ç
0ARTç))ç
2ETRIEVINGç$ATA
4HEõ3TRUCTUREõOFõAõ*OIN &ORSIMPLEJOINS ITSFAIRLYEASYTOWRITETHECORRECT3%,%#4STATEMENTBASEDONAN%NGLISH LANGUAGEREQUESTORTOLOOKATA3%,%#4STATEMENTANDFIGUREOUTWHATITDOES7HENMANY TABLESAREJOINEDORWHENTHESEARCHCONDITIONSBECOMECOMPLEX HOWEVER ITBECOMESVERY DIFFICULTJUSTTOLOOKATA3%,%#4STATEMENTANDFIGUREOUTWHATITMEANS&ORTHISREASON ITSIMPORTANTTODEFINEMORECAREFULLYANDJUSTABITMOREFORMALLYWHATAJOINIS WHAT QUERYRESULTSAREPRODUCEDBYAGIVEN3%,%#4STATEMENT ANDTOUNDERSTANDJUSTALITTLEBIT OFTHETHEORYOFRELATIONALDATABASEOPERATIONTHATUNDERLIESJOINS
4ABLEõ-ULTIPLICATION !JOINISASPECIALCASEOFAMOREGENERALCOMBINATIONOFDATAFROMTWOTABLES KNOWNASTHE #ARTESIANPRODUCTORJUSTTHEPRODUCT OFTWOTABLES4HEPRODUCTOFTWOTABLESISANOTHERTABLE THEPRODUCTTABLE WHICHCONSISTSOFALLPOSSIBLEPAIRSOFROWSFROMTHETWOTABLES4HE COLUMNSOFTHEPRODUCTTABLEAREALLTHECOLUMNSOFTHEFIRSTTABLE FOLLOWEDBYALLTHE COLUMNSOFTHESECONDTABLE&IGURE SHOWSTWOSMALLSAMPLETABLESANDTHEIRPRODUCT )FYOUSPECIFYATWO TABLEQUERYWITHOUTA7(%2%CLAUSE 31,PRODUCESTHEPRODUCTOF THETWOTABLESASTHEQUERYRESULT&OREXAMPLE THISQUERY 3HOWALLPOSSIBLECOMBINATIONSOFSALESPEOPLEANDCITIES 3%,%#4.!-% #)49 &2/-3!,%32%03 /&&)#%3
WOULDPRODUCETHEPRODUCTOFTHE3!,%32%03AND/&&)#%3TABLES SHOWINGALLPOSSIBLE SALESPERSONCITYPAIRS4HEREWOULDBEROWSOFQUERYRESULTSOFFICES¾SALESPEOPLE COMBINATIONS .OTICETHATTHEPRECEDING3%,%#4STATEMENTISEXACTLYTHESAMEASTHE FOLLOWINGONEYOUWOULDNATURALLYUSETOJOINTHETWOTABLES BUTWITHOUTTHESPECIFICATION OFTHEMATCHINGCOLUMNS 3HOWALLSALESPEOPLEANDTHECITIESWHERETHEYWORK 3%,%#4.!-% #)49 &2/-3!,%32%03*/)./&&)#%3 /.2%0?/&&)#%/&&)#%
!
$ #! ""$
$!
!
#"
!"
#"
!
1, ÊÇ££Ê /
iÊ«À`ÕVÌÊvÊÌÜÊÌ>LiÃ
$ #! ""$ $ #! ""$
!" !"
!
!
!
! ! !
#HAPTERçç
-ULTITABLEç1UERIESç*OINS ç
4HESETWOQUERIESPOINTOUTANIMPORTANTRELATIONSHIPBETWEENJOINSANDPRODUCTS !JOINBETWEENTWOTABLESISJUSTTHEPRODUCTOFTHETWOTABLESWITHSOMEOFTHEROWSREMOVED 4HEREMOVEDROWSAREPRECISELYTHOSETHATDONOTMEETTHEMATCHINGCOLUMNCONDITIONFOR THEJOIN0RODUCTSAREIMPORTANTBECAUSETHEYAREPARTOFTHEFORMALDEFINITIONOFHOW31, PROCESSESAMULTITABLEQUERY DESCRIBEDINTHENEXTSECTION
2ULESõFORõ-ULTITABLEõ1UERYõ0ROCESSING
,ISTTHECOMPANYNAMEANDALLORDERSFORCUSTOMERNUMBER 3%,%#4#/-0!.9 /2$%2?.5- !-/5.4 &2/-#534/-%23*/)./2$%23 /.#534?.5-#534 7(%2%#534?.5- /2$%2"9/2$%2?.5- #/-0!.9/2$%2?.5-!-/5.4
!CME-FG !CME-FG !CME-FG !CME-FG
4OGENERATETHEQUERYRESULTSFORA3%,%#4STATEMENT
)FTHESTATEMENTISA5.)/.OF3%,%#4STATEMENTS APPLY3TEPSTHROUGHTOEACH OFTHESTATEMENTSTOGENERATETHEIRINDIVIDUALQUERYRESULTS
&ORMTHEPRODUCTOFTHETABLESNAMEDINTHE&2/-CLAUSE)FTHE&2/-CLAUSENAMES ASINGLETABLE THEPRODUCTISTHATTABLE
)FTHEREISAN/.CLAUSE APPLYITSMATCHING COLUMNCONDITIONTOEACHROWOFTHE PRODUCTTABLE RETAININGTHOSEROWSFORWHICHTHECONDITIONIS425%ANDDISCARDING THOSEFORWHICHITIS&!,3%OR.5,,
)FTHEREISA7(%2%CLAUSE APPLYITSSEARCHCONDITIONTOEACHROWOFTHERESULTING TABLE RETAININGTHOSEROWSFORWHICHTHESEARCHCONDITIONIS425%ANDDISCARDING THOSEFORWHICHITIS&!,3%OR.5,,
&OREACHREMAININGROW CALCULATETHEVALUEOFEACHITEMINTHESELECTLISTTOPRODUCE ASINGLEROWOFQUERYRESULTS&OREACHCOLUMNREFERENCE USETHEVALUEOFTHE COLUMNINTHECURRENTROW
)F3%,%#4$)34).#4ISSPECIFIED ELIMINATEANYDUPLICATEROWSOFQUERYRESULTS THATWEREPRODUCED
0!24ç))
4HESTEPSAFTERTHECODETHATFOLLOWSRESTATETHERULESFOR31,QUERYPROCESSINGORIGINALLY INTRODUCEDINTHE2ULESFOR3INGLE 4ABLE1UERY0ROCESSINGTOPICIN#HAPTERANDEXPANDS THEMTOINCLUDEMULTITABLEQUERIES4HERULESDEFINETHEMEANINGOFANYMULTITABLE3%,%#4 STATEMENTBYSPECIFYINGAPROCEDURETHATALWAYSGENERATESTHECORRECTSETOFQUERYRESULTS 4OSEEHOWTHEPROCEDUREWORKS CONSIDERTHISQUERY
ç
0ARTç))ç
2ETRIEVINGç$ATA
)FTHESTATEMENTISA5.)/.OF3%,%#4STATEMENTS MERGETHEQUERYRESULTSFORTHE INDIVIDUALSTATEMENTSINTOASINGLETABLEOFQUERYRESULTS%LIMINATEDUPLICATEROWS UNLESS5.)/.!,,ISSPECIFIED
)FTHEREISAN/2$%2"9CLAUSE SORTTHEQUERYRESULTSASSPECIFIED 4HEROWSGENERATEDBYTHISPROCEDURECOMPRISETHEQUERYRESULTS &OLLOWINGTHEPREVIOUSSTEPS
4HE&2/-CLAUSEGENERATESALLPOSSIBLECOMBINATIONSOFROWSFROMTHE#534/-%23 TABLEROWS ANDTHE/2$%23TABLEROWS PRODUCINGAPRODUCTTABLEOF ROWS
4HE/.CLAUSESELECTSONLYTHOSEROWSOFTHEPRODUCTTABLEWHERETHECUSTOMERNUMBERS MATCH#534?.5-#534 REDUCINGTHEROWSTOONLYONEFOREACHORDER
4HE7(%2%CLAUSESELECTSONLYTHOSEROWSOFTHERESULTINGTABLEWHERETHECUSTOMER NUMBERISTHEONESPECIFIED#534?.5- /NLYFOURROWSARESELECTEDTHE OTHERROWSAREELIMINATED
4HE3%,%#4CLAUSEEXTRACTSTHETHREEREQUESTEDCOLUMNS#/-0!.9 /2$%2? .5- AND!-/5.4 FROMEACHREMAININGROWOFTHERESULTINGTABLETOGENERATEFOUR ROWSOFDETAILEDQUERYRESULTS
4HE/2$%2"9CLAUSESORTSTHEFOURROWSONTHE/2$%2?.5-COLUMNTOGENERATETHE FINALQUERYRESULTS
/BVIOUSLYNO31, BASED$"-3WOULDACTUALLYCARRYOUTTHEQUERYTHISWAY BUTTHE PURPOSEOFTHEPREVIOUSDEFINITIONISNOTTODESCRIBEHOWTHEQUERYISCARRIEDOUTBYA $"-3)NSTEAD ITCONSTITUTESADEFINITIONOFHOWTOFIGUREOUTEXACTLYWHATAPARTICULAR MULTITABLEQUERYhMEANSvTHATIS THESETOFQUERYRESULTSTHATITSHOULDPRODUCE
/UTERõ*OINS 4HE31,JOINOPERATIONCOMBINESINFORMATIONFROMTWOTABLESBYFORMINGPAIRSOFRELATED ROWSFROMTHETWOTABLESWHERETHEMATCHINGCOLUMNSINEACHOFTHETABLESHAVETHESAME VALUES)FONEOFTHEROWSOFATABLEISUNMATCHEDINTHISPROCESS THEJOINCANPRODUCE UNEXPECTEDRESULTS ASILLUSTRATEDBYTHESEQUERIES ,ISTTHESALESPEOPLEANDTHEOFFICESWHERETHEYWORK 3%,%#4.!-% 2%0?/&&)#% &2/-3!,%32%03 .!-%2%0?/&&)#%
"ILL!DAMS -ARY*ONES 3UE3MITH 3AM#LARK "OB3MITH $AN2OBERTS 4OM3NYDER.5,,
#HAPTERçç
-ULTITABLEç1UERIESç*OINS ç
,ARRY&ITCH 0AUL#RUZ .ANCY!NGELLI
2ECALLTHATNOTALL31,TOOLSDISPLAY.5,,VALUESINTHEMANNERSHOWN ,ISTTHESALESPEOPLEANDTHECITIESWHERETHEYWORK
"ASEDONTHE%NGLISH LANGUAGEDESCRIPTIONSOFTHESETWOQUERIES YOUWOULDPROBABLY EXPECTTHEMTOPRODUCETENROWS ONEFOREACHSALESPERSON4HEFIRSTQUERYINDEEDPRODUCES TENROWS BUTTHESECONDQUERYPRODUCESONLYNINEROWS7HY"ECAUSE4OM3NYDERIS CURRENTLYNOTASSIGNEDTOANOFFICE(ISROWHASA.5,,VALUEINTHE2%0?/&&)#%COLUMN WHICHISTHEMATCHINGCOLUMNFORTHEJOIN 4HIS.5,,VALUEDOESNTMATCHANYOFTHEOFFICE NUMBERSINTHE/&&)#%3TABLE SO4OMSROWINTHE3!,%32%03TABLEISUNMATCHED!SA RESULT IThVANISHESvINTHEJOIN WHETHERTHEJOINISSPECIFIEDUSINGTHE/.CLAUSEORTHE 7(%2%CLAUSE4HESTANDARD31,JOINTHUSHASTHEPOTENTIALTOLOSEINFORMATIONIFTHETABLES BEINGJOINEDCONTAINUNMATCHEDROWS "ASEDONTHE%NGLISH LANGUAGEVERSIONOFTHEREQUEST YOUWOULDPROBABLYEXPECTTHE SECONDQUERYTOPRODUCERESULTSLIKETHESE ,ISTTHESALESPEOPLEANDTHECITIESWHERETHEYWORK 3%,%#4.!-% #)49 &2/-3!,%32%03,%&4/54%2*/)./&&)#%3 /.2%0?/&&)#%/&&)#% .!-%#)49
4OM3NYDER.5,, -ARY*ONES.EW9ORK 3AM#LARK.EW9ORK "OB3MITH#HICAGO 0AUL#RUZ#HICAGO $AN2OBERTS#HICAGO "ILL!DAMS!TLANTA 3UE3MITH,OS!NGELES ,ARRY&ITCH,OS!NGELES .ANCY!NGELLI$ENVER
0!24ç))
3%,%#4.!-% #)49 &2/-3!,%32%03*/)./&&)#%3 /.2%0?/&&)#%/&&)#% .!-%#)49
-ARY*ONES.EW9ORK 3AM#LARK.EW9ORK "OB3MITH#HICAGO 0AUL#RUZ#HICAGO $AN2OBERTS#HICAGO "ILL!DAMS!TLANTA 3UE3MITH,OS!NGELES ,ARRY&ITCH,OS!NGELES .ANCY!NGELLI$ENVER
ç
0ARTç))ç
2ETRIEVINGç$ATA
4HESEQUERYRESULTSAREGENERATEDBYADIFFERENTTYPEOFJOINOPERATION CALLEDANOUTERJOIN ASINDICATEDBYTHEADDITIONALKEYWORDSINTHE&2/-CLAUSE4HEOUTERJOINISANEXTENSIONOF THESTANDARDJOINDESCRIBEDEARLIERINTHISCHAPTER WHICHISTECHNICALLYCALLEDANINNERJOIN4HE ORIGINAL31,STANDARDSPECIFIEDONLYTHEINNERJOIN ANDTHEEARLY)"-31,PRODUCTSALSO SUPPORTEDONLYTHEINNERJOIN(OWEVER THEOUTERJOINISAWELL UNDERSTOOD USEFUL AND INCREASINGLYIMPORTANTPARTOFTHERELATIONALDATABASEMODEL)TWASIMPLEMENTEDINMANY NON )"-31,PRODUCTS INCLUDINGTHEFLAGSHIPDATABASEPRODUCTSFROM-ICROSOFT 3YBASE AND /RACLE/UTERJOINSWEREINCLUDEDINTHE31,STANDARDSTARTINGWITH31,ANDARENOW BROADLYSUPPORTEDINMAINSTREAMPRODUCTS ALTHOUGHMANYENTRY LEVEL31,IMPLEMENTATIONS SUCHASTHOSEFOREMBEDDEDDEVICEAPPLICATIONSSTILLSUPPORTONLYINNERJOINS 4OUNDERSTANDTHEOUTERJOINWELL ITSUSEFULTOMOVEAWAYFROMTHESAMPLEDATABASE ANDCONSIDERTHETWOSIMPLETABLESATTHETOPOF&IGURE !SCRIPTTOCREATETHESETABLES ANDINSERTTHESAMPLEROWSCANBEFOUNDONTHEDOWNLOADSITEASDESCRIBEDIN!PPENDIX! 4HE')2,3TABLELISTSFIVEGIRLSANDTHECITIESWHERETHEYLIVETHE"/93TABLELISTSFIVEBOYS ANDTHECITIESWHERETHEYLIVE4OFINDTHEGIRLBOYPAIRSWHOLIVEINTHESAMECITY YOU COULDUSETHISQUERY WHICHFORMSTHEINNERJOINOFTHETWOTABLES ,ISTTHEGIRLSANDBOYSWHOLIVEINTHESAMECITY 3%,%#4 &2/-')2,3)..%2*/)."/93 /.')2,3#)49"/93#)49 ')2,3.!-%')2,3#)49"/93.!-%"/93#)49
-ARY"OSTON*OHN"OSTON -ARY"OSTON(ENRY"OSTON 3USAN#HICAGO3AM#HICAGO "ETTY#HICAGO3AM#HICAGO
4HISQUERYEXPLICITLYREQUESTSTHEINNERJOINOFTHETWOTABLESANDPRODUCESFOURROWSOF QUERYRESULTS4HEINNERJOINISTHEDEFAULT SOEXACTLYTHESAMERESULTSWOULDBEPRODUCEDIFTHE OPTIONALKEYWORD)..%2HADBEENOMITTEDFROMTHE&2/-CLAUSE.OTICETHATTWOOFTHEGIRLS !NNEAND.ANCY ANDTWOOFTHEBOYS*AMESAND'EORGE ARENOTREPRESENTEDINTHEQUERY RESULTS4HESEROWSCANNOTBEPAIREDWITHANYROWFROMTHEOTHERTABLE ANDSOTHEYAREMISSING FROMTHEINNERJOINRESULTS4WOOFTHEUNMATCHEDROWS!NNEAND*AMES HAVEVALIDVALUESIN THEIR#)49COLUMNS BUTTHEYDONTMATCHANYCITIESINTHEOPPOSITETABLE4HEOTHERTWO UNMATCHEDROWS.ANCYAND'EORGE HAVE.5,,VALUESINTHEIR#)49COLUMNS ANDBYTHERULES OF31,.5,,HANDLING THE.5,,VALUEDOESNTMATCHANYOTHERVALUEEVENANOTHER.5,,VALUE 3UPPOSEYOUWANTEDTOLISTTHEGIRLBOYPAIRSWHOSHARETHESAMECITIESANDINCLUDETHE UNMATCHEDGIRLSANDBOYSINTHELIST4HEFULLOUTERJOINOFTHE')2,3AND"/93TABLES PRODUCESEXACTLYTHISRESULT4HEFOLLOWINGLISTSHOWSTHEPROCEDUREFORCONSTRUCTINGTHEFULL OUTERJOIN ANDTHEPROCESSISSHOWNGRAPHICALLYIN&IGURE
"EGINWITHTHEINNERJOINOFTHETWOTABLES USINGMATCHINGCOLUMNSINTHENORMAL WAY4HISPRODUCESTHEFIRSTFOURROWSOFTHERESULTSTABLEINTHEFIGURE
&OREACHROWOFTHEFIRSTTABLETHATISNOTMATCHEDBYANYROWINTHESECONDTABLE ADDONEROWTOTHEQUERYRESULTS USINGTHEVALUESOFTHECOLUMNSINTHEFIRSTTABLE ANDASSUMINGA.5,,VALUEFORALLCOLUMNSOFTHESECONDTABLE4HISPRODUCESTHE FIFTHANDSIXTHROWSOFRESULTSINTHEFIGURE
#HAPTERçç
"# %!
!' ! "
"# "# "
# ! &"
!'
!' $" ##' '
"# "# %!
!' " !
"# "# "
1, ÊÇ£ÓÊ >ÌÞÊvÊ>ÊÕÌiÀÊ
&OREACHROWOFTHESECONDTABLETHATISNOTMATCHEDBYANYROWINTHEFIRSTTABLE ADDONEROWTOTHEQUERYRESULTS USINGTHEVALUESOFTHECOLUMNSINTHESECOND TABLE ANDASSUMINGA.5,,VALUEFORALLCOLUMNSOFTHEFIRSTTABLE4HISPRODUCES THESEVENTHANDEIGHTHROWSOFRESULTSINTHEFIGURE
4HERESULTINGTABLEISTHEOUTERJOINOFTHETWOTABLES!LLEIGHTROWSOFQUERYRESULTS INTHEFIGURE (EREISTHE31,STATEMENTTHATPRODUCESTHEOUTERJOIN
,ISTGIRLSANDBOYSINTHESAMECITY INCLUDINGANYUNMATCHEDGIRLSORBOYS 3%,%#4 &2/-')2,3&5,,/54%2*/)."/93 /.')2,3#)49"/93#)49 ')2,3.!-%')2,3#)49"/93.!-%"/93#)49
-ARY"OSTON*OHN"OSTON -ARY"OSTON(ENRY"OSTON 3USAN#HICAGO3AM#HICAGO "ETTY#HICAGO3AM#HICAGO !NNE$ENVER.5,,.5,, .ANCY.5,,.5,,.5,, .5,,.5,,*AMES$ALLAS .5,,.5,,'EORGE.5,,
0!24ç))
$#!
# ! &"
!' ' $" ##'
-ULTITABLEç1UERIESç*OINS ç
ç
0ARTç))ç
2ETRIEVINGç$ATA
!STHISEXAMPLESHOWS THEFULLOUTERJOINISANhINFORMATION PRESERVINGvJOIN3OME $"-3PRODUCTS SUCHAS-Y31, DONOTYETSUPPORTFULLOUTERJOINS %VERYROWOFTHE "/93TABLEISREPRESENTEDINTHEQUERYRESULTSSOMEMORETHANONCE 3IMILARLY EVERYROW OFTHE')2,3TABLEISREPRESENTEDINTHEQUERYRESULTSAGAIN SOMEMORETHANONCE
,EFTõANDõ2IGHTõ/UTERõ*OINS 4HEFULLOUTERJOINOFTWOTABLES ILLUSTRATEDINTHEPREVIOUSQUERY TREATSBOTHOFTHEJOINED TABLESSYMMETRICALLY4WOOTHERUSEFULANDWELL DEFINEDOUTERJOINSDONOT 4HELEFTOUTERJOINBETWEENTWOTABLESISPRODUCEDBYFOLLOWING3TEPAND3TEPINTHE PREVIOUSNUMBEREDLISTBUTOMITTING3TEP4HELEFTOUTERJOINTHUSINCLUDES.5,, EXTENDED COPIESOFTHEUNMATCHEDROWSFROMTHEFIRSTLEFT TABLE BUTDOESNOTINCLUDEANYUNMATCHED ROWSFROMTHESECONDRIGHT TABLE(EREISALEFTOUTERJOINBETWEENTHE')2,3AND"/93TABLES ,ISTGIRLSANDBOYSINTHESAMECITYANDANYUNMATCHEDGIRLS 3%,%#4 &2/-')2,3,%&4/54%2*/)."/93 /.')2,3#)49"/93#)49 ')2,3.!-%')2,3#)49"/93.!-%"/93#)49
-ARY"OSTON*OHN"OSTON -ARY"OSTON(ENRY"OSTON 3USAN#HICAGO3AM#HICAGO "ETTY#HICAGO3AM#HICAGO !NNE$ENVER.5,,.5,, .ANCY.5,,.5,,.5,,
4HEQUERYPRODUCESSIXROWSOFQUERYRESULTS SHOWINGTHEMATCHEDGIRLBOYPAIRSAND THEUNMATCHEDGIRLS4HEUNMATCHEDBOYSAREMISSINGFROMTHERESULTS 3IMILARLY THERIGHTOUTERJOINBETWEENTWOTABLESISPRODUCEDBYFOLLOWING3TEPAND 3TEPINTHEPREVIOUSNUMBEREDLISTBUTOMITTING3TEP4HERIGHTOUTERJOINTHUSINCLUDES .5,, EXTENDEDCOPIESOFTHEUNMATCHEDROWSFROMTHESECONDRIGHT TABLE BUTDOESNOT INCLUDETHEUNMATCHEDROWSOFTHEFIRSTLEFT TABLE(EREISARIGHTOUTERJOINBETWEENTHE ')2,3AND"/93TABLES ,ISTGIRLSANDBOYSINTHESAMECITYANDANYUNMATCHEDBOYS 3%,%#4 &2/-')2,32)'(4/54%2*/)."/93 /.')2,3#)49"/93#)49 ')2,3.!-%')2,3#)49"/93.!-%"/93#)49
-ARY"OSTON*OHN"OSTON -ARY"OSTON(ENRY"OSTON 3USAN#HICAGO3AM#HICAGO "ETTY#HICAGO3AM#HICAGO .5,,.5,,*AMES$ALLAS .5,,.5,,'EORGE.5,,
#HAPTERçç
-ULTITABLEç1UERIESç*OINS ç
,ISTTHESALESPEOPLEANDTHECITIESWHERETHEYWORK 3%,%#4.!-% #)49 &2/-3!,%32%03,%&4/54%2*/)./&&)#%3 /.2%0?/&&)#%/&&)#% .!-%#)49
4OM3NYDER.5,, -ARY*ONES.EW9ORK 3AM#LARK.EW9ORK "OB3MITH#HICAGO 0AUL#RUZ#HICAGO $AN2OBERTS#HICAGO "ILL!DAMS!TLANTA 3UE3MITH,OS!NGELES ,ARRY&ITCH,OS!NGELES .ANCY!NGELLI$ENVER
.OTEINTHISCASEALEFTOUTERJOIN THEhCHILDvTABLE3!,%32%03 THETABLEWITHTHE FOREIGNKEY ISTHEMAJORTABLE ANDTHEhPARENTvTABLE/&&)#%3 ISTHEMINORTABLE4HE OBJECTIVEISTORETAINROWSCONTAINING.5,,FOREIGNKEYVALUESLIKE4OM3NYDERS FROMTHE CHILDTABLEINTHEQUERYRESULTS SOTHECHILDTABLEBECOMESTHEMAJORTABLE)TDOESNTMATTER
0!24ç))
4HISQUERYALSOPRODUCESSIXROWSOFQUERYRESULTS SHOWINGTHEMATCHEDGIRLBOYPAIRS ANDTHEUNMATCHEDBOYS4HISTIMETHEUNMATCHEDGIRLSAREMISSINGFROMTHERESULTS !SNOTEDBEFORE THELEFTANDRIGHTOUTERJOINSDONOTTREATTHETWOJOINEDTABLES SYMMETRICALLY)TISOFTENUSEFULTOTHINKABOUTONEOFTHETABLESBEINGTHEhMAJORvTABLETHEONE WHOSEROWSAREALLREPRESENTEDINTHEQUERYRESULTS ANDTHEOTHERTABLEBEINGTHEhMINORvTABLE THEONEWHOSECOLUMNSCONTAIN.5,,VALUESINTHEJOINEDQUERYRESULTS )NALEFTOUTERJOIN THELEFTFIRST MENTIONED TABLEISTHEMAJORTABLE ANDTHERIGHTLATER NAMED TABLEISTHEMINOR TABLE4HEROLESAREREVERSEDINARIGHTOUTERJOINTHERIGHTTABLEISMAJOR THELEFTTABLEISMINOR )NPRACTICE THELEFTANDRIGHTOUTERJOINSAREMOREUSEFULTHANTHEFULLOUTERJOIN ESPECIALLY WHENJOININGDATAFROMTWOTABLESUSINGAPARENTCHILDPRIMARYKEYFOREIGNKEY RELATIONSHIP 7EHAVEALREADYSEENONEEXAMPLEINVOLVINGTHE3!,%32%03AND/&&)#%3TABLEINTHESAMPLE DATABASE4HE2%0?/&&)#%COLUMNINTHE3!,%32%03TABLEISAFOREIGNKEYTOTHE/&&)#%3 TABLEITTELLSTHEOFFICEWHEREEACHSALESPERSONWORKS ANDITISALLOWEDTOHAVEA.5,,VALUEFOR ANEWSALESPERSONWHOHASNOTYETBEENASSIGNEDTOANOFFICE SUCHAS4OM3NYDER!NYJOIN THATEXERCISESTHIS3!,%32%03 TO /&&)#%3RELATIONSHIPANDEXPECTSTOINCLUDEDATAFOR4OM 3NYDERMUSTBEANOUTERJOIN WITHTHE3!,%32%03TABLEASTHEMAJORTABLE(EREISTHEEXAMPLE USEDEARLIER
ç
0ARTç))ç
2ETRIEVINGç$ATA
WHETHERTHEQUERYISACTUALLYEXPRESSEDASALEFTOUTERJOINASJUSTSHOWN ORIFITISFLIPPED TOBECOMEARIGHTOUTERJOINLIKETHIS ,ISTTHESALESPEOPLEANDTHECITIESWHERETHEYWORK 3%,%#4.!-% #)49 &2/-/&&)#%32)'(4/54%2*/).3!,%32%03 /./&&)#%2%0?/&&)#% .!-%#)49
4OM3NYDER.5,, -ARY*ONES.EW9ORK 3AM#LARK.EW9ORK "OB3MITH#HICAGO 0AUL#RUZ#HICAGO $AN2OBERTS#HICAGO "ILL!DAMS!TLANTA 3UE3MITH,OS!NGELES ,ARRY&ITCH,OS!NGELES .ANCY!NGELLI$ENVER
7HATMATTERSISTHATTHECHILDTABLEISTHEMAJORTABLEINTHEOUTERJOIN 4HEREAREALSOUSEFULJOINEDQUERIESWHERETHEPARENTISTHEMAJORTABLEANDTHECHILD TABLEISTHEMINORTABLE&OREXAMPLE SUPPOSETHECOMPANYINTHESAMPLEDATABASEOPENSA NEWSALESOFFICEIN$ALLAS BUTINITIALLYTHEOFFICEHASNOSALESPEOPLEASSIGNEDTOIT)FYOU WANTTOGENERATEAREPORTLISTINGALLOFTHEOFFICESANDTHENAMESOFTHESALESPEOPLEWHO WORKTHERE YOUMIGHTWANTTOINCLUDEAROWREPRESENTINGTHE$ALLASOFFICE(EREISTHE OUTERJOINQUERYTHATPRODUCESTHOSERESULTS ,ISTTHEOFFICESANDTHESALESPEOPLEWHOWORKINEACHONE 3%,%#4#)49 .!-% &2/-/&&)#%3,%&4/54%2*/).3!,%32%03 /./&&)#%2%0?/&&)#% #)49.!-%
.EW9ORK-ARY*ONES .EW9ORK3AM#LARK #HICAGO"OB3MITH #HICAGO0AUL#RUZ #HICAGO$AN2OBERTS !TLANTA"ILL!DAMS ,OS!NGELES3UE3MITH ,OS!NGELES,ARRY&ITCH $ENVER.ANCY!NGELLI $ALLAS.5,,
)NTHISCASE THEPARENTTABLE/&&)#%3 ISTHEMAJORTABLEINTHEOUTERJOIN ANDTHECHILD TABLE3!,%32%03 ISTHEMINORTABLE4HEOBJECTIVEISTOENSURETHATALLROWSFROMTHE /&&)#%3TABLEAREREPRESENTEDINTHEQUERYRESULTS SOITPLAYSTHEROLEOFMAJORTABLE4HE ROLESOFTHETWOTABLESAREPRECISELYREVERSEDFROMTHEPREVIOUSEXAMPLE/FCOURSE THE ROWFOR4OM3NYDER WHICHWASINCLUDEDINTHEQUERYRESULTSFORTHEEARLIEREXAMPLE
#HAPTERçç
-ULTITABLEç1UERIESç*OINS ç
WHEN3!,%32%03WASTHEMAJORTABLE ISMISSINGFROMTHISSETOFQUERYRESULTSBECAUSE 3!,%32%03ISNOWTHEMINORTABLE
/LDERõ/UTERõ*OINõ.OTATION
,ISTGIRLSANDBOYSINTHESAMECITY INCLUDINGANYUNMATCHEDGIRLSORBOYS 3%,%#4 &2/-')2,3&5,,/54%2*/)."/93 /.')2,3#)49"/93#)49
BECOMESTHISQUERYUSINGTHE31,3ERVERNOTATION 3%,%#4 &2/-')2,3 "/93 7(%2%')2,3#)49 "/93#)49
4OINDICATETHEFULLOUTERJOINBETWEENTHETWOTABLES ANASTERISK ISPLACEDBEFOREAND AFTERTHEEQUALSIGNTHATDEFINESTHEJOIN4OINDICATEALEFTOUTERJOIN ONLYTHELEADING ASTERISKISSPECIFIED PRODUCINGTHISQUERY 3%,%#4 &2/-')2,3 "/93 7(%2%')2,3#)49 "/93#)49
WHICHISEQUIVALENTTOTHISSTANDARDS BASEDFORM 3%,%#4 &2/-')2,3,%&4/54%2*/)."/93 /.')2,3#)49"/93#)49
3IMILARLY ARIGHTOUTERJOINISINDICATEDBYANASTERISKFOLLOWINGTHEEQUALSIGN 3%,%#4 &2/-')2,3 "/93 7(%2%')2,3#)49 "/93#)49
0!24ç))
"ECAUSETHEOUTERJOINWASNOTPARTOFTHEORIGINAL31,STANDARDANDWASNOTIMPLEMENTED INEARLY)"-31,PRODUCTS THE$"-3VENDORSWHOPIONEEREDSUPPORTFORTHEOUTERJOIN EACHINVENTEDTHEIROWNNOTATIONFOREXPRESSINGOUTERJOINS5SERSOFTHESEPRODUCTSBEGAN TODEVELOPPROGRAMSTHATUSEDTHESEPROPRIETARYOUTERJOINCAPABILITIES CREATINGANINSTALLED BASEOFUSER WRITTENPROGRAMSTHATDEPENDEDONTHESPECIFIC/RACLEOR31,3ERVERNOTATION 4HEWRITERSOFTHE31,STANDARDWANTEDTOADDOUTERJOINSUPPORTINAWAYTHATWOULDNOT hBREAKvTHESEEXISTINGPROGRAMS SOTHEYCOULDCOEXISTWITHNEW STANDARDS BASED PROGRAMS!LLOFTHEMAJORVENDORSNOWSUPPORTSOMEORALLOFTHE31,STANDARDOUTERJOIN NOTATION ANDTHEYENCOURAGEITSUSE(OWEVER YOUMAYENCOUNTEROLDERPROGRAMSTHATUSE THEOLDERPROPRIETARYFORMS SOTHEYAREDESCRIBEDHERE 31,3ERVERSUPPORTEDOUTERJOINSINITSEARLYIMPLEMENTATIONSFROM3YBASEAND CONTINUEDTOSUPPORTOUTERJOINSAFTERITWASADOPTEDBY-ICROSOFT4HE31,3ERVERNOTATION APPENDSANASTERISK TOTHEEQUALSIGNINTHECOMPARISONTESTINTHE7(%2%CLAUSETHAT DEFINESTHEJOINCONDITION3OTHISFULLOUTERJOINBETWEENTHE')2,3AND"/93TABLES EXPRESSEDUSINGTHE31,STANDARDNOTATION
ç
0ARTç))ç
2ETRIEVINGç$ATA
4HEASTERISKMAYALSOBEUSEDINCONJUNCTIONWITHOTHERCOMPARISONOPERATORS SUCHASTHE GREATER THANORLESS THANSIGNS TOSPECIFYOUTERNON EQUI JOINS4HISOLDER31,3ERVER NOTATIONISSTILLSUPPORTEDBYCURRENTVERSIONSOFTHEPRODUCT IFTHEAPPROPRIATE COMPATIBILITYLEVELISSET BUTASOF31,3ERVER ITISCONSIDEREDADEPRECATEDFEATURE)T MAYALSOBEFOUNDINSTOREDPROCEDURESWRITTENUSING31,3ERVERS4RANSACT 31,LANGUAGE /RACLEALSOPROVIDEDEARLYSUPPORTFOROUTERJOINS BUTUSESADIFFERENTNOTATIONFROM 31,3ERVER4HISNOTATIONINDICATESTHEOUTERJOININTHE7(%2%CLAUSEBYINCLUDINGA PARENTHESIZEDPLUSSIGNFOLLOWINGTHECOLUMNWHOSETABLEISTOHAVETHEIMAGINARY.5,,ROW ADDEDTHATIS THEMINORTABLEINTHEOUTERJOIN 4HELEFTOUTERJOINOFTHE')2,3AND"/93 TABLESPRODUCESAN/RACLEQUERYTHATLOOKSLIKETHIS 3%,%#4 &2/-')2,3 "/93 7(%2%')2,3#)49"/93#)49
WHICHISONCEAGAINEQUIVALENTTOTHISSTANDARDS BASEDFORM 3%,%#4 &2/-')2,3,%&4/54%2*/)."/93 /.')2,3#)49"/93#)49
.OTETHATTHEPLUSSIGNAPPEARSONTHEOPPOSITESIDEOFTHECOMPARISONFROMWHERETHE ASTERISKAPPEARSINTHE31,3ERVERNOTATION3IMILARLY ARIGHTOUTERJOINISINDICATEDONTHE OPPOSITESIDEOFTHEEQUALSIGN 3%,%#4 &2/-')2,3 "/93 7(%2%')2,3#)49 "/93#)49
/RACLEDIDNOTSUPPORTAPROPRIETARYFORMOFTHEFULLOUTERJOIN BUTASNOTEDEARLIER THISDID NOTDIMINISHTHEPRACTICALUSEFULNESSOF/RACLESOUTERJOINS ANDYOUWILLFINDTHEOLDER NOTATIONINEXISTINGPROGRAMSWRITTENFORUSEWITH/RACLE "OTH 31,3ERVERAND/RACLENOTATIONSHAVESOMESIGNIFICANTLIMITATIONSCOMPAREDWITH THESTANDARDFORM&OREXAMPLE WHENTHREEORMORETABLESARECOMBINEDUSINGANOUTER JOIN THEORDERINWHICHTHETABLESAREJOINEDAFFECTSTHEQUERYRESULTS4HERESULTSOF 4",/54%2 */).4", /54%2 */).4",
WILLINGENERALBEDIFFERENTFROMTHERESULTSOF 4",/54%2 */).4",/54%2 */).4",
5SINGEITHERTHE31,3ERVEROR/RACLENOTATIONS ITSIMPOSSIBLETOSPECIFYTHEEVALUATION ORDEROFTHEOUTERJOINS"ECAUSEOFTHIS THERESULTSPRODUCEDBYTHEOUTERJOINOFTHREEOR MORETABLESDEPENDUPONTHESPECIFICSOFTHE$"-3IMPLEMENTATION&ORTHISANDOTHER REASONS YOUSHOULDALWAYSWRITENEWPROGRAMSUSINGTHE31,STANDARDOUTERJOIN NOTATION)TSALSOUSUALLYAGOODIDEATOCONVERTEXISTINGPROGRAMSTOTHESTANDARDNOTATION WHENTHEYAREBEINGREVISED
#HAPTERçç
-ULTITABLEç1UERIESç*OINS ç
*OINSõANDõTHEõ31,õ3TANDARD
)NNERõ*OINSõINõ3TANDARDõ31, &IGURE SHOWSASIMPLIFIEDFORMOFTHEEXTENDEDSTANDARD31,SYNTAXFORTHE&2/-CLAUSE )TSEASIESTTOUNDERSTANDALLOFTHEOPTIONSPROVIDEDBYCONSIDERINGEACHTYPEOFJOIN ONEBY ONE STARTINGWITHTHEBASICINNERJOINANDTHENMOVINGTOTHEVARIOUSFORMSOFOUTERJOIN4HE STANDARDINNERJOINOFTHE')2,3AND"/93TABLES EXPRESSEDINTHEORIGINAL31,NOTATION 3%,%#4 &2/-')2,3 "/93 7(%2%')2,3#)49"/93#)49
ISSTILLANACCEPTABLESTATEMENTINTHELATESTVERSIONOFTHESTANDARD4HESTANDARDWRITERS REALLYCOULDNTHAVEMADEITILLEGALWITHOUThBREAKINGvALLOFTHEMILLIONSOFMULTITABLE31, QUERIESTHATHADALREADYBEENWRITTENBYTHEEARLYS"UTTHEMODERN31,STANDARD ALLOWSTHESEALTERNATIVEWAYSOFEXPRESSINGANINNERJOIN WHICHWEHAVEALREADYSEENIN EARLIEREXAMPLES 3%,%#4 &2/-')2,3)..%2*/)."/93 /.')2,3#)49"/93#)49 3%,%#4 &2/-')2,3)..%2*/)."/93 53).'#)49 3%,%#4 &2/-')2,3.!452!,)..%2*/)."/93
4HE)..%2KEYWORDISOPTIONALANINNERJOINISTHEDEFAULT4HE.!452!,*/).FORM OFTHESTATEMENTCANBEUSEDIFALLOFTHEIDENTICALLYNAMEDCOLUMNSINTHETWOTABLESARE MATCHINGCOLUMNSOTHERWISE THE53).'CLAUSEMUSTBEUSEDTOINDICATESPECIFICMATCHING COLUMNS)NTHISCASE THEMATCHINGCOLUMNSARE.!-%AND#)49 ANDSINCENONEOFTHEBOYS HASTHESAMENAMEASONEOFTHEGIRLS THAT.!452!,*/).FORMOFTHEQUERYRETURNSNO ROWS)FTHEMATCHINGCOLUMNSDONOTHAVEIDENTICALNAMESINTHETWOTABLES ORIFANON EQUI JOINISNEEDED THENTHEFULL/.CLAUSEOR7(%2%CLAUSEMUSTBEUSEDTOSPECIFYTHE MATCHINGCOLUMNCONDITIONS4HE/.AND7(%2%CLAUSESAREALSOMOREWIDELYSUPPORTED THANTHE.!452!,AND53).'VARIATIONS
0!24ç))
4HE31,REVISIONDRAMATICALLYEXPANDEDTHESUPPORTFORJOINSINTHE!.3))3/31,STANDARD THROUGHANEW EXPANDEDFORMOFTHE&2/-CLAUSETHATCANEXPRESSEVENTHEMOSTCOMPLEX OFJOINS!TTHISWRITING ALLOFTHEMAJOR31,PRODUCTSHAVESUPPORTFORALL ORNEARLYALL OF THE31,EXPANDEDJOINCAPABILITY4HEEXPANDEDJOINSUPPORTCOMESATTHEEXPENSEOFSOME SIGNIFICANTADDEDCOMPLEXITYFORWHATHADPREVIOUSLYBEENONEOFTHESIMPLERPARTSOF31, )NFACT THEEXPANDEDJOINSUPPORTISPARTOFAMUCHLARGEREXPANSIONOFQUERYCAPABILITIESIN 31,ANDSUBSEQUENTVERSIONSOFTHE31,STANDARD WHICHADDEVENMORECAPABILITYAND COMPLEXITY4HEOTHEREXPANDEDFEATURESINCLUDESETOPERATIONSONQUERYRESULTSUNION INTERSECTION ANDDIFFERENCESOFTABLES ANDMUCHRICHERQUERYEXPRESSIONSTHATMANIPULATE ROWSANDTABLESANDALLOWTHEMTOBEUSEDINSUBQUERIES4HESECAPABILITIESAREDESCRIBEDIN THENEXTCHAPTER AFTERTHEDISCUSSIONOFBASICSUBQUERIES
ç
0ARTç))ç
2ETRIEVINGç$ATA
1, ÊÇ£ÎÊ ÝÌi`i`Ê&2/-ÊV>ÕÃiÊÊÌ
iÊ-+ÊÃÌ>`>À`
/UTERõ*OINSõINõ3TANDARDõ31,
7EHAVEALREADYSEENHOWTHEEXPANDED31,STANDARDSUPPORTSOUTERJOINS SUCHASTHE FULL LEFT ANDRIGHTOUTERJOINSSPECIFIEDBYTHESEQUERIES 3%,%#4 &2/-')2,3&5,,/54%2*/)."/93 /.')2,3#)49"/93#)49 3%,%#4 &2/-')2,3,%&4/54%2*/)."/93 /.')2,3#)49"/93#)49
#HAPTERçç
-ULTITABLEç1UERIESç*OINS ç
3%,%#4 &2/-')2,32)'(4/54%2*/)."/93 /.')2,3#)49"/93#)49
#ROSSõ*OINSõINõ3TANDARDõ31,
4HESUPPORTFOREXTENDEDJOINSINCLUDESTWOOTHERMETHODSFORCOMBININGDATAFROMTWO TABLES!CROSSJOINISANOTHERNAMEFORTHE#ARTESIANPRODUCTOFTWOTABLES ASDESCRIBED EARLIERINTHISCHAPTER(EREISAQUERYTHATGENERATESTHECOMPLETEPRODUCTOFTHE')2,3AND "/93TABLES 3%,%#4 &2/-')2,3#2/33*/)."/93
"YDEFINITION THE#ARTESIANPRODUCTALSOSOMETIMESCALLEDTHECROSSPRODUCT HENCETHE NAMEh#2/33*/).v CONTAINSEVERYPOSSIBLEPAIROFROWSFROMTHETWOTABLES)T hMULTIPLIESvTHETWOTABLES TURNINGTABLESOF FOREXAMPLE THREEGIRLSANDTWOBOYSINTOA TABLEOFSIX¾ BOYGIRLPAIRS.OhMATCHINGCOLUMNSvORhSELECTIONCRITERIAvARE ASSOCIATEDWITHTHECROSSPRODUCTS SOTHE/.CLAUSEANDTHE53).'CLAUSEARENOTALLOWED .OTETHATTHECROSSJOINREALLYDOESNTADDANYNEWCAPABILITIESTOTHE31,LANGUAGE%XACTLY THESAMEQUERYRESULTSCANBEGENERATEDWITHANINNERJOINTHATSPECIFIESNOMATCHING COLUMNS3OTHEPRECEDINGQUERYCOULDJUSTASWELLHAVEBEENWRITTENAS 3%,%#4 &2/-')2,3 "/93
4HEUSEOFTHEKEYWORDS#2/33*/).INTHE&2/-CLAUSESIMPLYMAKESTHECROSSJOIN MOREEXPLICIT)NMOSTDATABASES THECROSSJOINOFTWOTABLESBYITSELFISOFVERYLITTLEPRACTICAL USE)TSUSEFULNESSREALLYCOMESASABUILDINGBLOCKFORMORECOMPLEXQUERYEXPRESSIONSTHAT STARTWITHTHECROSSPRODUCTOFTWOTABLESANDTHENUSESUMMARYQUERYCAPABILITIES DESCRIBEDINTHENEXTCHAPTER ORSETOPERATIONSTOFURTHERMANIPULATETHERESULTS!TTHIS WRITING $"DOESNOTSUPPORTTHECROSSJOINSYNTAX BUTTHESAMEEFFECTCANBEACHIEVED WITHTHEOLDER31,SYNTAX 4HEUNIONJOINCOMBINESSOMEOFTHEFEATURESOFTHE5.)/.OPERATIONDESCRIBEDINTHE PREVIOUSCHAPTER WITHSOMEOFTHEFEATURESOFTHEJOINOPERATIONSDESCRIBEDINTHISCHAPTER (OWEVER THE5.)/.*/).WASDEPRECATEDINTHE31,STANDARDANDREMOVEDENTIRELY FROMTHE31,STANDARD3O IFYOUAREUSINGA$"-3THATSUPPORTSANEWERVERSIONOF THESTANDARD ITSLIKELYTHATITHASNOSUPPORTFORTHE5.)/.*/).SYNTAX)NFACT NONEOF THECURRENTVERSIONSOF/RACLE 31,3ERVER -Y31, AND$"SUPPORTSIT
0!24ç))
4HEUSEOFTHE/54%2KEYWORDISOPTIONALTHE$"-3CANINFERFROMTHEKEYWORD&5,, ,%&4 OR2)'(4THATANOUTERJOINISREQUIRED4HERESULTSOFTHEEXAMPLESSHOWNWILLALLBE DIFFERENTTHE&5,,/54%2*/).WILLRETURNALLTHEROWSFROMBOTHTABLES THE,%&4 /54%2*/).WILLRETURNALLTHEROWSFROMTHELEFT')2,3 TABLEPLUSMATCHINGROWSFROM THERIGHTTABLE"/93 ANDTHE2)'(4/54%2*/).WILLRETURNALLTHEROWSFROMTHERIGHT "/93 TABLEPLUSMATCHINGROWSFROMTHELEFT')2,3 TABLE!SFOR)..%2JOINS ANATURAL JOINCANBESPECIFIEDWITHTHE.!452!,KEYWORD ELIMINATINGTHENEEDTOEXPLICITLYNAME THEMATCHINGCOLUMNS3IMILARLY THEMATCHINGCOLUMNSCANBENAMEDINA53).'CLAUSE
ç
0ARTç))ç
2ETRIEVINGç$ATA
2ECALLTHATTHE5.)/.OPERATIONEFFECTIVELYCOMBINESTHEROWSOFTWOTABLES WHICHMUST HAVETHESAMENUMBEROFCOLUMNSANDTHECOMPATIBLEDATATYPESFOREACHCORRESPONDING COLUMN4HISQUERY WHICHUSESASIMPLE5.)/.OPERATION 3%,%#4 &2/-')2,3 5.)/.!,, 3%,%#4 &2/-"/93
WHENAPPLIEDTOAFIVE ROWTABLEOFGIRLSANDAFIVE ROWTABLEOFBOYS YIELDSATEN ROWTABLE OFQUERYRESULTS%ACHROWOFQUERYRESULTSCORRESPONDSPRECISELYTOEITHERAROWOFTHE')2,3 TABLEORAROWOFTHE"/93TABLEFROMWHICHITWASDERIVED4HEQUERYRESULTSHAVETWO COLUMNS .!-%AND#)49 BECAUSETHE')2,3AND"/93TABLESEACHHAVETHESETWOCOLUMNS 4HEUNIONJOINOFTHE')2,3AND"/93TABLESISSPECIFIEDBYTHISQUERY 3%,%#4 &2/-')2,3 5.)/.*/)."/93
4HEQUERYRESULTSAGAINHAVEFIVEROWS ANDAGAINEACHROWOFRESULTSISCONTRIBUTEDBY EXACTLYONEOFTHEROWSINTHE')2,3TABLEORTHE"/93TABLE"UTUNLIKETHESIMPLEUNION THESEQUERYRESULTSHAVEFOURCOLUMNSALLOFTHECOLUMNSOFTHEFIRSTTABLEPLUSALLOFTHE COLUMNSOFTHESECONDTABLE)NTHISASPECT THEUNIONJOINISLIKEALLOFTHEOTHERJOINS&OREACH ROWOFQUERYRESULTSCONTRIBUTEDBYTHE')2,3TABLE THECOLUMNSTHATCOMEFROMTHE')2,3 TABLERECEIVETHECORRESPONDINGDATAVALUESTHEOTHERCOLUMNSTHOSETHATCOMEFROMTHE "/93TABLE HAVE.5,,VALUES3IMILARLY FOREACHROWOFQUERYRESULTSCONTRIBUTEDBYTHE "/93TABLE THECOLUMNSTHATCOMEFROMTHE"/93TABLERECEIVETHECORRESPONDINGDATAVALUES THEOTHERCOLUMNSTHISTIME THOSETHATCOMEFROMTHE')2,3TABLE HAVE.5,,VALUES !NOTHERWAYOFLOOKINGATTHERESULTSOFTHEUNIONJOINISTOCOMPARETHEMTOTHERESULTS OFAFULLOUTERJOINOFTHE')2,3AND"/93TABLES4HEUNIONJOINRESULTSINCLUDETHE.5,, EXTENDEDROWSOFDATAFROMTHE')2,3TABLEANDTHE.5,, EXTENDEDROWSOFDATAFROMTHE "/93TABLE BUTTHEYDONOTINCLUDEANYOFTHEROWSGENERATEDBYMATCHINGCOLUMNS 2EFERRINGBACKTOTHEDEFINITIONOFANOUTERJOIN IN&IGURE THEUNIONJOINISPRODUCEDBY OMITTING3TEPANDFOLLOWING3TEPSAND &INALLY ITSUSEFULTOEXAMINETHERELATIONSHIPSBETWEENTHESETSOFROWSPRODUCEDBY THECROSSJOIN THEVARIOUSTYPESOFOUTERJOINS ANDTHEINNERJOINSHOWNIN&IGURE 7HENJOININGTWOTABLES 4",WITHMROWSAND4",WITHNROWS THEFIGURESHOWSTHAT s 4HECROSSJOINWILLCONTAINM¾NROWS CONSISTINGOFALLPOSSIBLEROWPAIRSFROMTHE TWOTABLES s 4",)..%2*/).4",WILLCONTAINSOMENUMBEROFROWS R WHICHISLESSTHAN M¾N4HEINNERJOINISSTRICTLYASUBSETOFTHECROSSJOIN)TISFORMEDBYELIMINATING THOSEROWSFROMTHECROSSJOINTHATDONOTSATISFYTHEMATCHINGCONDITIONFORTHE INNERJOIN s 4HELEFTOUTERJOINCONTAINSALLOFTHEROWSFROMTHEINNERJOIN PLUSEACHUNMATCHED ROWFROM4", .5,, EXTENDED s 4HERIGHTOUTERJOINALSOCONTAINSALLOFTHEROWSFROMTHEINNERJOIN PLUSEACH UNMATCHEDROWFROM4", .5,, EXTENDED
#HAPTERçç
-ULTITABLEç1UERIESç*OINS ç
s 4HEFULLOUTERJOINCONTAINSALLOFTHEROWSFROMTHEINNERJOIN PLUSEACHUNMATCHED ROWFROM4", .5,, EXTENDED PLUSEACHUNMATCHEDROWFROM4", .5,, EXTENDED2OUGHLYSPEAKING ITSQUERYRESULTSAREEQUALTOTHELEFTOUTERJOINhPLUSv THERIGHTOUTERJOIN s 4HEUNIONJOINCONTAINSALLOFTHEROWSOF4", .5,, EXTENDED PLUSALLOFTHEROWS OF4", .5,, EXTENDED2OUGHLYSPEAKING ITSQUERYRESULTSARETHEFULLOUTERJOIN hMINUSvTHEINNERJOIN
-ULTITABLEõ*OINSõINõ3TANDARDõ31,
#(),$
>ÌV
iÃÊÌ
iÊ.!-%ÊVÕÊÊÌ
iÊ')2,3ÊÀÊ"/93ÊÌ>Li
490%
-«iVviÃÊ&!4(%2ÊÀÊ-/4(%2
0.!-%
ÀÃÌÊ>iÊvÊÌ
iÊ«>ÀiÌ
"
" " !
" " !
"
" " !
" " !
# "
$"
1, ÊÇ£{Ê ,i>ÌÃ
«ÃÊ>}ÊÊÌÞ«iÃ
# "
0!24ç))
!NIMPORTANTADVANTAGEOFTHESTANDARD31,NOTATIONISTHATITALLOWSVERYCLEAR SPECIFICATIONOFTHREE TABLEORFOUR TABLEJOINS4OBUILDTHESEMORECOMPLEXJOINS ANYOFTHE JOINEXPRESSIONSSHOWNIN&IGURE ANDDESCRIBEDINTHEPRECEDINGSECTIONSCANBE ENCLOSEDINPARENTHESES4HERESULTINGJOINEXPRESSIONCANITSELFBEUSEDINANOTHERJOIN EXPRESSION ASIFITWEREASIMPLETABLE*USTAS31,ALLOWSYOUTOCOMBINEMATHEMATICAL OPERATIONS AND WITHPARENTHESESANDBUILDMORECOMPLEXEXPRESSIONS THE31, STANDARDALLOWSYOUTOBUILDMORECOMPLEXJOINEXPRESSIONSINTHESAMEWAY 4OILLUSTRATEMULTITABLEJOINS ASSUMETHATANEW0!2%.43TABLEHASBEENADDEDTOTHE DATABASECONTAININGTHE')2,3AND"/93EXAMPLEWEHAVEBEENUSING4HE0!2%.43TABLE HASTHREECOLUMNS
ç
0ARTç))ç
2ETRIEVINGç$ATA
!ROWINTHE')2,3OR"/93TABLECANHAVETWOMATCHINGROWSINTHE0!2%.43TABLE ONESPECIFYINGA-/4(%2ANDONEA&!4(%2 ORITCANHAVEONLYONEOFTHESEROWS ORITCAN HAVENOMATCHINGROWSIFNODATAONTHECHILDSPARENTSISAVAILABLE4HE')2,3 "/93 AND 0!2%.43TABLESTOGETHERPROVIDEARICHSETOFDATAFORSOMEMULTITABLEJOINEXAMPLES 3UPPOSEYOUWANTEDTOMAKEALISTOFALLOFTHEGIRLS ALONGWITHTHENAMESOFTHEIR MOTHERSANDTHENAMESOFTHEBOYSWHOLIVEINTHESAMECITY(EREISONEQUERYTHAT PRODUCESTHELIST 3%,%#4')2,3.!-% 0.!-% "/93.!-% &2/-')2,3*/).0!2%.43 /.0!2%.43#(),$.!-% */)."/93 /.')2,3#)49"/93#)49 7(%2%490%g-/4(%2g
"ECAUSEBOTHOFTHESEJOINSAREINNERJOINS ANYGIRLWHODOESNOTHAVEABOYLIVINGINTHE SAMECITYORANYGIRLWHODOESNOTHAVEAMOTHERINTHEDATABASEWILLNOTSHOWUPINTHE QUERYRESULTS4HISMAYORMAYNOTBETHEDESIREDRESULT4OINCLUDETHOSEGIRLSWITHOUTA MATCHINGMOTHERINTHEDATABASE YOUWOULDCHANGETHEJOINBETWEENTHE')2,3ANDTHE 0!2%.43TABLETOALEFTOUTERJOIN LIKETHIS 3%,%#4')2,3.!-% 0.!-% "/93.!-% &2/-')2,3,%&4*/).0!2%.43 /.0!2%.43#(),$.!-% */)."/93 /.')2,3#)49"/93#)49 7(%2%490%g-/4(%2g /2490%)3.5,,
4HISQUERYWILLINCLUDEALLOFTHEGIRLBOYPAIRS REGARDLESSOFWHETHERTHEGIRLSHAVE AMOTHERINTHEDATABASE BUTITWILLSTILLOMITGIRLSWHODONOTLIVEINACITYWITHANYOF THEBOYS4OINCLUDETHESEGIRLSASWELL THESECONDJOINMUSTALSOBECONVERTEDTOALEFT OUTERJOIN 3%,%#4')2,3.!-% 0.!-% "/93.!-% &2/-')2,3,%&4*/).0!2%.43 /.0!2%.43#(),$.!-% ,%&4*/)."/93 /.')2,3#)49"/93#)49 7(%2%490%g-/4(%2g /2490%)3.5,,
.OTETHATTHE.5,, EXTENSIONOFTHE')2,3ROWSBYTHEOUTERJOINWITHTHEIRMOTHERS ALSOCREATESSOMEADDITIONALCOMPLICATIONINTHE7(%2%CLAUSE4HEGIRLSWITHOUTMATCHING MOTHERSWILLGENERATEROWSWITHNOTONLYA.5,,MOTHERSNAME0.!-% COLUMN BUTALSO A.5,,VALUEINTHE490%COLUMN4HESIMPLESELECTIONCRITERION 7(%2%490%g-/4(%2g
WOULDGENERATEANhUNKNOWNvRESULTFORTHESEROWS ANDTHEYWILLNOTBEINCLUDEDINTHE QUERYRESULTS"UTTHEENTIREREASONFORUSINGTHELEFTOUTERJOINWASTOMAKECERTAINTHEY WEREINCLUDED4OSOLVETHISPROBLEM THE7(%2%CLAUSEISEXPANDEDTOALSOTESTFOR AND ALLOW ROWSWHERETHEPARENTTYPEIS.5,,
#HAPTERçç
-ULTITABLEç1UERIESç*OINS ç
3%,%#4')2,3.!-% -/4(%230.!-% "/93.!-% &!4(%230.!-% &2/-')2,3,%&4*/).0!2%.43!3-/4(%23 /.-/4(%23#(),$')2,3.!-% !.$-/4(%23490%g-/4(%2g */)."/93/.')2,3#)49"/93#)49 ,%&4*/).0!2%.43!3&!4(%23 /.&!4(%23#(),$"/93.!-% !.$&!4(%23490%g&!4(%2g
4HISQUERYSOLVESTHE7(%2% CLAUSETESTPROBLEMINADIFFERENTWAYBYMOVINGTHETEST FORTHE490%OFPARENTINTOTHE/.CLAUSEOFTHEJOINSPECIFICATION)NTHISPOSITION THETESTFOR APPROPRIATE490%OFPARENTWILLBEPERFORMEDWHENTHE$"-3FINDSMATCHINGCOLUMNSTO CONSTRUCTTHEJOIN BEFORETHE.5,, EXTENDEDROWSAREADDEDTOTHEOUTERJOINRESULTS "ECAUSETHE0!2%.43TABLEISBEINGUSEDTWICEINTHE&2/-CLAUSE INTWODIFFERENTROLES ITS NECESSARYTOGIVEITTWODIFFERENTTABLEALIASESSOTHATTHECORRECTNAMESCANBESPECIFIEDIN THESELECTLIST !STHISEXAMPLESHOWS EVENAFOUR JOINQUERYLIKETHISONECANBECOMEQUITE COMPLEXWITHTHEEXPANDEDSTANDARD31,JOINSYNTAX3YNTAXCANVARYACROSS31, IMPLEMENTATIONS&OREXAMPLE /RACLEDOESNTACCEPTTHE!3KEYWORDBETWEENTHETABLE NAMEANDALIASINTHE*/).CLAUSE(OWEVER DESPITETHECOMPLEXITY THEQUERYDOES SPECIFYPRECISELYTHEQUERYTHATTHE$"-3ISTOCARRYOUT4HEREISNOAMBIGUITYABOUTTHE ORDERINWHICHTHETABLESAREJOINED ORABOUTWHICHJOINSAREINNEROROUTERJOINS /VERALL THEADDEDCAPABILITYISWELLWORTHTHEADDEDCOMPLEXITYINTRODUCEDBYTHE EXTENDEDSTANDARD31,&2/-CLAUSE !LTHOUGHNONEOFTHEQUERYEXAMPLESINCLUDEDINTHISSECTIONHAD7(%2%OR/2$%2"9 CLAUSES THEYCANBEFREELYUSEDWITHTHEEXTENDEDJOINSUPPORT4HERELATIONSHIPAMONGTHE CLAUSESISSIMPLEANDREMAINSASDESCRIBEDEARLIERINTHISCHAPTER4HEPROCESSINGSPECIFIED INTHE&2/-CLAUSESGENERALLYOCCURSFIRST INCLUDINGANYJOINSORUNIONS4HEJOINCRITERIA SPECIFIEDINA53).'OR/.CLAUSEAREAPPLIEDASAPARTOFTHEPARTICULARJOINSPECIFICATION WHERETHEYAPPEAR7HENPROCESSINGOFTHE&2/-CLASSISCOMPLETE THERESULTINGTABLEIS USEDTOAPPLYTHESELECTIONCRITERIAINTHE7(%2%CLAUSE4HUS THE/.CLAUSESPECIFIESSEARCH CRITERIATHATAPPLYTOSPECIFICJOINSTHE7(%2%CLAUSESPECIFIESSEARCHCRITERIATHATAPPLYTO THEENTIRETABLERESULTINGFROMTHESEJOINS 4ABLE SUMMARIZES31,JOINSYNTAX SHOWINGBOTHOLDANDNEW31,STANDARD VARIANTSUSINGMANYOFTHEEXAMPLESFROMTHISCHAPTER
0!24ç))
!SONEFINALEXAMPLE SUPPOSEYOUWANTTOGENERATEAGIRLBOYLISTINGAGAIN BUTTHIS TIMEYOUWANTTOINCLUDETHENAMEOFTHEBOYSFATHERANDTHEGIRLSMOTHERINTHEQUERY RESULTS4HISQUERYREQUIRESAFOUR TABLEJOIN"/93 ')2,3 ANDTWOCOPIESOFTHE 0!2%.43TABLE ONEFORJOININGTOTHEBOYSINFORMATIONTOGETFATHERNAMESANDONEFOR JOININGTOTHEGIRLSINFORMATIONTOOBTAINMOTHERNAMES !GAINTHEPOTENTIALFOR UNMATCHEDROWSINTHEJOINSMEANSTHEREARESEVERALPOSSIBLEhRIGHTvANSWERSTOTHE QUERY3UPPOSE ASBEFORE THATYOUWANTTOINCLUDEALLGIRLSANDBOYSINTHEBOYGIRL PAIRING EVENIFTHEBOYORGIRLDOESNOTHAVEAMATCHINGROWINTHE0!2%.43TABLE9OU NEEDTOUSEOUTERJOINSFORTHE"/93JOIN0!2%.43 AND')2,3JOIN0!2%.43 PARTSOF THEQUERY BUTANINNERJOINFORTHE"/93JOIN')2,3 PARTOFTHEQUERY4HISQUERYYIELDS THEDESIREDRESULTS
ç
£
ÀiÊÌ
>ÊÌÜÊÌ>LiÃÊ>ÀiÊi`ÊÌ}iÌ
iÀÊLÞÊ >``}Ê>``Ì>Ê*/).ÊV>ÕÃið
ÊiµÕÊÌ
>ÌÊ>ÌV
iÃÊÀÜÃÊL>Ãi`ÊÊ>ÊÌ
iÊ VÕÃÊÌ
>ÌÊÃ
>ÀiÊÌ
iÊÃ>iÊ>iÊLiÌÜiiÊÌ
iÊ i`ÊÌ>Lið ÊiµÕÊL>Ãi`ÊÊÌ
iÊiÝ«VÌÞÊ`iÌvi`Ê VÕÊ>iÃÊÌ
>ÌÊÃ
>ÀiÊÌ
iÊÃ>iÊ>iÊÊÌ
iÊ i`ÊÌ>Lið
3%,%#4#)49 .!-% 4)4,% &2/-/&&)#%3*/).3!,%32%03 /.-'2%-0,?.5- 7(%2%4!2'%4 3%,%#4/2$%2?.5- !-/5.4 $%3#2)04)/. &2/-/2$%23*/).02/$5#43 /.-&2-&2?)$ !.$02/$5#402/$5#4?)$ 3%,%#4/2$%2?.5- !-/5.4 #/-0!.9 .!-% &2/-/2$%23*/).#534/-%23 /.#534#534?.5- */).3!,%32%03 /.2%0%-0,?.5- 7(%2%!-/5.4 3%,%#4.!-% 15/4! 4!2'%4 &2/-3!,%32%03*/)./&&)#%3 /.15/4!4!2'%4
3%,%#4/2$%2?.5- !-/5.4 $%3#2)04)/. &2/-/2$%23.!452!,*/).02/$5#43 3%,%#4/2$%2?.5- !-/5.4 $%3#2)04)/. &2/-/2$%23*/).02/$5#43 53).'-&2 02/$5#4 3%,%#4%-03.!-% -'23.!-% &2/-3!,%32%03%-03*/).3!,%32%03-'23 /.%-03-!.!'%2-'23%-0,?.5-
3%,%#4#)49 .!-% 4)4,% &2/-/&&)#%3 3!,%32%03 7(%2%-'2%-0,?.5- !.$4!2'%4
3%,%#4/2$%2?.5- !-/5.4 $%3#2)04)/. &2/-/2$%23 02/$5#43 7(%2%-&2-&2?)$ !.$02/$5#402/$5#4?)$
3%,%#4/2$%2?.5- !-/5.4 #/-0!.9 .!-% &2/-/2$%23 #534/-%23 3!,%32%03 7(%2%#534#534?.5- !.$2%0%-0,?.5- !.$!-/5.4
3%,%#4.!-% 15/4! 4!2'%4 &2/-3!,%32%03 /&&)#%3 7(%2%15/4!4!2'%4
3%,%#4/2$%2?.5- !-/5.4 $%3#2)04)/. &2/-/2$%23 02/$5#43 7(%2%-&2-&2?)$ !.$02/$5#402/$5#4?)$
NA
3%,%#4%-03.!-% -'23.!-% &2/-3!,%32%03%-03 3!,%32%03-'23 7(%2%%-03-!.!'%2-'23%-0,?.5-
*>ÀiÌÉV
`ʵÕiÀÞ
,ÜÊÃiiVÌÊ VÀÌiÀ>
ÕÌ«iÊ>ÌV
}Ê VÕÃ
/
ÀiiÌ>LiÊ
iµÕ
>ÌÕÀ>Ê
Ê ÜÌ
Ê53).'ÊV>ÕÃi
-iv
ÕÊÕÌiÀÊ
"ÕÌiÀÊÃÓ]Î
3%,%#4 &2/-')2,3 "/93 7(%2%')2,3#)49"/93#)49 5.)/. 3%,%#4 &2/-')2,3 "/93 7(%2%')2,3#)49 "/93#)49
3%,%#4 &2/-')2,3&5,,/54%2*/)."/93 /.')2,3#)49"/93#)49
ÕÌVÕÊ«À>ÀÞÊ>`ÊvÀi}ÊiÞÃÊÀiµÕÀiÊ ÕÌ«iÊVÕÊ>ÌV
}ÊÊÌ
iÊÊ«Ài`V>Ìi°
3%,%#4#)49 .!-% 4)4,% &2/-/&&)#%3*/).3!,%32%03 /.-'2%-0,?.5-
3%,%#4#)49 .!-% 4)4,% &2/-/&&)#%3 3!,%32%03 7(%2%-'2%-0,?.5-
``ÃÊ>Ê.5,,iÝÌi`i`ÊÀÜÊÌÊÌ
iʵÕiÀÞÊÀiÃÕÌÃÊ vÀÊi>V
ÊÕ>ÌV
i`ÊÀÜÊvÊi>V
Êi`ÊÌ>Li°
ÊiµÕÊvÊ>ÊÌ>LiÊÌÊÌÃivÊÜÌ
Êi>V
ÊÀÜÊ >ÌV
i`ÊÜÌ
ÊÌ
iÀÊÀÜÃÊÊÌ
iÊÃ>iÊÌ>Li°
/
iÊV«>ÀÃÊ«iÀ>ÌÀÊÊÌ
iÊÊ«Ài`V>ÌiÊÃÊ Ì
iÀÊÌ
>ÊiµÕ>Êr®°
1Ü>Ìi`ÊÀÜÃÊ>ÀiÊvÌiÀi`ÊÕÌÊvÀÊÌ
iʵÕiÀÞÊ ÀiÃÕÌÃÊLÞÊ>``}Ê>Ê7(%2%Ê«Ài`V>Ìi°
ÊiµÕÊÌ
>ÌÊ>ÌV
iÃÊÌ
iÊ«À>ÀÞÊiÞÊÊiÊ Ì>LiÊÜÌ
ÊÌ
iÊVÀÀië`}ÊvÀi}ÊiÞÊÊÌ
iÊÌ
iÀ°
-ÞÌ>ÝÊÛ>À>ÌÊÕÃ}Ê)..%2*/).ÊiÞÜÀ`ÃÊ ÃÌi>`ÊvÊëÞÊ*/).°
-«iÊiµÕ
NA
3%,%#4.!-% #)49 &2/-3!,%32%03 /&&)#%3 7(%2%2%0?/&&)#%/&&)#%
Ý«VÌÊiµÕ
iÃVÀ«Ì
3%,%#4.!-% #)49 &2/-3!,%32%03)..%2*/)./&&)#%3 /.2%0?/&&)#%/&&)#%
-Ì>`>À`Ê-+Ê-ÞÌ>Ý
ÀÃÊ«>ÀÃÊvÊÀÜÃÊLÞÊ>ÌV
}ÊÌ
iÊVÌiÌÃÊvÊ Ài>Ìi`ÊVÕÃÊL>Ãi`ÊÊ>ÊiÝ>VÌÊ>ÌV
ÊLiÌÜiiÊ «>ÀÃÊvÊVÕð
"`Ê-ÞÌ>Ý
3%,%#4.!-% #)49 &2/-3!,%32%03*/)./&&)#%3 /.2%0?/&&)#%/&&)#%
iÀÊÃ
/Þ«i
3%,%#4 &2/-')2,3 "/93 7(%2%')2,3#)49"/93#)49
ivÌÊÕÌiÀÊ
3%,%#4 &2/-')2,32)'(4/54%2*/)."/93 53).'#)49
3%,%#4 &2/-')2,3 "/93 7(%2%')2,3#)49 "/93#)49
NA
,}
ÌÊÕÌiÀÊ
,}
ÌÊÕÌiÀÊÊ ÜÌ
Ê53).'ÊV>ÕÃi
3%,%#4 &2/-')2,3#2/33*/)."/93 3%,%#4 &2/-')2,3 5.)/.!,, 3%,%#4 &2/-"/93
3%,%#4 &2/-')2,3 "/93
3%,%#4 &2/-')2,3 5.)/.!,, 3%,%#4 &2/-"/93
ÀÃÃÊ
1ʺ»
/iV
V>ÞÊÌÊ>ÊÆÊÌ
iÊ3%,%#4ÃÊ«ÀViÃÃÊ `i«i`iÌÞÊ>`ÊÌ
iÊÀiÃÕÌÊÃiÌÃÊ>ÀiÊÌ
iÊ VV>Ìi>Ìi`ÊLÞÊÌ
iÊ5.)/.Ê«iÀ>ÌÀ°
Ý«VÌÞÊÀiµÕiÃÌÃÊÌ
iÊ >ÀÌiÃ>Ê«À`ÕVÌ]ÊÜ
V
Ê ÃÊÌ
iÊ«À`ÕVÌÊVÃÃÌ}ÊvÊ>Ê«ÃÃLiÊ«>ÀÃÊvÊ ÀÜÃÊvÀÊÌ
iÊÌÜÊÌ>Lið
ÊÀ}
ÌÊÕÌiÀÊÊL>Ãi`ÊÊÌ
iÊiÝ«VÌÞÊ`iÌvi`Ê VÕÊ>iÃÊÌ
>ÌÊÃ
>ÀiÊÌ
iÊÃ>iÊ>iÊÊÌ
iÊ i`ÊÌ>Lið
3%,%#4 &2/-')2,32)'(4/54%2*/)."/93 /.')2,3#)49"/93#)49
NA
"Ì
iÀÊÃ
``ÃÊ>Ê.5,,iÝÌi`i`ÊÀÜÊÌÊÌ
iʵÕiÀÞÊÀiÃÕÌÃÊ vÀÊi>V
ÊÕ>ÌV
i`ÊÀÜÊvÊÌ
iÊÃiV`ÊÀ}
Ì®Ê Ì>Li°
3%,%#4 &2/-')2,3,%&4/54%2*/)."/93 53).'#)49
ivÌÊÕÌiÀÊÊ ÜÌ
Ê53).'ÊV>ÕÃi
ÊivÌÊÕÌiÀÊÊL>Ãi`ÊÊÌ
iÊiÝ«VÌÞÊ`iÌvi`Ê VÕÊ>iÃÊÌ
>ÌÊÃ
>ÀiÊÌ
iÊÃ>iÊ>iÊÊÌ
iÊ i`ÊÌ>Lið
``ÃÊ>Ê.5,,iÝÌi`i`ÊÀÜÊÌÊÌ
iʵÕiÀÞÊÀiÃÕÌÃÊ vÀÊi>V
ÊÕ>ÌV
i`ÊÀÜÊvÊÌ
iÊvÀÃÌÊivÌ®ÊÌ>Li°
>ÞÊ-+Ê«iiÌ>ÌÃÊ>ÜÊÌ
iÊiÞÜÀ`Ê /54%2ÊÌÊLiÊivÌÊÕÌÊLiV>ÕÃiÊÌÊÃÊ«i`ÊLÞÊÌ
iÊ iÞÜÀ`Ê&5,,°
/ ÊÇ£Ê Ê-Õ>ÀÞ
)NNERJOINSHAVETHEPOTENTIALTOLOSEINFORMATIONIFTHETABLESBEINGJOINEDCONTAINUNMATCHEDROWS /UTERJOINSDONOTLOSEINFORMATIONBECAUSETHEYhADDBACKvTHEUNMATCHEDROWS /RACLESYNTAXUSEDIN/LD3YNTAXEXAMPLES 4HISQUERYISFORILLUSTRATIONONLYBECAUSENOCOLUMNSSHARETHESAMENAMEINTHE/2$%23AND02/$5#43TABLESOFTHESAMPLEDATABASE)FYOURUNTHISORANYQUERYTHAT PERFORMSANATURALJOINONTWOTABLESWITHNOMATCHINGCOLUMNNAMESBETWEENTHEM MANYBRANDSOF31,$"-3WILLRETURNTHE#ARTESIANPRODUCT 4HISQUERYISFORILLUSTRATIONONLYANDWILLNOTRUNONTHESAMPLEDATABASEBECAUSETHE02/$5#43TABLEDOESNOTCONTAINCOLUMNSNAMED-&2AND02/$5#4
3%,%#4 &2/-')2,3,%&4/54%2*/)."/93 /.')2,3#)49"/93#)49
NA
ÕÊÕÌiÀÊÊ ÜÌ
ÊiÞÜÀ`Ê /54%2Ê«i`
"ÕÌiÀÊÃÓ]Î
3%,%#4 &2/-')2,3&5,,*/)."/93 53).'#)49
NA
ÊvÕÊÕÌiÀÊÊL>Ãi`ÊÊÌ
iÊiÝ«VÌÞÊ`iÌvi`Ê VÕÊ>iÃÊÌ
>ÌÊÃ
>ÀiÊÌ
iÊÃ>iÊ>iÊÊÌ
iÊ i`ÊÌ>Lið
ÕÊÕÌiÀÊÊ ÜÌ
Ê53).'ÊV>ÕÃi
3%,%#4 &2/-')2,3&5,,/54%2*/)."/93 53).'#)49
NA
ÊvÕÊÕÌiÀÊÊÌ
>ÌÊ>ÌV
iÃÊÀÜÃÊL>Ãi`ÊÊ>Ê Ì
iÊVÕÃÊÌ
>ÌÊÃ
>ÀiÊÌ
iÊÃ>iÊ>iÊLiÌÜiiÊ Ì
iÊi`ÊÌ>Lið
3%,%#4 &2/-')2,3.!452!,&5,,/54%2*/). "/93
>ÌÕÀ>Ê vÕÊÕÌiÀÊ
0!24ç))
ç
ç
0ARTç))ç
2ETRIEVINGç$ATA
3UMMARY 4HISCHAPTERDESCRIBEDHOW31,HANDLESQUERIESTHATCOMBINEDATAFROMTWOORMORETABLES s )NAMULTITABLEQUERYAJOIN THETABLESCONTAININGTHEDATAARENAMEDINTHE&2/- CLAUSE s %ACHROWOFQUERYRESULTSISACOMBINATIONOFDATAFROMASINGLEROWINEACHOFTHE TABLES ANDITISTHEONLYROWTHATDRAWSITSDATAFROMTHATPARTICULARCOMBINATION s 4HEMOSTCOMMONMULTITABLEQUERIESUSETHEPARENTCHILDRELATIONSHIPSCREATEDBY PRIMARYKEYSANDFOREIGNKEYS s )NGENERAL JOINSCANBEBUILTBYCOMPARINGANYPAIRS OFCOLUMNSFROMTHETWO JOINEDTABLES USINGEITHERATESTFOREQUALITYORANYOTHERCOMPARISONTEST s !JOINCANBETHOUGHTOFASTHEPRODUCTOFTWOTABLESFROMWHICHSOMEOFTHEROWS HAVEBEENREMOVED s !TABLECANBEJOINEDTOITSELFSELF JOINSREQUIRETHEUSEOFATABLEALIAS s /UTERJOINSEXTENDTHESTANDARDINNER JOINBYRETAININGUNMATCHEDROWSOFONEOR BOTHOFTHEJOINEDTABLESINTHEQUERYRESULTS ANDUSING.5,,VALUESFORDATAFROM THEOTHERTABLE s 4HE31,STANDARDPROVIDESCOMPREHENSIVESUPPORTFORINNERANDOUTERJOINS AND FORCOMBININGTHERESULTSOFJOINSWITHOTHERMULTITABLEOPERATIONSSUCHASUNIONS INTERSECTIONS ANDDIFFERENCES
#(!04%2
3UMMARYç1UERIES
-
ANYREQUESTSFORINFORMATIONDONTREQUIRETHELEVELOFDETAILPROVIDEDBYTHE 31,QUERIESDESCRIBEDINTHELASTTWOCHAPTERS&OREXAMPLE EACHOFTHEFOLLOWING REQUESTSASKSFORASINGLEVALUEORASMALLNUMBEROFVALUESTHATSUMMARIZESTHE CONTENTSOFTHEDATABASE s 7HATISTHETOTALQUOTAFORALLSALESPEOPLE s 7HATARETHESMALLESTANDLARGESTASSIGNEDQUOTAS s (OWMANYSALESPEOPLEHAVEEXCEEDEDTHEIRQUOTA s 7HATISTHESIZEOFTHEAVERAGEORDER s 7HATISTHESIZEOFTHEAVERAGEORDERFOREACHSALESOFFICE s (OWMANYSALESPEOPLEAREASSIGNEDTOEACHSALESOFFICE 31,SUPPORTSTHESEREQUESTSFORSUMMARYDATATHROUGHCOLUMNFUNCTIONSANDTHE '2/50"9AND(!6).'CLAUSESOFTHE3%,%#4STATEMENT WHICHAREDESCRIBEDINTHISCHAPTER
#OLUMNõ&UNCTIONS 31,LETSYOUSUMMARIZEDATAFROMTHEDATABASETHROUGHASETOFCOLUMNFUNCTIONS!31, COLUMNFUNCTIONTAKESANENTIRECOLUMNOFDATAASITSARGUMENTANDPRODUCESASINGLEDATA ITEMTHATSUMMARIZESTHECOLUMN&OREXAMPLE THE!6' COLUMNFUNCTIONTAKESACOLUMN OFDATAANDCOMPUTESITSAVERAGE(EREISAQUERYTHATUSESTHE!6' COLUMNFUNCTIONTO COMPUTETHEAVERAGEVALUEOFTWOCOLUMNSFROMTHE3!,%32%03TABLE 7HATARETHEAVERAGEQUOTAANDAVERAGESALESOFOURSALESPEOPLE 3%,%#4!6'15/4! !6'3!,%3 &2/-3!,%32%03 !6'15/4! !6'3!,%3
ç
0ARTç))ç
2ETRIEVINGç$ATA
1, Ên£Ê ÊÃÕ>ÀÞʵÕiÀÞÊÊ«iÀ>Ì
&IGURE GRAPHICALLYSHOWSHOWTHEQUERYRESULTSAREPRODUCED4HEFIRSTCOLUMN FUNCTIONINTHEQUERYTAKESVALUESINTHE15/4!COLUMNANDCOMPUTESTHEIRAVERAGE THESECONDONEAVERAGESTHEVALUESINTHE3!,%3COLUMN4HEQUERYPRODUCESASINGLEROW OFQUERYRESULTSSUMMARIZINGTHEDATAINTHE3!,%32%03TABLE 4HE31,STANDARDSPECIFIESANUMBEROFCOLUMNFUNCTIONS AND$"-3VENDORSHAVE ADDEDMANYMORETOTHEIRPRODUCTS4HESIXMOSTCOMMONLYSUPPORTEDCOLUMNFUNCTIONS ARESHOWNIN&IGURE 4HESECOLUMNFUNCTIONSOFFERDIFFERENTKINDSOFSUMMARYDATA s 35- COMPUTESTHETOTALOFACOLUMN s !6' COMPUTESTHEAVERAGEVALUEINACOLUMN s -). FINDSTHESMALLESTVALUEINACOLUMN s -!8 FINDSTHELARGESTVALUEINACOLUMN s #/5.4 COUNTSTHENUMBEROFVALUESINACOLUMN.5,,VALUESARENOTCOUNTED s #/5.4 COUNTSROWSOFQUERYRESULTS4HISISACTUALLYANALTERNATEFORMOFTHE #/5.4 FUNCTION 4HEARGUMENTTOACOLUMNFUNCTIONCANBEASIMPLECOLUMNNAME ASINTHEPREVIOUS EXAMPLE ORITCANBEA31,EXPRESSION ASSHOWNHERE 7HATISTHEAVERAGESALESPERFORMANCEACROSSALLOFOURSALESPEOPLE 3%,%#4!6' 3!,%315/4! &2/-3!,%32%03 !6' 3!,%315/4!
#HAPTERçç
3UMMARYç1UERIESç
0!24ç))
1, ÊnÓÊ ÕÊvÕVÌÃÊÃÞÌ>ÝÊ`>}À>
4OPROCESSTHISQUERY 31,CONSTRUCTSATEMPORARYCOLUMNCONTAININGTHEVALUEOFTHE EXPRESSION 3!,%315/4! FOREACHROWOFTHE3!,%32%03TABLEANDTHEN COMPUTESTHEAVERAGESOFTHETEMPORARYCOLUMN
#OMPUTINGõAõ#OLUMNõ4OTALõ35- 4HE35- COLUMNFUNCTIONCOMPUTESTHESUMOFACOLUMNOFDATAVALUES4HEDATAINTHE COLUMNMUSTHAVEANUMERICTYPESUCHASINTEGER DECIMAL FLOATINGPOINT ORMONEY 4HERESULTOFTHE35- FUNCTIONHASTHESAMEBASICDATATYPEASTHEDATAINTHECOLUMN BUTTHERESULTMAYHAVEAHIGHERPRECISION&OREXAMPLE IFYOUAPPLYTHE35- FUNCTION TOACOLUMNOF BITINTEGERS ITMAYPRODUCEA BITINTEGERASITSRESULT (EREARESOMEEXAMPLESTHATUSETHE35- COLUMNFUNCTION 7HATARETHETOTALQUOTASANDSALESFORALLSALESPEOPLE 3%,%#435-15/4! 35-3!,%3 &2/-3!,%32%03 35-15/4! 35-3!,%3
ç
0ARTç))ç
2ETRIEVINGç$ATA
7HATISTHETOTALOFTHEORDERSTAKENBY"ILL!DAMS 3%,%#435-!-/5.4 &2/-/2$%23 3!,%32%03 7(%2%.!-%g"ILL!DAMSg !.$2%0%-0,?.5- 35-!-/5.4
#OMPUTINGõAõ#OLUMNõ!VERAGEõ!6' 4HE!6' COLUMNFUNCTIONCOMPUTESTHEAVERAGEOFACOLUMNOFDATAVALUES!SWITHTHE 35- FUNCTION THEDATAINTHECOLUMNMUSTHAVEANUMERICTYPE"ECAUSETHE!6' FUNCTIONADDSTHEVALUESINTHECOLUMNANDTHENDIVIDESBYTHENUMBEROFVALUES ITSRESULT MAYHAVEADIFFERENTDATATYPETHANTHATOFTHEVALUESINTHECOLUMN&OREXAMPLE IFYOU APPLYTHE!6' FUNCTIONTOACOLUMNOFINTEGERS THERESULTWILLBEEITHERADECIMALORA FLOATINGPOINTNUMBER DEPENDINGONTHEBRANDOF$"-3YOUAREUSING (EREARESOMEEXAMPLESOFTHE!6' COLUMNFUNCTION #ALCULATETHEAVERAGEPRICEOFPRODUCTSFROMMANUFACTURER!#) 3%,%#4!6'02)#% &2/-02/$5#43 7(%2%-&2?)$g!#)g !6'02)#%
#ALCULATETHEAVERAGESIZEOFANORDERPLACEDBY!CME-FGCUSTOMERNUMBER 3%,%#4!6'!-/5.4 &2/-/2$%23 7(%2%#534 !6'!-/5.4
&INDINGõ%XTREMEõ6ALUESõ-).õANDõ-!8 4HE-). AND-!8 COLUMNFUNCTIONSFINDTHESMALLESTANDLARGESTVALUESINACOLUMN RESPECTIVELY4HEDATAINTHECOLUMNCANCONTAINNUMERIC STRING ORDATETIMEINFORMATION 4HERESULTOFTHE-). OR-!8 FUNCTIONHASEXACTLYTHESAMEDATATYPEASTHEDATAINTHE COLUMN (EREARESOMEEXAMPLESTHATSHOWTHEUSEOFTHESECOLUMNFUNCTIONS 7HATARETHESMALLESTANDLARGESTASSIGNEDQUOTAS 3%,%#4-).15/4! -!815/4! &2/-3!,%32%03
#HAPTERçç
3UMMARYç1UERIESç
-).15/4! -!815/4!
7HATISTHEEARLIESTORDERDATEINTHEDATABASE 3%,%#4-)./2$%2?$!4% &2/-/2$%23 -)./2$%2?$!4%
3%,%#4-!8 3!,%315/4! &2/-3!,%32%03 -!8 3!,%315/4!
7HENTHE-). AND-!8 COLUMNFUNCTIONSAREAPPLIEDTONUMERICDATA 31, COMPARESTHENUMBERSINALGEBRAICORDERLARGENEGATIVENUMBERSARELESSTHANSMALL NEGATIVENUMBERS WHICHARELESSTHANZERO WHICHISLESSTHANALLPOSITIVENUMBERS $ATES ARECOMPAREDSEQUENTIALLY%ARLIERDATESARESMALLERTHANLATERONES $URATIONSARE COMPAREDBASEDONTHEIRLENGTH3HORTERDURATIONSARESMALLERTHANLONGERONES 7HENUSING-). AND-!8 WITHSTRINGDATA THECOMPARISONOFTWOSTRINGSDEPENDS ONTHECHARACTERSETBEINGUSED/NAPERSONALCOMPUTERORATYPICALSERVER BOTHOFWHICH USETHE!3#))CHARACTERSET DIGITSCOMEBEFORETHELETTERSINTHESORTINGSEQUENCE ANDALLOF THEUPPERCASECHARACTERSCOMEBEFOREALLOFTHELOWERCASECHARACTERS/NMAINFRAMES WHICH USETHE%"#$)#CHARACTERSET THELOWERCASECHARACTERSPRECEDETHEUPPERCASECHARACTERS ANDDIGITSCOMEAFTERTHELETTERS(EREISACOMPARISONOFTHE!3#))AND%"#$)#COLLATING SEQUENCESOFALISTOFSTRINGS FROMSMALLESTTOLARGEST - Ê !"# !"# !#-%-&'° !CME-FG° :%4!#/20° :ETA#ORP° ACMEMFG° ZETACORP°
ACMEMFG° ZETACORP° !CME-FG° !#-%-&'° :ETA#ORP° :%4!#/20° !"# !"#
4HEDIFFERENCEINTHECOLLATINGSEQUENCESMEANSTHATAQUERYWITHAN/2$%2"9CLAUSE CANPRODUCEDIFFERENTRESULTSONTWODIFFERENTSYSTEMS
0!24ç))
7HATISTHEBESTSALESPERFORMANCEOFANYSALESPERSON
ç
0ARTç))ç
2ETRIEVINGç$ATA
)NTERNATIONALCHARACTERSFOREXAMPLE ACCENTEDCHARACTERSIN&RENCH 'ERMAN 3PANISH OR)TALIAN ORTHE#YRILLICALPHABETLETTERSUSEDIN'REEKOR2USSIAN ORTHE+ANJISYMBOLS USEDIN*APANESE POSEADDITIONALPROBLEMS3OMEBRANDSOF$"-3USESPECIALINTERNATIONAL SORTINGALGORITHMSTOSORTTHESECHARACTERSINTOTHEIRCORRECTPOSITIONFOREACHLANGUAGE /THERSSIMPLYSORTTHEMACCORDINGTOTHENUMERICVALUEOFTHECODEASSIGNEDTOTHE CHARACTER4OADDRESSTHESEISSUES THE31,STANDARDINCLUDESELABORATESUPPORTFORNATIONAL CHARACTERSETS USER DEFINEDCHARACTERSETS ANDALTERNATECOLLATINGSEQUENCES5NFORTUNATELY SUPPORTFORTHESE31,FEATURESVARIESWIDELYAMONGPOPULAR$"-3PRODUCTS)FYOUR APPLICATIONINVOLVESINTERNATIONALTEXT YOUWILLWANTTOEXPERIMENTWITHYOURPARTICULAR $"-3TOFINDOUTHOWITHANDLESTHESECHARACTERS
#OUNTINGõ$ATAõ6ALUESõ#/5.4 4HE#/5.4 COLUMNFUNCTIONCOUNTSTHENUMBEROFDATAVALUESINACOLUMN4HEDATAIN THECOLUMNCANBEOFANYTYPE4HE#/5.4 FUNCTIONALWAYSRETURNSANINTEGER REGARDLESS OFTHEDATATYPEOFTHECOLUMN(EREARESOMEEXAMPLESOFQUERIESTHATUSETHE#/5.4 COLUMNFUNCTION (OWMANYCUSTOMERSARETHERE 3%,%#4#/5.4#534?.5- &2/-#534/-%23 #/5.4#534?.5-
(OWMANYSALESPEOPLEAREOVERQUOTA 3%,%#4#/5.4.!-% &2/-3!,%32%03 7(%2%3!,%315/4! #/5.4.!-%
(OWMANYORDERSFORMORETHAN AREONTHEBOOKS 3%,%#4#/5.4!-/5.4 &2/-/2$%23 7(%2%!-/5.4 #/5.4!-/5.4
.OTETHATTHE#/5.4 FUNCTIONTHATINCLUDESACOLUMNNAMEDOESNOTCOUNT.5,, VALUESINTHATCOLUMN BUT#/5.4 COUNTSALLROWSREGARDLESSOFCOLUMNVALUES!SIDE FROM.5,,VALUES HOWEVER #/5.4 IGNORESTHEVALUESOFTHEDATAITEMSINTHECOLUMNIT SIMPLYCOUNTSHOWMANYDATAITEMSTHEREARE!SARESULT ITDOESNTREALLYMATTERWHICH
#HAPTERçç
3UMMARYç1UERIESç
COLUMNYOUSPECIFYASTHEARGUMENTOFTHE#/5.4 FUNCTION4HELASTEXAMPLECOULDJUST ASWELLHAVEBEENWRITTENTHISWAY 3%,%#4#/5.4/2$%2?.5- &2/-/2$%23 7(%2%!-/5.4 #/5.4/2$%2?.5-
3%,%#4#/5.4 &2/-/2$%23 7(%2%!-/5.4 #/5.4
)FYOUTHINKOFTHE#/5.4 FUNCTIONASAhROWCOUNTvFUNCTION ITMAKESTHEQUERY EASIERTOREAD)NPRACTICE THE#/5.4 FUNCTIONISALMOSTALWAYSUSEDINSTEADOFTHE #/5.4 FUNCTIONTOCOUNTROWS
#OLUMNõ&UNCTIONSõINõTHEõ3ELECTõ,IST 3IMPLEQUERIESWITHACOLUMNFUNCTIONINTHEIRSELECTLISTAREFAIRLYEASYTOUNDERSTAND (OWEVER WHENTHESELECTLISTINCLUDESSEVERALCOLUMNFUNCTIONS ORWHENTHEARGUMENTTOA COLUMNFUNCTIONISACOMPLEXEXPRESSION THEQUERYCANBEHARDERTOREADANDUNDERSTAND 4HEFOLLOWINGSTEPSSHOWTHERULESFOR31,QUERYPROCESSINGEXPANDEDONCEMORETO DESCRIBEHOWCOLUMNFUNCTIONSAREHANDLED!SBEFORE THERULESAREINTENDEDTOPROVIDEA PRECISEDEFINITIONOFWHATAQUERYMEANS NOTADESCRIPTIONOFHOWTHE$"-3ACTUALLYGOES ABOUTPRODUCINGTHEQUERYRESULTS 4OGENERATETHEQUERYRESULTSFORA3%,%#4STATEMENT
)FTHESTATEMENTISA5.)/.OF3%,%#4STATEMENTS APPLY3TEPSTHROUGHTOEACH OFTHESTATEMENTSTOGENERATETHEIRINDIVIDUALQUERYRESULTS
&ORMTHEPRODUCTOFTHETABLESNAMEDINTHE&2/-CLAUSE)FTHE&2/-CLAUSENAMES ASINGLETABLE THEPRODUCTISTHATTABLE
)FTHEREISA7(%2%CLAUSE APPLYITSSEARCHCONDITIONTOEACHROWOFTHEPRODUCT TABLE RETAININGTHOSEROWSFORWHICHTHESEARCHCONDITIONIS425%ANDDISCARDING THOSEFORWHICHITIS&!,3%OR.5,,
&OREACHREMAININGROW CALCULATETHEVALUEOFEACHITEMINTHESELECTLISTTOPRODUCEA SINGLEROWOFQUERYRESULTS&ORASIMPLECOLUMNREFERENCE USETHEVALUEOFTHECOLUMN INTHECURRENTROW&ORACOLUMNFUNCTION USETHEENTIRESETOFROWSASITSARGUMENT
0!24ç))
)NFACT ITSAWKWARDTOTHINKOFTHEQUERYAShCOUNTINGHOWMANYORDERAMOUNTSvOR hCOUNTINGHOWMANYORDERNUMBERSvITSMUCHEASIERTOTHINKABOUThCOUNTINGHOWMANY ORDERSv&ORTHISREASON 31,SUPPORTSASPECIAL#/5.4 COLUMNFUNCTION WHICHCOUNTS ROWSRATHERTHANDATAVALUES(EREISTHESAMEQUERY REWRITTENONCEAGAINTOUSETHE #/5.4 FUNCTION
ç
0ARTç))ç
2ETRIEVINGç$ATA
)F3%,%#4$)34).#4ISSPECIFIED ELIMINATEANYDUPLICATEROWSOFQUERYRESULTS THATWEREPRODUCED
)FTHESTATEMENTISA5.)/.OF3%,%#4STATEMENTS MERGETHEQUERYRESULTSFORTHE INDIVIDUALSTATEMENTSINTOASINGLETABLEOFQUERYRESULTS%LIMINATEDUPLICATEROWS UNLESS5.)/.!,,ISSPECIFIED
)FTHEREISAN/2$%2"9CLAUSE SORTTHEQUERYRESULTSASSPECIFIED
4HEROWSGENERATEDBYTHISPROCEDURECOMPRISETHEQUERYRESULTS /NEOFTHEBESTWAYSTOTHINKABOUTSUMMARYQUERIESANDCOLUMNFUNCTIONSISTOIMAGINE THEQUERYPROCESSINGBROKENDOWNINTOTWOSTEPS&IRST YOUSHOULDIMAGINEHOWTHEQUERY WOULDWORKWITHOUTTHECOLUMNFUNCTIONS PRODUCINGMANYROWSOFDETAILEDQUERYRESULTS 4HENYOUSHOULDIMAGINE31,APPLYINGTHECOLUMNFUNCTIONSTOTHEDETAILEDQUERYRESULTS PRODUCINGASINGLESUMMARYROW&OREXAMPLE CONSIDERTHEFOLLOWINGCOMPLEXQUERY &INDTHEAVERAGEORDERAMOUNT TOTALORDERAMOUNT AVERAGEORDERAMOUNTASAPERCENTAGEOFTHE CUSTOMERSCREDITLIMIT ANDAVERAGEORDERAMOUNTASAPERCENTAGEOFTHESALESPERSONSQUOTA 3%,%#4!6'!-/5.4 35-!-/5.4 !6'!-/5.4#2%$)4?,)-)4 !6'!-/5.415/4! &2/-/2$%23 #534/-%23 3!,%32%03 7(%2%#534#534?.5- !.$2%0%-0,?.5- !6'!-/5.4 35-!-/5.4 !6'!-/5.4#2%$)4?,)-)4
!6'!-/5.415/4!
.OTETHATTHEROWSIZEINTHEQUERYRESULTSISRATHERLARGEBECAUSEOFTHEVERYLONGCOLUMN HEADINGS)FYOUAREUSINGAN31,CLIENTTHATRESTRICTSQUERYRESULTROWSTOCHARACTERSOR LESS EACHROWWILLWRAPTOMULTIPLELINESANDITWONTBENEARLYASREADABLEASWHATISSHOWN HERE9OUWILLLATERLEARNHOWTOADDACOLUMNALIASTOTHEQUERYRESULTSTOELIMINATETHELONG COLUMNHEADINGSGENERATEDBYTHE$"-3WHENCOLUMNFUNCTIONSAREUSED 7ITHOUTTHECOLUMNFUNCTIONS ITWOULDLOOKLIKETHIS 3%,%#4!-/5.4 !-/5.4 !-/5.4#2%$)4?,)-)4 !-/5.415/4! &2/-/2$%23 #534/-%23 3!,%32%03 7(%2%#534#534?.5-!.$ !.$2%0%-0,?.5-
ANDWOULDPRODUCEONEROWOFDETAILEDQUERYRESULTSFOREACHORDER4HECOLUMNFUNCTIONS USETHECOLUMNSOFTHISDETAILEDQUERYRESULTSTABLETOGENERATEASINGLE ROWTABLEOF SUMMARYQUERYRESULTS !COLUMNFUNCTIONCANAPPEARINA31,STATEMENTANYWHERETHATACOLUMNNAMECAN APPEAR)TCAN FOREXAMPLE BEPARTOFANEXPRESSIONTHATADDSORSUBTRACTSTHEVALUESOF TWOCOLUMNFUNCTIONS(OWEVER INSOME31,IMPLEMENTATIONS PARTICULARLYOLDERONES BASEDONTHE31,STANDARD THEARGUMENTOFACOLUMNFUNCTIONCANNOTCONTAINANOTHER
#HAPTERçç
3UMMARYç1UERIESç
COLUMNFUNCTION BECAUSETHERESULTINGEXPRESSIONDOESNTMAKESENSE4HISRULEIS SOMETIMESSUMMARIZEDAShITSILLEGALTONESTCOLUMNFUNCTIONSv )TSALSOILLEGALTOMIXCOLUMNFUNCTIONSANDORDINARYCOLUMNNAMESINASELECTLIST EXCEPTINGROUPEDQUERIESANDSUBQUERIESASDESCRIBEDINTHEh'ROUPED1UERIESvSECTION LATERINTHISCHAPTER AGAINBECAUSETHERESULTINGQUERYDOESNTMAKESENSE&OREXAMPLE CONSIDERTHISQUERY 3%,%#4.!-% 35-3!,%3 &2/-3!,%32%03
.5,,õ6ALUESõANDõ#OLUMNõ&UNCTIONS 4HE35- !6' -). -!8 AND#/5.4 COLUMNFUNCTIONSEACHTAKEACOLUMNOF DATAVALUESASTHEIRARGUMENTANDPRODUCEASINGLEDATAVALUEASARESULT7HATHAPPENSIF ONEORMOREOFTHEDATAVALUESINTHECOLUMNISA.5,,VALUE4HE!.3))3/31,STANDARD SPECIFIESTHAT.5,,VALUESINTHECOLUMNAREIGNOREDBYTHECOLUMNFUNCTIONS 4HISQUERYSHOWSHOWTHE#/5.4 COLUMNFUNCTIONIGNORESANY.5,,VALUESINA COLUMN 3%,%#4#/5.4 #/5.43!,%3 #/5.415/4! &2/-3!,%32%03 #/5.4 #/5.43!,%3 #/5.415/4!
4HE3!,%32%03TABLECONTAINSTENROWS SO#/5.4 RETURNSACOUNTOFTEN4HE 3!,%3COLUMNCONTAINSTENNON .5,,VALUES SOTHEFUNCTION#/5.43!,%3 ALSORETURNSA COUNTOFTEN4HE15/4!COLUMNIS.5,,FORTHENEWESTSALESPERSON4HE#/5.415/4! FUNCTIONIGNORESTHIS.5,,VALUEANDRETURNSACOUNTOFNINE"ECAUSEOFTHESEANOMALIES THE#/5.4 FUNCTIONISALMOSTALWAYSUSEDINSTEADOFTHE#/5.4 FUNCTION UNLESSYOU SPECIFICALLYWANTTOEXCLUDE.5,,VALUESINAPARTICULARCOLUMNFROMTHETOTAL )GNORING.5,,VALUESHASLITTLEIMPACTONTHE-). AND-!8 COLUMNFUNCTIONS (OWEVER ITCANCAUSESUBTLEPROBLEMSFORTHE35- AND!6' COLUMNFUNCTIONS AS ILLUSTRATEDBYTHISQUERY 3%,%#435-3!,%3 35-15/4! 35-3!,%3 35-15/4! 35-3!,%3 15/4! &2/-3!,%32%03 35-3!,%3 35-15/4! 35-3!,%3 35-15/4! 35-3!,%3 15/4!
0!24ç))
4HEFIRSTSELECTITEMASKS31,TOGENERATEAMULTIROWTABLEOFDETAILEDQUERYRESULTSONE ROWFOREACHSALESPERSON4HESECONDSELECTITEMASKS31,TOGENERATEAONE ROWCOLUMNOF SUMMARYQUERYRESULTSCONTAININGTHETOTALOFTHE3!,%3COLUMN4HETWO3%,%#4ITEMS CONTRADICTEACHOTHER PRODUCINGANERROR&ORTHISREASON EITHERALLCOLUMNREFERENCESINTHE SELECTLISTMUSTAPPEARWITHINTHEARGUMENTOFACOLUMNFUNCTIONPRODUCINGASUMMARY QUERY ORTHESELECTLISTMUSTNOTCONTAINANYCOLUMNFUNCTIONSPRODUCINGADETAILEDQUERY EXCEPTASDESCRIBEDINTHEh'ROUPED1UERIESvSECTIONLATERINTHISCHAPTER
ç
0ARTç))ç
2ETRIEVINGç$ATA
9OUWOULDEXPECTTHETWOEXPRESSIONS 35-3!,%3 35-15/4! !.$35-3!,%3 15/4!
INTHESELECTLISTTOPRODUCEIDENTICALRESULTS BUTTHEEXAMPLESHOWSTHATTHEYDONOT4HE SALESPERSONWITHA.5,,VALUEINTHE15/4!COLUMNISAGAINTHEREASON4HEEXPRESSION 35-3!,%3
TOTALSTHESALESFORALLTENSALESPEOPLE WHILETHEEXPRESSION 35-15/4!
TOTALSONLYTHENINENON .5,,QUOTAVALUES4HEEXPRESSION 35-3!,%3 35-15/4!
COMPUTESTHEDIFFERENCEOFTHESETWOAMOUNTS(OWEVER THECOLUMNFUNCTION 35-3!,%3 15/4!
HASANON .5,,ARGUMENTVALUEFORONLYNINEOFTHETENSALESPEOPLE)NTHEROWWITHA.5,, QUOTAVALUE THESUBTRACTIONPRODUCESA.5,, WHICHISIGNOREDBYTHE35- FUNCTION 4HUS THESALESFORTHESALESPERSONWITHOUTAQUOTA WHICHAREINCLUDEDINTHEPREVIOUS CALCULATION AREEXCLUDEDFROMTHISCALCULATION 7HICHISTHEhCORRECTvANSWER"OTHARE4HEFIRSTEXPRESSIONCALCULATESEXACTLYWHATIT SAYShTHESUMOF3!,%3 LESSTHESUMOF15/4!v4HESECONDEXPRESSIONALSOCALCULATES EXACTLYWHATITSAYShTHESUMOF3!,%3n15/4! v7HEN.5,,VALUESOCCUR HOWEVER THE TWOCALCULATIONSARENOTQUITETHESAME 4HE!.3))3/31,STANDARDSPECIFIESTHESEPRECISERULESFORHANDLING.5,,VALUESIN COLUMNFUNCTIONS s )FANYOFTHEDATAVALUESINACOLUMNARE.5,, THEYAREIGNOREDFORTHEPURPOSEOF COMPUTINGTHECOLUMNFUNCTIONSVALUE s )FEVERYDATAITEMINTHECOLUMNIS.5,, THENTHE35- !6' -). AND-!8 COLUMNFUNCTIONSRETURNA.5,,VALUETHE#/5.4 FUNCTIONRETURNSAVALUEOFZERO s )FNODATAITEMSAREINTHECOLUMNTHATIS THECOLUMNISEMPTY THENTHE35- !6' -). AND-!8 COLUMNFUNCTIONSRETURNA.5,,VALUETHE#/5.4 FUNCTIONRETURNSAVALUEOFZERO s 4HE#/5.4 COUNTSROWSANDDOESNOTDEPENDONTHEPRESENCEORABSENCEOF .5,,VALUESINACOLUMN)FTHEREARENOROWS ITRETURNSAVALUEOFZERO !LTHOUGHTHESTANDARDISVERYCLEARINTHISAREA COMMERCIAL31,PRODUCTSMAYPRODUCE RESULTSDIFFERENTFROMTHESTANDARD ESPECIALLYIFALLOFTHEDATAVALUESINACOLUMNARE.5,, ORWHENACOLUMNFUNCTIONISAPPLIEDTOANEMPTYTABLE"EFOREASSUMINGITWILLBEHAVEAS SPECIFIEDBYTHESTANDARD YOUSHOULDTESTYOURPARTICULAR$"-3
#HAPTERçç
3UMMARYç1UERIESç
$UPLICATEõ2OWõ%LIMINATIONõ$)34).#4 2ECALLFROM#HAPTERTHATYOUCANSPECIFYTHE$)34).#4KEYWORDATTHEBEGINNINGOFTHE SELECTLISTTOELIMINATEDUPLICATEROWSOFQUERYRESULTS9OUCANALSOASK31,TOELIMINATE DUPLICATEVALUESFROMACOLUMNBEFOREAPPLYINGACOLUMNFUNCTIONTOIT4OELIMINATE DUPLICATEVALUES THEKEYWORD$)34).#4ISINCLUDEDBEFORETHECOLUMNFUNCTIONARGUMENT IMMEDIATELYAFTERTHEOPENINGPARENTHESIS (EREARETWOQUERIESTHATILLUSTRATEDUPLICATEROWELIMINATIONFORCOLUMNFUNCTIONS (OWMANYDIFFERENTTITLESAREHELDBYSALESPEOPLE
(OWMANYSALESOFFICESHAVESALESPEOPLEWHOAREOVERQUOTA 3%,%#4#/5.4$)34).#42%0?/&&)#% &2/-3!,%32%03 7(%2%3!,%315/4! #/5.4$)34).#42%0?/&&)#%
4HE$)34).#4KEYWORDCANBESPECIFIEDONLYONCEINAQUERY)FITAPPEARSINTHE ARGUMENTOFONECOLUMNFUNCTION ITCANTAPPEARINANYOTHER)FITISSPECIFIEDBEFORETHE SELECTLIST ITCANTAPPEARINANYCOLUMNFUNCTIONS4HEONLYEXCEPTIONISTHAT$)34).#4 MAYBESPECIFIEDASECONDTIMEINSIDEASUBQUERYCONTAINEDWITHINTHEQUERY 3UBQUERIES AREDESCRIBEDIN#HAPTER
'ROUPEDõ1UERIESõ'2/50õ"9õ#LAUSE 4HESUMMARYQUERIESDESCRIBEDTHUSFARARELIKETHETOTALSATTHEBOTTOMOFAREPORT4HEY CONDENSEALLOFTHEDETAILEDDATAINTHEREPORTINTOASINGLE SUMMARYROWOFDATA*USTAS SUBTOTALSAREUSEFULINPRINTEDREPORTS ITSOFTENCONVENIENTTOSUMMARIZEQUERYRESULTSATA hSUBTOTALvLEVEL4HE'2/50"9CLAUSEOFTHE3%,%#4STATEMENTPROVIDESTHISCAPABILITY 4HEFUNCTIONOFTHE'2/50"9CLAUSEISMOSTEASILYUNDERSTOODBYEXAMPLE#ONSIDER THESETWOQUERIES 7HATISTHEAVERAGEORDERSIZE 3%,%#4!6'!-/5.4 &2/-/2$%23 !6'!-/5.4
0!24ç))
3%,%#4#/5.4$)34).#44)4,% &2/-3!,%32%03 #/5.4$)34).#44)4,%
ç
0ARTç))ç
2ETRIEVINGç$ATA
7HATISTHEAVERAGEORDERSIZEFOREACHSALESPERSON 3%,%#42%0 !6'!-/5.4 &2/-/2$%23 '2/50"92%0 2%0!6'!-/5.4
4HEFIRSTQUERYISASIMPLESUMMARYQUERYLIKETHEPREVIOUSEXAMPLESINTHISCHAPTER 4HESECONDQUERYPRODUCESSEVERALSUMMARYROWSONEROWFOREACHGROUP SUMMARIZING THEORDERSTAKENBYASINGLESALESPERSON&IGURE SHOWSHOWTHESECONDQUERYWORKS #ONCEPTUALLY 31,CARRIESOUTTHEQUERYASFOLLOWS
31,DIVIDESTHEORDERSINTOGROUPSOFORDERS WITHONEGROUPFOREACHSALESPERSON 7ITHINEACHGROUP ALLOFTHEORDERSHAVETHESAMEVALUEINTHE2%0COLUMN
"#%$
"#%$ !
)
) )
) ) )
1, ÊnÎÊ Ê}ÀÕ«i`ʵÕiÀÞÊÊ«iÀ>Ì
$&(%'&
) ) )
#HAPTERçç
3UMMARYç1UERIESç
&OREACHGROUP 31,COMPUTESTHEAVERAGEVALUEOFTHE!-/5.4COLUMNFORALLOF THEROWSINTHEGROUPANDGENERATESASINGLE SUMMARYROWOFQUERYRESULTS4HE ROWCONTAINSTHEVALUEOFTHE2%0COLUMNFORTHEGROUPANDTHECALCULATEDAVERAGE ORDERSIZE
!QUERYTHATINCLUDESTHE'2/50"9CLAUSEISCALLEDAGROUPEDQUERYBECAUSEITGROUPS THEDATAFROMITSSOURCETABLESANDPRODUCESASINGLESUMMARYROWFOREACHROWGROUP4HE COLUMNSNAMEDINTHE'2/50"9CLAUSEARECALLEDTHEGROUPINGCOLUMNSOFTHEQUERY BECAUSE THEYDETERMINEHOWTHEROWSAREDIVIDEDINTOGROUPS(EREARESOMEADDITIONALEXAMPLES OFGROUPEDQUERIES
3%,%#42%0?/&&)#% -).15/4! -!815/4! &2/-3!,%32%03 '2/50"92%0?/&&)#% 2%0?/&&)#%-).15/4! -!815/4!
.5,,.5,,.5,,
(OWMANYSALESPEOPLEAREASSIGNEDTOEACHOFFICE 3%,%#42%0?/&&)#% #/5.4 &2/-3!,%32%03 '2/50"92%0?/&&)#% 2%0?/&&)#%#/5.4
.5,,
(OWMANYDIFFERENTCUSTOMERSARESERVEDBYEACHSALESPERSON 3%,%#4#/5.4$)34).#4#534?.5- gCUSTOMERSFORSALESREPg #534?2%0 &2/-#534/-%23 '2/50"9#534?2%0 #/5.4$)34).#4#534?.5- #534/-%23&/23!,%32%0#534?2%0
CUSTOMERSFORSALESREP CUSTOMERSFORSALESREP CUSTOMERSFORSALESREP CUSTOMERSFORSALESREP
0!24ç))
7HATISTHERANGEOFASSIGNEDQUOTASINEACHOFFICE
ç
0ARTç))ç
2ETRIEVINGç$ATA
CUSTOMERSFORSALESREP CUSTOMERSFORSALESREP
4HEREISANINTIMATELINKBETWEENTHE31,COLUMNFUNCTIONSANDTHE'2/50"9CLAUSE 2EMEMBERTHATTHECOLUMNFUNCTIONSTAKEACOLUMNOFDATAVALUESANDPRODUCEASINGLE RESULT7HENTHE'2/50"9CLAUSEISPRESENT ITTELLS31,TODIVIDETHEDETAILEDQUERYRESULTS INTOGROUPSANDTOAPPLYTHECOLUMNFUNCTIONSEPARATELYTOEACHGROUP PRODUCINGASINGLE RESULTFOREACHGROUP4HEFOLLOWINGSTEPSSHOWTHERULESFOR31,QUERYPROCESSING EXPANDEDONCEAGAINFORGROUPEDQUERIES 4OGENERATETHEQUERYRESULTSFORA3%,%#4STATEMENT
)FTHESTATEMENTISA5.)/.OF3%,%#4STATEMENTS APPLY3TEPSTHROUGHTOEACH OFTHESTATEMENTSTOGENERATETHEIRINDIVIDUALQUERYRESULTS
&ORMTHEPRODUCTOFTHETABLESNAMEDINTHE&2/-CLAUSE)FTHE&2/-CLAUSENAMES ASINGLETABLE THEPRODUCTISTHATTABLE
)FTHEREISA7(%2%CLAUSE APPLYITSSEARCHCONDITIONTOEACHROWOFTHEPRODUCT TABLE RETAININGTHOSEROWSFORWHICHTHESEARCHCONDITIONIS425%ANDDISCARDING THOSEFORWHICHITIS&!,3%OR.5,,
)FTHEREISA'2/50"9CLAUSE ARRANGETHEREMAININGROWSOFTHEPRODUCTTABLEINTO ROWGROUPS SOTHATTHEROWSINEACHGROUPHAVEIDENTICALVALUESINALLOFTHE GROUPINGCOLUMNS
)FTHEREISA(!6).'CLAUSE APPLYITSSEARCHCONDITIONTOEACHROWGROUP RETAINING THOSEGROUPSFORWHICHTHESEARCHCONDITIONIS425%ANDDISCARDINGTHOSEFOR WHICHITIS&!,3%OR.5,,
&OREACHREMAININGROWORROWGROUP CALCULATETHEVALUEOFEACHITEMINTHESELECT LISTTOPRODUCEASINGLEROWOFQUERYRESULTS&ORASIMPLECOLUMNREFERENCE USETHE VALUEOFTHECOLUMNINTHECURRENTROWORROWGROUP &ORACOLUMNFUNCTION USE THECURRENTROWGROUPASITSARGUMENTIF'2/50"9ISSPECIFIEDOTHERWISE USETHE ENTIRESETOFROWS
)F3%,%#4$)34).#4ISSPECIFIED ELIMINATEANYDUPLICATEROWSOFQUERYRESULTS THATWEREPRODUCED
)FTHESTATEMENTISA5.)/.OF3%,%#4STATEMENTS MERGETHEQUERYRESULTSFORTHE INDIVIDUALSTATEMENTSINTOASINGLETABLEOFQUERYRESULTS%LIMINATEDUPLICATEROWS UNLESS5.)/.!,,ISSPECIFIED
)FTHEREISAN/2$%2"9CLAUSE SORTTHEQUERYRESULTSASSPECIFIED 4HEROWSGENERATEDBYTHISPROCEDURECOMPRISETHEQUERYRESULTS
-ULTIPLEõ'ROUPINGõ#OLUMNS 31,CANGROUPQUERYRESULTSBASEDONTHECONTENTSOFTWOORMORECOLUMNS&OREXAMPLE SUPPOSEYOUWANTTOGROUPTHEORDERSBYSALESPERSONANDBYCUSTOMER4HISQUERYGROUPS THEDATABASEDONBOTHCRITERIA
#HAPTERçç
3UMMARYç1UERIESç
#ALCULATETHETOTALORDERSFOREACHCUSTOMEROFEACHSALESPERSON
%VENWITHMULTIPLEGROUPINGCOLUMNS OLDER31,VERSIONSPROVIDEONLYASINGLELEVELOF GROUPING4HEQUERYPRODUCESASEPARATESUMMARYROWFOREACHSALESPERSONCUSTOMER PAIR4OPRODUCEMORETHANONELEVELOFSUBTOTALSINMOREMODERN31, YOUCANUSETHE 7)4(2/,,50AND7)4(#5"%OPERATORSINCOMBINATIONWITHTHE'2/50"9OPERATOR 7)4(2/,,50CAUSESTHE'2/50"9OPERATIONTODISPLAYASUBTOTALFOREACHLEVELOF GROUPINGWORKINGLEFTTORIGHTACROSSTHELISTOFGROUPINGCOLUMNS7)4(#5"%GOESFURTHER BYSHOWINGSUBTOTALSFOREVERYPOSSIBLECOMBINATIONOFGROUPINGCOLUMNS7)4(#5"%AND 7)4(2/,,50ALSOPROVIDEAGRANDTOTALINTHERESULTSET BUTTHEGRANDTOTALMIGHTNOT ALWAYSAPPEARATTHEENDOFTHERESULTSET/RACLES#5"%OPTION FOREXAMPLE DISPLAYSTHE GRANDTOTALFIRST9OUCANSPOTTHESUBTOTALROWSBECAUSEGROUPINGCOLUMNSTHATDONTAPPLY ARE.5,,3IMILARLY THEGRANDTOTALLINEWILLHAVE.5,,VALUESINALLOFTHEGROUPING COLUMNS #ALCULATETHETOTALORDERSFOREACHCUSTOMEROFEACHSALESPERSONWITHSUBTOTALSFOREACHSALESPERSON 3%,%#42%0 #534 35-!-/5.4 &2/-/2$%23 '2/50"92%0 #5347)4(2/,,50 2%0#53435-!-/5.4
0!24ç))
3%,%#42%0 #534 35-!-/5.4 &2/-/2$%23 '2/50"92%0 #534 2%0#53435-!-/5.4
ç
0ARTç))ç
2ETRIEVINGç$ATA
#ALCULATETHETOTALORDERSFOREACHCUSTOMEROFEACHSALESPERSONWITHSUBTOTALSFOREACHSALESPERSON ANDEACHCUSTOMER 3%,%#42%0 #534 35-!-/5.4 &2/-/2$%23 '2/50"92%0 #5347)4(#5"% 2%0#53435-!-/5.4
#HAPTERçç
3UMMARYç1UERIESç
#ALCULATETHETOTALORDERSFOREACHCUSTOMEROFEACHSALESPERSON SORTEDBYCUSTOMER ANDWITHINEACH CUSTOMERBYSALESPERSON 3%,%#4#534 2%0 35-!-/5.4 &2/-/2$%23 '2/50"9#534 2%0 /2$%2"9#534 2%0 #5342%035-!-/5.4
2ESTRICTIONSõONõ'ROUPEDõ1UERIES 'ROUPEDQUERIESARESUBJECTTOSOMERATHERSTRICTLIMITATIONS4HEGROUPINGCOLUMNSMUST BEACTUALCOLUMNSOFTHETABLESNAMEDINTHE&2/-CLAUSEOFTHEQUERY(OWEVER SOME IMPLEMENTATIONSALSOPERMITCOLUMNEXPRESSIONSANDEVENALLOWYOUTOGROUPON EXPRESSIONSBYSIMPLYREPEATINGTHECOLUMNEXPRESSIONINTHE'2/50"9CLAUSE 4HEREAREALSORESTRICTIONSONTHEITEMSTHATCANAPPEARINTHESELECTLISTOFAGROUPED QUERY!LLOFTHEITEMSINTHESELECTLISTMUSTHAVEASINGLEVALUEFOREACHGROUPOFROWS "ASICALLY THISMEANSTHATASELECTITEMINAGROUPEDQUERYCANBE s !COLUMNPROVIDEDITISONEOFTHEGROUPINGCOLUMNS s !CONSTANT s !COLUMNFUNCTION WHICHPRODUCESASINGLEVALUESUMMARIZINGTHEROWSINTHEGROUP
0!24ç))
4HESYNTAXFOR7)4(2/,,50AND7)4(#5"%VARIESSOMEWHATFROMONE31,PRODUCTTO ANOTHER SOCHECKYOURVENDORSDOCUMENTATION4HE31,STANDARDSYNTAX WHICHISSUPPORTED BY31,3ERVER $"5NIVERSAL$ATABASE5$" AND-Y31, ISSHOWNINTHEPRECEDING EXAMPLES(OWEVER ASOFVERSION -Y31,DOESNOTYETSUPPORT7)4(#5"% /RACLE REQUIRESTHEKEYWORDS'2/50"92/,,50OR'2/50"9#5"%FOLLOWEDBYTHEGROUPING COLUMNLIST WHICHMUSTBEENCLOSEDINPARENTHESES SUCHAS'2/50"9#5"%2%0 #534 $"5$"SUPPORTSBOTHTHESTANDARDSYNTAXANDTHEVARIATIONREQUIREDBY/RACLE )FYOUR31,IMPLEMENTATIONDOESNOTSUPPORT2/,,50OR#5"% THEBESTYOUCANDOIS SORTTHEDATASOTHATTHEROWSOFQUERYRESULTSAPPEARINTHEAPPROPRIATEORDER)NMANY31, IMPLEMENTATIONS THE'2/50"9CLAUSEWILLAUTOMATICALLYHAVETHESIDE EFFECTOFSORTINGTHE DATA BUTYOUCANOVERRIDETHISSORTWITHAN/2$%2"9CLAUSE ASSHOWNNEXT
ç
0ARTç))ç
2ETRIEVINGç$ATA
s !GROUPINGCOLUMN WHICHBYDEFINITIONHASTHESAMEVALUEINEVERYROWOFTHEGROUP s !NEXPRESSIONINVOLVINGCOMBINATIONSOFTHESE )NPRACTICE AGROUPEDQUERYWILLALWAYSINCLUDEBOTHAGROUPINGCOLUMNANDACOLUMN FUNCTIONINITSSELECTLIST)FNOCOLUMNFUNCTIONAPPEARS THEQUERYCANBEEXPRESSEDMORE SIMPLYUSING3%,%#4$)34).#4 WITHOUT'2/50"9#ONVERSELY IFYOUDONTINCLUDEA GROUPINGCOLUMNINTHEQUERYRESULTS YOUWONTBEABLETOTELLWHICHROWOFQUERYRESULTS CAMEFROMWHICHGROUP !NOTHERLIMITATIONOFGROUPEDQUERIESISTHAT31,IGNORESINFORMATIONABOUTPRIMARY KEYSANDFOREIGNKEYSWHENANALYZINGTHEVALIDITYOFAGROUPEDQUERY#ONSIDERTHISQUERY WHICHPRODUCESANERROR #ALCULATETHETOTALORDERSFOREACHSALESPERSON 3%,%#4%-0,?.5- .!-% 35-!-/5.4 &2/-/2$%23 3!,%32%03 7(%2%2%0%-0,?.5- '2/50"9%-0,?.5- %RROR.!-%NOTA'2/50"9EXPRESSION
'IVENTHENATUREOFTHEDATA THEQUERYMAKESPERFECTLYGOODSENSE BECAUSEGROUPING ONTHESALESPERSONSEMPLOYEENUMBERISINEFFECTTHESAMEASGROUPINGONTHESALESPERSONS NAME-OREPRECISELY %-0,?.5- THEGROUPINGCOLUMN ISTHEPRIMARYKEYOFTHE 3!,%32%03TABLE SOTHE.!-%COLUMNMUSTBESINGLE VALUEDFOREACHGROUP.ONETHELESS 31,REPORTSANERRORBECAUSETHE.!-%COLUMNISNOTEXPLICITLYSPECIFIEDASAGROUPING COLUMN4HEEXACTERRORMESSAGEWILLVARYFROMONE$"-3PRODUCTTOANOTHER 4OCORRECT THEPROBLEM YOUCANSIMPLYINCLUDETHE.!-%COLUMNASASECONDREDUNDANT GROUPING COLUMN #ALCULATETHETOTALORDERSFOREACHSALESPERSON 3%,%#4%-0,?.5- .!-% 35-!-/5.4 &2/-/2$%23 3!,%32%03 7(%2%2%0%-0,?.5- '2/50"9%-0,?.5- .!-% %-0,?.5-.!-%35-!-/5.4
$AN2OBERTS 3UE3MITH 0AUL#RUZ "ILL!DAMS 3AM#LARK .ANCY!NGELLI ,ARRY&ITCH -ARY*ONES 4OM3NYDER
/FCOURSE IFTHESALESPERSONSEMPLOYEENUMBERISNOTNEEDEDINTHEQUERYRESULTS YOU CANELIMINATEITENTIRELYFROMTHESELECTLIST
#HAPTERçç
3UMMARYç1UERIESç
#ALCULATETHETOTALORDERSFOREACHSALESPERSON
.5,,õ6ALUESõINõ'ROUPINGõ#OLUMNS !.5,,VALUEPOSESASPECIALPROBLEMWHENITOCCURSINAGROUPINGCOLUMN)FTHEVALUEOF THECOLUMNISUNKNOWN INTOWHICHGROUPSHOULDTHEROWBEPLACED)NTHE7(%2%CLAUSE WHENTWODIFFERENT.5,,VALUESARECOMPARED THERESULTIS.5,,NOT425% THATIS THE TWO.5,,VALUESARENOTCONSIDEREDTOBEEQUAL!PPLYINGTHESAMECONVENTIONTOTHE '2/50"9CLAUSEWOULDFORCE31,TOPLACEEACHROWWITHA.5,,GROUPINGCOLUMNINTOA SEPARATEGROUPBYITSELF )NPRACTICE THISRULEPROVESTOOUNWIELDY)NSTEAD THE!.3))3/31,STANDARD CONSIDERSTWO.5,,VALUESTOBEEQUALFORPURPOSESOFTHE'2/50"9CLAUSE)FTWOROWS HAVE.5,,SINTHESAMEGROUPINGCOLUMNSANDIDENTICALVALUESINALLOFTHEIRNON .5,, GROUPINGCOLUMNS THEYAREGROUPEDTOGETHERINTOTHESAMEROWGROUP4HESMALLSAMPLE TABLEIN&IGURE ILLUSTRATESTHE!.3))3/HANDLINGOF.5,,VALUESBYTHE'2/50"9 CLAUSE ASSHOWNINTHISQUERY 3%,%#4(!)2 %9%3 #/5.4 &2/-0%/0,% '2/50"9(!)2 %9%3 (!)2%9%3#/5.4
"ROWN"LUE .5,,"LUE .5,,.5,, "ROWN.5,, "ROWN"ROWN "ROWN"ROWN
!LTHOUGHTHISBEHAVIOROF.5,,SINGROUPINGCOLUMNSISCLEARLYSPECIFIEDINTHE!.3) )3/STANDARD ITISNOTIMPLEMENTEDINALL31,DIALECTS)TSAGOODIDEATOBUILDASMALLTEST TABLEANDCHECKTHEBEHAVIOROFYOUR$"-3BRANDBEFORECOUNTINGONASPECIFICBEHAVIOR
0!24ç))
3%,%#4.!-% 35-!-/5.4 &2/-/2$%23 3!,%32%03 7(%2%2%0%-0,?.5- '2/50"9.!-% .!-%35-!-/5.4
"ILL!DAMS $AN2OBERTS ,ARRY&ITCH -ARY*ONES .ANCY!NGELLI 0AUL#RUZ 3AM#LARK 3UE3MITH 4OM3NYDER
ç
0ARTç))ç
2ETRIEVINGç$ATA
#
# #
!
"
" " " " "
"
1, Ên{Ê /
iÊ0%/0,%ÊÌ>Li
'ROUPõ3EARCHõ#ONDITIONSõ(!6).'õ#LAUSE *USTASTHE7(%2%CLAUSECANBEUSEDTOSELECTANDREJECTTHEINDIVIDUALROWSTHATPARTICIPATEIN AQUERY THE(!6).'CLAUSECANBEUSEDTOSELECTANDREJECTROWGROUPS4HEFORMATOFTHE (!6).'CLAUSEPARALLELSTHATOFTHE7(%2%CLAUSE CONSISTINGOFTHEKEYWORD(!6).'FOLLOWED BYASEARCHCONDITION4HE(!6).'CLAUSETHUSSPECIFIESASEARCHCONDITIONFORGROUPS !NEXAMPLEPROVIDESTHEBESTWAYTOUNDERSTANDTHEROLEOFTHE(!6).'CLAUSE #ONSIDERTHISQUERY 7HATISTHEAVERAGEORDERSIZEFOREACHSALESPERSONWHOSEORDERSTOTALMORETHAN 3%,%#42%0 !6'!-/5.4 &2/-/2$%23 '2/50"92%0 (!6).'35-!-/5.4 2%0!6'!-/5.4
&IGURE SHOWSGRAPHICALLYHOW31,CARRIESOUTTHEQUERY4HE'2/50"9CLAUSEFIRST ARRANGESTHEORDERSINTOGROUPSBYSALESPERSON4HE(!6).'CLAUSETHENELIMINATESANY GROUPWHERETHETOTALOFTHEORDERSINTHEGROUPDOESNOTEXCEED &INALLY THE 3%,%#4CLAUSECALCULATESTHEAVERAGEORDERSIZEFOREACHOFTHEREMAININGGROUPSAND GENERATESTHEQUERYRESULTS 4HESEARCHCONDITIONSYOUCANSPECIFYINTHE(!6).'CLAUSEARETHESAMEONESUSEDIN THE7(%2%CLAUSE ASDESCRIBEDIN#HAPTERSAND(EREISANOTHEREXAMPLEOFTHEUSEOFA GROUPSEARCHCONDITION
#HAPTERçç
3UMMARYç1UERIESç
!&')(
"!&')(
"!
""!
#"!
- - -
- - -
- - -
!" ""!
1, ÊnxÊ Ê}ÀÕ«i`ÊÃi>ÀV
ÊV`ÌÊÊ«iÀ>Ì
&OREACHOFFICEWITHTWOORMOREPEOPLE COMPUTETHETOTALQUOTAANDTOTALSALESFORALLSALESPEOPLEWHO WORKINTHEOFFICE 3%,%#4#)49 35-15/4! 35-3!,%32%033!,%3 &2/-/&&)#%3 3!,%32%03 7(%2%/&&)#%2%0?/&&)#% '2/50"9#)49 (!6).'#/5.4 #)4935-15/4! 35-3!,%32%033!,%3
#HICAGO ,OS!NGELES .EW9ORK
4HEFOLLOWINGSTEPSSHOWTHERULESFOR31,QUERYPROCESSING EXPANDEDONCEAGAINTO INCLUDEGROUPSEARCHCONDITIONS 4OGENERATETHEQUERYRESULTSFORA3%,%#4STATEMENT
)FTHESTATEMENTISA5.)/.OF3%,%#4STATEMENTS APPLY3TEPSTHROUGHTOEACH OFTHESTATEMENTSTOGENERATETHEIRINDIVIDUALQUERYRESULTS
&ORMTHEPRODUCTOFTHETABLESNAMEDINTHE&2/-CLAUSE)FTHE&2/-CLAUSENAMES ASINGLETABLE THEPRODUCTISTHATTABLE
)FTHEREISA7(%2%CLAUSE APPLYITSSEARCHCONDITIONTOEACHROWOFTHEPRODUCT TABLE RETAININGTHOSEROWSFORWHICHTHESEARCHCONDITIONIS425%ANDDISCARDING THOSEFORWHICHITIS&!,3%OR.5,,
0!24ç))
" $ -
"$(*,)+*
%"
ç
0ARTç))ç
2ETRIEVINGç$ATA
)FTHEREISA'2/50"9CLAUSE ARRANGETHEREMAININGROWSOFTHEPRODUCTTABLEINTO ROWGROUPS SOTHATTHEROWSINEACHGROUPHAVEIDENTICALVALUESINALLOFTHE GROUPINGCOLUMNS
)FTHEREISA(!6).'CLAUSE APPLYITSSEARCHCONDITIONTOEACHROWGROUP RETAINING THOSEGROUPSFORWHICHTHESEARCHCONDITIONIS425%ANDDISCARDINGTHOSEFOR WHICHITIS&!,3%OR.5,,
&OREACHREMAININGROWORROWGROUP CALCULATETHEVALUEOFEACHITEMINTHESELECT LISTTOPRODUCEASINGLEROWOFQUERYRESULTS&ORASIMPLECOLUMNREFERENCE USETHE VALUEOFTHECOLUMNINTHECURRENTROWORROWGROUP &ORACOLUMNFUNCTION USE THECURRENTROWGROUPASITSARGUMENTIF'2/50"9ISSPECIFIEDOTHERWISE USETHE ENTIRESETOFROWS
)F3%,%#4$)34).#4ISSPECIFIED ELIMINATEANYDUPLICATEROWSOFQUERYRESULTS THATWEREPRODUCED
)FTHESTATEMENTISA5.)/.OF3%,%#4STATEMENTS MERGETHEQUERYRESULTSFORTHE INDIVIDUALSTATEMENTSINTOASINGLETABLEOFQUERYRESULTS%LIMINATEDUPLICATEROWS UNLESS5.)/.!,,ISSPECIFIED
)FTHEREISAN/2$%2"9CLAUSE SORTTHEQUERYRESULTSASSPECIFIED
4HEROWSGENERATEDBYTHISPROCEDURECOMPRISETHEQUERYRESULTS &OLLOWINGTHISPROCEDURE 31,HANDLESTHEQUERYINTHEPREVIOUSEXAMPLEASFOLLOWS
*OINSTHE/&&)#%3AND3!,%32%03TABLESTOFINDTHECITYWHEREEACHSALESPERSON WORKS
'ROUPSTHERESULTINGROWSBYOFFICE
%LIMINATESGROUPSWITHTWOORFEWERROWSTHESEREPRESENTOFFICESTHATDONTMEET THE(!6).'CLAUSECRITERION
#ALCULATESTHETOTALQUOTAANDTOTALSALESFOREACHGROUP (EREISONEMOREEXAMPLE WHICHUSESALLOFTHE3%,%#4STATEMENTCLAUSES
3HOWTHEPRICE QUANTITYONHAND ANDTOTALQUANTITYONORDERFOREACHPRODUCTWHERETHETOTAL QUANTITYONORDERISMORETHANPERCENTOFTHEQUANTITYONHAND 3%,%#4$%3#2)04)/. 02)#% 149?/.?(!.$ 35-149 &2/-02/$5#43 /2$%23 7(%2%-&2-&2?)$ !.$02/$5#402/$5#4?)$ '2/50"9-&2?)$ 02/$5#4?)$ $%3#2)04)/. 02)#% 149?/.?(!.$ (!6).'35-149 149?/.?(!.$ /2$%2"9149?/.?(!.$$%3# $%3#2)04)/.02)#%149?/.?(!.$35-149
2EDUCER 7IDGET!DJUSTER -OTOR-OUNT 2IGHT(INGE LB"RACE
#HAPTERçç
3UMMARYç1UERIESç
4OPROCESSTHISQUERY 31,CONCEPTUALLYPERFORMSTHEFOLLOWINGSTEPS *OINSTHE/2$%23AND02/$5#43TABLESTOFINDTHEDESCRIPTION PRICE ANDQUANTITY ONHANDFOREACHPRODUCTORDERED
'ROUPSTHERESULTINGROWSBYMANUFACTURERANDPRODUCT)$
%LIMINATESGROUPSWHERETHEQUANTITYORDEREDTHETOTALOFTHE149COLUMNFORALL ORDERSINTHEGROUP ISLESSTHANPERCENTOFTHEQUANTITYONHAND
#ALCULATESTHETOTALQUANTITYORDEREDFOREACHGROUP
'ENERATESONESUMMARYROWOFQUERYRESULTSFOREACHGROUP
3ORTSTHEQUERYRESULTSSOTHATPRODUCTSWITHTHELARGESTQUANTITYONHANDAPPEARFIRST
!SDESCRIBEDPREVIOUSLY $%3#2)04)/. 02)#% AND149?/.?(!.$MUSTBESPECIFIED ASGROUPINGCOLUMNSINTHISQUERYSOLELYBECAUSETHEYAPPEARINTHESELECTLIST4HEYACTUALLY CONTRIBUTENOTHINGTOTHEGROUPINGPROCESS BECAUSETHE-&2?)$AND02/$5#4?)$ COMPLETELYSPECIFYASINGLEROWOFTHE02/$5#43TABLE AUTOMATICALLYMAKINGTHEOTHER THREECOLUMNSSINGLE VALUEDPERGROUP
2ESTRICTIONSõONõ'ROUPõ3EARCHõ#ONDITIONS 4HE(!6).'CLAUSEISUSEDTOINCLUDEOREXCLUDEROWGROUPSFROMTHEQUERYRESULTS SOTHE SEARCHCONDITIONITSPECIFIESMUSTBEONETHATAPPLIESTOTHEGROUPASAWHOLERATHERTHANTO INDIVIDUALROWS4HISMEANSTHATANITEMAPPEARINGWITHINTHESEARCHCONDITIONINA (!6).'CLAUSECANBE s !CONSTANT s !COLUMNFUNCTION WHICHPRODUCESASINGLEVALUESUMMARIZINGTHEROWSINTHEGROUP s !GROUPINGCOLUMN WHICHBYDEFINITIONHASTHESAMEVALUEINEVERYROWOFTHEGROUP s !NEXPRESSIONINVOLVINGCOMBINATIONSOFTHESE )NPRACTICE THESEARCHCONDITIONINTHE(!6).'CLAUSEWILLALWAYSINCLUDEATLEASTONE COLUMNFUNCTION)FITDIDNOT THESEARCHCONDITIONCOULDBEMOVEDTOTHE7(%2%CLAUSEAND APPLIEDTOINDIVIDUALROWS4HEEASIESTWAYTOFIGUREOUTWHETHERASEARCHCONDITION BELONGSINTHE7(%2%CLAUSEORINTHE(!6).'CLAUSEISTOREMEMBERHOWTHETWOCLAUSES AREAPPLIED s 4HE7(%2%CLAUSEISAPPLIEDTOINDIVIDUALROWS SOTHEEXPRESSIONSITCONTAINSMUST BECOMPUTABLEFORINDIVIDUALROWS s 4HE(!6).'CLAUSEISAPPLIEDTOROWGROUPS SOTHEEXPRESSIONSITCONTAINSMUSTBE COMPUTABLEFORAGROUPOFROWS
0!24ç))
ç
0ARTç))ç
2ETRIEVINGç$ATA
.5,,õ6ALUESõANDõ'ROUPõ3EARCHõ#ONDITIONS ,IKETHESEARCHCONDITIONINTHE7(%2%CLAUSE THE(!6).'CLAUSESEARCHCONDITIONCAN PRODUCEONEOFTHREERESULTS s )FTHESEARCHCONDITIONIS425% THEROWGROUPISRETAINED ANDITCONTRIBUTESA SUMMARYROWTOTHEQUERYRESULTS s )FTHESEARCHCONDITIONIS&!,3% THEROWGROUPISDISCARDED ANDITDOESNOT CONTRIBUTEASUMMARYROWTOTHEQUERYRESULTS s )FTHESEARCHCONDITIONIS.5,, THEROWGROUPISDISCARDED ANDITDOESNOT CONTRIBUTEASUMMARYROWTOTHEQUERYRESULTS 4HEANOMALIESTHATCANOCCURWITH.5,,VALUESINTHESEARCHCONDITIONARETHESAMEAS THOSEFORTHE7(%2%CLAUSEANDHAVEBEENDESCRIBEDIN#HAPTER
(!6).'õ7ITHOUTõ'2/50õ"9 4HE(!6).'CLAUSEISALMOSTALWAYSUSEDINCONJUNCTIONWITHTHE'2/50"9CLAUSE BUTTHE SYNTAXOFTHE3%,%#4STATEMENTDOESNOTREQUIREIT)FA(!6).'CLAUSEAPPEARSWITHOUTA '2/50"9CLAUSE 31,CONSIDERSTHEENTIRESETOFDETAILEDQUERYRESULTSTOBEASINGLEGROUP )NOTHERWORDS THECOLUMNFUNCTIONSINTHE(!6).'CLAUSEAREAPPLIEDTOONE ANDONLYONE GROUPTODETERMINEWHETHERTHEGROUPISINCLUDEDOREXCLUDEDFROMTHEQUERYRESULTS AND THATGROUPCONSISTSOFALLTHEROWS4HEUSEOFA(!6).'CLAUSEWITHOUTACORRESPONDING '2/50"9CLAUSEISSELDOMSEENINPRACTICE
3UMMARY 4HISCHAPTERDESCRIBEDSUMMARYQUERIES WHICHSUMMARIZEDATAFROMTHEDATABASE s 3UMMARYQUERIESUSE31,COLUMNFUNCTIONSTOCOLLAPSEACOLUMNOFDATAVALUES INTOASINGLEVALUETHATSUMMARIZESTHECOLUMN s #OLUMNFUNCTIONSCANCOMPUTETHEAVERAGE SUM MINIMUM ANDMAXIMUMVALUES OFACOLUMN COUNTTHENUMBEROFDATAVALUESINACOLUMN ORCOUNTTHENUMBEROF ROWSOFQUERYRESULTS s !SUMMARYQUERYWITHOUTA'2/50"9CLAUSEGENERATESASINGLEROWOFQUERY RESULTS SUMMARIZINGALLTHEROWSOFATABLEORAJOINEDSETOFTABLES s !SUMMARYQUERYWITHA'2/50"9CLAUSEGENERATESMULTIPLEROWSOFQUERYRESULTS EACHSUMMARIZINGTHEROWSINAPARTICULARGROUP s 4HE(!6).'CLAUSEACTSASA7(%2%CLAUSEFORGROUPS SELECTINGTHEROWGROUPSTHAT CONTRIBUTETOTHESUMMARYQUERYRESULTS
#(!04%2
3UBQUERIESçANDç1UERYç %XPRESSIONS
4
HE31,SUBQUERYFEATURELETSYOUUSETHERESULTSOFONEQUERYASPARTOFANOTHERQUERY 4HEABILITYTOUSEAQUERYWITHINAQUERYWASTHEORIGINALREASONFORTHEWORD hSTRUCTUREDvINTHENAME3TRUCTURED1UERY,ANGUAGE4HESUBQUERYFEATUREISLESS WELL KNOWNTHAN31,SJOINFEATURE BUTITPLAYSANIMPORTANTROLEIN31,FORTHREEREASONS s !31,STATEMENTWITHASUBQUERYISOFTENTHEMOSTNATURALWAYTOEXPRESSAQUERY BECAUSEITMOSTCLOSELYPARALLELSTHE%NGLISH LANGUAGEDESCRIPTIONOFTHEQUERY s 3UBQUERIESMAKEITEASIERTOWRITE3%,%#4STATEMENTS BECAUSETHEYLETYOUBREAK AQUERYDOWNINTOPIECESTHEQUERYANDITSSUBQUERIES ANDTHENPUTTHEPIECES BACKTOGETHER s 3OMEQUERIESCANNOTBEEXPRESSEDIN31,WITHOUTUSINGASUBQUERY 4HEFIRSTSEVERALSECTIONSOFTHISCHAPTERDESCRIBESUBQUERIESANDSHOWHOWTHEYARE USEDINTHE7(%2%AND(!6).'CLAUSESOFA31,STATEMENT4HELATERSECTIONSOFTHISCHAPTER DESCRIBETHEADVANCEDQUERYEXPRESSIONCAPABILITIESTHATHAVEBEENADDEDTOTHE31, STANDARD WHICHSUBSTANTIALLYEXPANDSTHEPOWEROF31,TOPERFORMEVENTHEMOSTCOMPLEX OFDATABASEOPERATIONS
5SINGõ3UBQUERIES !SUBQUERYISAQUERYWITHINAQUERY4HERESULTSOFTHESUBQUERYAREUSEDBYTHE$"-3TO DETERMINETHERESULTSOFTHEHIGHER LEVELQUERYTHATCONTAINSTHESUBQUERY)NTHESIMPLEST FORMSOFASUBQUERY THESUBQUERYAPPEARSWITHINTHE7(%2%OR(!6).'CLAUSEOFANOTHER 31,STATEMENT3UBQUERIESPROVIDEANEFFICIENT NATURALWAYTOHANDLEQUERYREQUESTSTHAT ARETHEMSELVESEXPRESSEDINTERMSOFTHERESULTSOFOTHERQUERIES(EREISANEXAMPLEOFSUCH AREQUEST ,ISTTHEOFlCESWHERETHESALESTARGETFORTHEOFlCEEXCEEDSTHESUMOFTHESALESPEOPLESQUOTAS
ç
0ARTç))ç
2ETRIEVINGç$ATA
4HEREQUESTASKSFORALISTOFOFFICESFROMTHE/&&)#%3TABLE WHERETHEVALUEOFTHE 4!2'%4COLUMNMEETSSOMECONDITION)TSEEMSREASONABLETHATTHE3%,%#4STATEMENTTHAT EXPRESSESTHEQUERYSHOULDLOOKSOMETHINGLIKETHIS 3%,%#4#)49&2/-/&&)#%37(%2%4!2'%4
4HEVALUEhvNEEDSTOBEFILLEDINANDSHOULDBEEQUALTOTHESUMOFTHEQUOTASOF THESALESPEOPLEASSIGNEDTOTHEOFFICEINQUESTION(OWCANYOUSPECIFYTHATVALUEINTHE QUERY&ROM#HAPTER YOUKNOWTHATTHESUMOFTHEQUOTASFORASPECIFICOFFICESAY OFFICE NUMBER CANBEOBTAINEDWITHTHISQUERY 3%,%#435-15/4! &2/-3!,%32%03 7(%2%2%0?/&&)#%
"UTITWOULDBEINEFFICIENTTOHAVETOTYPEINTHISQUERY WRITEDOWNTHERESULTS ANDTHEN TYPEINTHEPREVIOUSQUERYWITHTHECORRECTAMOUNT(OWCANYOUPUTTHERESULTSOFTHIS QUERYINTOTHEEARLIERQUERYINPLACEOFTHEQUESTIONMARKS)TWOULDSEEMREASONABLETO STARTWITHTHEFIRSTQUERYANDREPLACETHEhvWITHTHESECONDQUERY ASFOLLOWS 3%,%#4#)49 &2/-/&&)#%3 7(%2%4!2'%43%,%#435-15/4! &2/-3!,%32%03 7(%2%2%0?/&&)#%/&&)#%
)NFACT THISISACORRECTLYFORMED31,QUERY&OREACHOFFICE THEINNERQUERYTHESUBQUERY CALCULATESTHESUMOFTHEQUOTASFORTHESALESPEOPLEWORKINGINTHATOFFICE4HEOUTERQUERY THEMAINQUERY COMPARESTHEOFFICESTARGETWITHTHECALCULATEDTOTALANDDECIDESWHETHERTO ADDTHEOFFICETOTHEMAINQUERYRESULTS7ORKINGTOGETHER THEMAINQUERYANDTHESUBQUERY EXPRESSTHEORIGINALREQUESTANDRETRIEVETHEREQUESTEDDATAFROMTHEDATABASE 31,SUBQUERIESTYPICALLYAPPEARASPARTOFTHE7(%2%CLAUSEORTHE(!6).'CLAUSE)N THE7(%2%CLAUSE THEYHELPTOSELECTTHEINDIVIDUALROWSTHATAPPEARINTHEQUERYRESULTS)N THE(!6).'CLAUSE THEYHELPTOSELECTTHEROWGROUPSTHATAPPEARINTHEQUERYRESULTS
7HATõ)SõAõ3UBQUERY &IGURE SHOWSTHEFORMOFA31,SUBQUERY4HESUBQUERYISENCLOSEDINPARENTHESES BUT OTHERWISEITHASTHEFAMILIARFORMOFA3%,%#4STATEMENT WITHA&2/-CLAUSEANDOPTIONAL 7(%2% '2/50"9 (!6).' AND/2$%2"9CLAUSES4HEFORMOFTHESECLAUSESINASUBQUERY ISIDENTICALTOTHATINA3%,%#4STATEMENT ANDTHEYPERFORMTHEIRNORMALFUNCTIONSWHEN USEDWITHINASUBQUERY4HEREARE HOWEVER AFEWDIFFERENCESBETWEENASUBQUERYANDAN ACTUAL3%,%#4STATEMENT s )NTHEMOSTCOMMONUSES ASUBQUERYMUSTPRODUCEASINGLECOLUMNOFDATAASITS QUERYRESULTS4HISMEANSTHATASUBQUERYALMOSTALWAYSHASASINGLESELECTITEMIN ITS3%,%#4CLAUSE s 7HILETHE/2$%2"9CLAUSECANBESPECIFIEDINASUBQUERY ITISRARELYUSEDTHERE 4HESUBQUERYRESULTSAREUSEDINTERNALLYBYTHEMAINQUERYANDARENEVERVISIBLE
#HAPTERçç
1, Ê£Ê Ê >ÃVÊÃÕLµÕiÀÞÊÊ ÃÞÌ>ÝÊ`>}À>
3UBQUERIESçANDç1UERYç%XPRESSIONSç
0!24ç))
TOTHEUSER SOITMAKESLITTLESENSETOSORTTHEM-OREOVER SORTINGLARGENUMBERSOF ROWSCANADVERSELYAFFECTPERFORMANCE s #OLUMNNAMESAPPEARINGINASUBQUERYMAYREFERTOCOLUMNSOFTABLESINTHEMAIN QUERY4HESEOUTERREFERENCESAREDESCRIBEDINDETAILLATERINTHEh/UTER2EFERENCESv SECTION s )NMOSTIMPLEMENTATIONS ASUBQUERYCANNOTBETHE5.)/.OFSEVERALDIFFERENT 3%,%#4STATEMENTSONLYASINGLE3%,%#4ISALLOWED4HE31,STANDARDALLOWS MUCHMOREPOWERFULQUERYEXPRESSIONSANDRELAXESTHISRESTRICTION ASDESCRIBED LATERINTHESECTIONh!DVANCED1UERIESv
3UBQUERIESõINõTHEõ7(%2%õ#LAUSE 3UBQUERIESAREMOSTFREQUENTLYUSEDINTHE7(%2%CLAUSEOFA31,STATEMENT7HENASUBQUERY APPEARSINTHE7(%2%CLAUSE ITWORKSASPARTOFTHEROWSELECTIONPROCESS4HEVERYSIMPLEST SUBQUERIESAPPEARWITHINASEARCHCONDITIONANDPRODUCEAVALUETHATISUSEDTOTESTTHESEARCH CONDITION4HEFOLLOWINGISANEXAMPLEOFASIMPLESUBQUERY
ç
0ARTç))ç
2ETRIEVINGç$ATA
,ISTTHESALESPEOPLEWHOSEQUOTAISLESSTHANPERCENTOFTHECOMPANYWIDESALESTARGET 3%,%#4.!-% &2/-3!,%32%03 7(%2%15/4! 3%,%#435-4!2'%4 &2/-/&&)#%3 .!-%
"OB3MITH
)NTHISCASE THESUBQUERYCALCULATESTHESUMOFTHESALESTARGETSFORALLOFTHEOFFICESTO DETERMINETHECOMPANYWIDETARGET WHICHISMULTIPLIEDBYPERCENTTODETERMINETHE CUTOFFSALESQUOTAFORTHEQUERY4HATVALUEISTHENUSEDINTHESEARCHCONDITIONTOCHECK EACHROWOFTHE3!,%32%03TABLEANDFINDTHEREQUESTEDNAMES)NTHISSIMPLECASE THE SUBQUERYPRODUCESTHESAMEVALUEFOREVERYROWOFTHE3!,%32%03TABLETHE15/4!VALUE FOREACHSALESPERSONISCOMPAREDWITHTHESAMECOMPANYWIDENUMBER/FCOURSE THE QUERYCOULDALSOBEWRITTENTOPERFORMTHEMULTIPLICATIONWITHINTHESUBQUERYLIKETHIS 3%,%#4.!-% &2/-3!,%32%03 7(%2%15/4!3%,%#435-4!2'%4 &2/-/&&)#%3
)NTHISCASEITSMORECONVENIENTTOUSETHESUBQUERY BUTITSNOTESSENTIAL7ECOULD HAVESIMPLYRUNTHEQUERYCONTAINEDINTHESUBQUERYBYITSELFTORETURNTHECUTOFFQUOTA AMOUNT INTHESAMPLEDATABASE ANDTHENKEYEDTHATAMOUNTINTOTHE7(%2% CLAUSEOFTHEMAINQUERYASSHOWNHERE 3%,%#435-4!2'%4 &2/-/&&)#%3 35-4!2'%4
3%,%#4.!-% &2/-3!,%32%03 7(%2%15/4!
(OWEVER SUBQUERIESAREUSUALLYNOTTHISSIMPLE&OREXAMPLE CONSIDERONCEAGAINTHE QUERYFROMTHEPREVIOUSSECTION ,ISTTHEOFlCESWHERETHESALESTARGETFORTHEOFlCEEXCEEDSTHESUMOFTHESALESPEOPLESQUOTAS 3%,%#4#)49 &2/-/&&)#%3 7(%2%4!2'%43%,%#435-15/4! &2/-3!,%32%03 7(%2%2%0?/&&)#%/&&)#% #)49
#HICAGO ,OS!NGELES
#HAPTERçç
3UBQUERIESçANDç1UERYç%XPRESSIONSç
/UTERõ2EFERENCES 7ITHINTHEBODYOFASUBQUERY ITSOFTENNECESSARYTOREFERTOTHEVALUEOFACOLUMNINTHE CURRENTROWOFTHEMAINQUERY#ONSIDERONCEAGAINTHEQUERYFROMTHEPREVIOUSSECTIONS ,ISTTHEOFlCESWHERETHESALESTARGETFORTHEOFlCEEXCEEDSTHESUMOFTHESALESPEOPLESQUOTAS 3%,%#4#)49 &2/-/&&)#%3 7(%2%4!2'%43%,%#435-15/4! &2/-3!,%32%03 7(%2%2%0?/&&)#%/&&)#%
$%,' 3%/3'06
!#
$%,'
"
'-4'0 '5".0+ )*&$(. 2,$-2$ .1-(','1
7 7 7
$%,' 3%/3'06
!#
1, ÊÓÊ -ÕLµÕiÀÞÊ«iÀ>ÌÊÊÌ
iÊ7(%2%ÊV>ÕÃi
0!24ç))
)NTHISMORETYPICAL CASE THESUBQUERYCANNOTBECALCULATEDONCEFORTHEENTIREQUERY 4HESUBQUERYPRODUCESADIFFERENTVALUEFOREACHOFFICE BASEDONTHEQUOTASOFTHE SALESPEOPLEINTHATPARTICULAROFFICE&IGURE SHOWSCONCEPTUALLYHOW31,CARRIESOUTTHE QUERY4HEMAINQUERYDRAWSITSDATAFROMTHE/&&)#%3TABLE ANDTHE7(%2%CLAUSESELECTS WHICHOFFICESWILLBEINCLUDEDINTHEQUERYRESULTS31,GOESTHROUGHTHEROWSOFTHE /&&)#%3TABLEONEBYONE APPLYINGTHETESTSTATEDINTHE7(%2%CLAUSE4OTESTTHE4!2'%4 VALUE 31,CARRIESOUTTHESUBQUERY FINDINGTHESUMOFTHEQUOTASFORSALESPEOPLEINTHE CURRENTOFFICE4HESUBQUERYPRODUCESASINGLENUMBER ANDTHE7(%2%CLAUSECOMPARESTHE NUMBERWITHTHE4!2'%4VALUE SELECTINGORREJECTINGTHECURRENTOFFICEBASEDONTHE COMPARISON!STHEFIGURESHOWS 31,CARRIESOUTTHESUBQUERYREPEATEDLY ONCEFOREACH ROWTESTEDBYTHE7(%2%CLAUSEOFTHEMAINQUERY
ç
0ARTç))ç
2ETRIEVINGç$ATA
4HEROLEOFTHESUBQUERYINTHIS3%,%#4STATEMENTISTOCALCULATETHETOTALQUOTAFOR THOSESALESPEOPLEWHOWORKINAPARTICULAROFFICESPECIFICALLY THEOFFICECURRENTLYBEING TESTEDBYTHE7(%2%CLAUSEOFTHEMAINQUERY4HESUBQUERYDOESTHISBYSCANNINGTHE 3!,%32%03TABLE"UTNOTICETHATTHE/&&)#%COLUMNINTHE7(%2%CLAUSEOFTHESUBQUERY DOESNTREFERTOACOLUMNOFTHE3!,%32%03TABLEITREFERSTOACOLUMNOFTHE/&&)#%3 TABLE WHICHISAPARTOFTHEMAINQUERY!S31,MOVESTHROUGHEACHROWOFTHE/&&)#%3 TABLE ITUSESTHE/&&)#%VALUEFROMTHECURRENTROWWHENITCARRIESOUTTHESUBQUERY 4HE/&&)#%COLUMNINTHISSUBQUERYISANEXAMPLEOFANOUTERREFERENCE WHICHISA COLUMNNAMETHATDOESNOTREFERTOANYOFTHETABLESNAMEDINTHE&2/-CLAUSEOFTHE SUBQUERYINWHICHTHECOLUMNNAMEAPPEARS)NSTEAD THECOLUMNNAMEREFERSTOACOLUMN OFATABLESPECIFIEDINTHE&2/-CLAUSEOFTHEMAINQUERY!STHEPREVIOUSEXAMPLESHOWS WHENTHE$"-3EXAMINESTHESEARCHCONDITIONINTHESUBQUERY THEVALUEOFTHECOLUMNIN ANOUTERREFERENCEISTAKENFROMTHEROWCURRENTLYBEINGTESTEDBYTHEMAINQUERY
3UBQUERYõ3EARCHõ#ONDITIONS !SUBQUERYUSUALLYAPPEARSASPARTOFASEARCHCONDITIONINTHE7(%2%OR(!6).'CLAUSE #HAPTERDESCRIBEDTHESIMPLESEARCHCONDITIONSTHATCANBEUSEDINTHESECLAUSES)N ADDITION MOST31,PRODUCTSOFFERTHESESUBQUERYSEARCHCONDITIONS s 3UBQUERYCOMPARISONTEST #OMPARESTHEVALUEOFANEXPRESSIONWITHASINGLE VALUEPRODUCEDBYASUBQUERY4HISTESTRESEMBLESTHESIMPLECOMPARISONTEST s 3UBQUERYSETMEMBERSHIPTEST #HECKSWHETHERTHEVALUEOFANEXPRESSION MATCHESONEOFTHESETOFVALUESPRODUCEDBYASUBQUERY4HISTESTRESEMBLESTHE SIMPLESETMEMBERSHIPTEST s %XISTENCETEST 4ESTSWHETHERASUBQUERYPRODUCESANYROWSOFQUERYRESULTS s 1UANTIFIEDCOMPARISONTEST #OMPARESTHEVALUEOFANEXPRESSIONWITHEACHOFTHE SETSOFVALUESPRODUCEDBYASUBQUERY
4HEõ3UBQUERYõ#OMPARISONõ4ESTõ õ õ õ õ õ 4HESUBQUERYCOMPARISONTESTISAMODIFIEDFORMOFTHESIMPLECOMPARISONTEST ASSHOWN IN&IGURE )TCOMPARESTHEVALUEOFANEXPRESSIONWITHTHEVALUEPRODUCEDBYASUBQUERY
1, ÊÎÊ Ê -ÕLµÕiÀÞÊ V«>ÀÃÊÌiÃÌÊ ÃÞÌ>ÝÊ`>}À>
#HAPTERçç
3UBQUERIESçANDç1UERYç%XPRESSIONSç
ANDRETURNSA425%RESULTIFTHECOMPARISONISTRUE9OUUSETHISTESTTOCOMPAREAVALUE FROMTHEROWBEINGTESTEDWITHASINGLEVALUEPRODUCEDBYASUBQUERY ASINTHISEXAMPLE ,ISTTHESALESPEOPLEWHOSEQUOTASAREEQUALTOORHIGHERTHANTHETARGETOFTHE!TLANTASALESOFlCE
4HESUBQUERYINTHEEXAMPLERETRIEVESTHESALESTARGETOFTHE!TLANTAOFFICE4HEVALUEIS THENUSEDTOSELECTTHESALESPEOPLEWHOSEQUOTASAREHIGHERTHANTHERETRIEVEDTARGET 4HESUBQUERYCOMPARISONTESTOFFERSTHESAMESIXCOMPARISONOPERATORS AVAILABLEWITHTHESIMPLECOMPARISONTEST4HESUBQUERYSPECIFIEDINTHISTESTMUST PRODUCEASINGLEVALUEOFTHEAPPROPRIATEDATATYPETHATIS ITMUSTPRODUCEASINGLEROWOF QUERYRESULTSCONTAININGEXACTLYONECOLUMN)FTHESUBQUERYPRODUCESMULTIPLEROWSOR MULTIPLECOLUMNS THECOMPARISONDOESNOTMAKESENSE AND31,REPORTSANERRORCONDITION )FTHESUBQUERYPRODUCESNOROWSORPRODUCESA.5,,VALUE THECOMPARISONTESTRETURNS .5,,UNKNOWN (EREARESOMEADDITIONALEXAMPLESOFSUBQUERYCOMPARISONTESTS ,ISTALLCUSTOMERSSERVEDBY"ILL!DAMS 3%,%#4#/-0!.9 &2/-#534/-%23 7(%2%#534?2%03%,%#4%-0,?.5- &2/-3!,%32%03 7(%2%.!-%g"ILL!DAMSg #/-0!.9
!CME-FG 4HREE 7AY,INES
,ISTALLPRODUCTSFROMMANUFACTURER!#)WHERETHEQUANTITYONHANDISABOVETHEQUANTITYONHAND OFPRODUCT!#) 3%,%#4$%3#2)04)/. 149?/.?(!.$ &2/-02/$5#43 7(%2%-&2?)$g!#)g !.$149?/.?(!.$3%,%#4149?/.?(!.$ &2/-02/$5#43 7(%2%-&2?)$g!#)g !.$02/$5#4?)$gg
0!24ç))
3%,%#4.!-% &2/-3!,%32%03 7(%2%15/4!3%,%#44!2'%4 &2/-/&&)#%3 7(%2%#)49g!TLANTAg .!-%
"ILL!DAMS 3UE3MITH ,ARRY&ITCH
ç
0ARTç))ç
2ETRIEVINGç$ATA
$%3#2)04)/.149?/.?(!.$
3IZE7IDGET 3IZE7IDGET 3IZE7IDGET
4HESUBQUERYCOMPARISONTESTSPECIFIEDBYTHEORIGINAL31,STANDARD31, AND SUPPORTEDBYALLOFTHELEADING$"-3PRODUCTSALLOWSASUBQUERYONLYONTHERIGHTSIDEOF THECOMPARISONOPERATOR4HISCOMPARISON !SUBQUERY
ISALLOWED BUTTHISCOMPARISON SUBQUERY !
ISNOTPERMITTED4HISDOESNTLIMITTHEPOWEROFTHECOMPARISONTEST BECAUSETHEOPERATOR INANYUNEQUALCOMPARISONCANALWAYSBETURNEDAROUNDSOTHATTHESUBQUERYISPUTONTHE RIGHTSIDEOFTHEINEQUALITY(OWEVER ITDOESMEANTHATYOUMUSTSOMETIMESTURNAROUND THELOGICOFAN%NGLISH LANGUAGEREQUESTTOGETAFORMOFTHEREQUESTTHATCORRESPONDSTOA LEGAL31,STATEMENT 3UBSEQUENTVERSIONSOFTHE31,STANDARDELIMINATEDTHISRESTRICTIONANDALLOWTHE SUBQUERYTOAPPEARONEITHERSIDEOFTHECOMPARISONOPERATOR)NFACT THECURRENT31,STANDARD GOESCONSIDERABLYFURTHERANDALLOWSACOMPARISONTESTTOBEAPPLIEDTOANENTIREROWOF VALUESINSTEADOFTOASINGLEVALUE4HISANDOTHERMOREADVANCEDQUERYEXPRESSIONFEATURES OFTHE31,STANDARDAREDESCRIBEDINTHELATTERSECTIONSOFTHISCHAPTER(OWEVER THEYARENOT UNIFORMLYSUPPORTEDBYTHECURRENTVERSIONSOFTHEMAJOR31,PRODUCTS&ORPORTABILITY ITS BESTTOWRITESUBQUERIESTHATCONFORMTOTHE31,RESTRICTIONS ASDESCRIBEDPREVIOUSLY
4HEõ3ETõ-EMBERSHIPõ4ESTõ). 4HESUBQUERYSETMEMBERSHIPTEST). ISAMODIFIEDFORMOFTHESIMPLESETMEMBERSHIP TEST ASSHOWNIN&IGURE )TCOMPARESASINGLEDATAVALUEWITHACOLUMNOFDATAVALUES PRODUCEDBYASUBQUERYANDRETURNSA425%RESULTIFTHEDATAVALUEMATCHESONEOFTHE VALUESINTHECOLUMN9OUUSETHISTESTWHENYOUNEEDTOCOMPAREAVALUEFROMTHEROW BEINGTESTEDWITHASETOFVALUESPRODUCEDBYASUBQUERY(EREISASIMPLEEXAMPLE ,ISTTHESALESPEOPLEWHOWORKINOFlCESTHATAREOVERTARGET 3%,%#4.!-% &2/-3!,%32%03 7(%2%2%0?/&&)#%).3%,%#4/&&)#% &2/-/&&)#%3 7(%2%3!,%34!2'%4 .!-%
-ARY*ONES 3AM#LARK "ILL!DAMS 3UE3MITH ,ARRY&ITCH
#HAPTERçç
1, Ê{Ê Ê -ÕLµÕiÀÞÊÃiÌÊ iLiÀÃ
«ÊÌiÃÌÊ ).®ÊÃÞÌ>ÝÊ `>}À>
3UBQUERIESçANDç1UERYç%XPRESSIONSç
,ISTTHESALESPEOPLEWHODONOTWORKINOFlCESMANAGEDBY,ARRY&ITCHEMPLOYEE 3%,%#4.!-% &2/-3!,%32%03 7(%2%2%0?/&&)#%./4).3%,%#4/&&)#% &2/-/&&)#%3 7(%2%-'2 .!-%
"ILL!DAMS -ARY*ONES 3AM#LARK "OB3MITH $AN2OBERTS 0AUL#RUZ
,ISTALLOFTHECUSTOMERSWHOHAVEPLACEDORDERSFOR!#)7IDGETSMANUFACTURER!#) PRODUCT NUMBERSSTARTINGWITH BETWEEN*ANUARYAND*UNE 3%,%#4#/-0!.9 &2/-#534/-%23 7(%2%#534?.5-).3%,%#4$)34).#4#534 &2/-/2$%23 7(%2%-&2g!#)g !.$02/$5#4,)+%gg !.$/2$%2?$!4%"%47%%.g g !.$g g #/-0!.9
!CME-FG !CE)NTERNATIONAL (OLM,ANDIS *#0)NC
0!24ç))
4HESUBQUERYPRODUCESASETOFOFFICENUMBERSWHERETHESALESAREABOVETARGET)NTHE SAMPLEDATABASE THEREARETHREESUCHOFFICES NUMBERED AND 4HEMAINQUERY THENCHECKSEACHROWOFTHE3!,%32%03TABLETODETERMINEWHETHERTHATPARTICULAR SALESPERSONWORKSINANOFFICEWITHONEOFTHESENUMBERS(EREARESOMEOTHEREXAMPLESOF SUBQUERIESTHATTESTSETMEMBERSHIP
ç
0ARTç))ç
2ETRIEVINGç$ATA
.OTETHATTHEUSEOF$)34).#4INTHESUBQUERYISNTSTRICTLYNECESSARY)FTHESAME CUSTOMERAPPEARSMULTIPLETIMESINTHESUBQUERYRESULTSINSTEADOFONLYONCE THEOUTER QUERYYIELDSTHESAMERESULTS/FTENTHEREISAPERFORMANCETRADE OFFBETWEENTHEOVERHEAD THE$"-3REQUIRESTOELIMINATEDUPLICATESUSUALLYASORTISREQUIRED ANDTHEOVERHEADOF PROCESSINGADDITIONALROWSINTHESUBQUERYRESULTSWHENPROCESSINGTHE7(%2%CLAUSEOFTHE MAINQUERY5SUALLYTHELARGERINTERMEDIATERESULTSETISALOTMOREEFFICIENTTHANTHESORT REQUIREDTOELIMINATEDUPLICATES!NDTHEREAREOFTENOTHERCONSIDERATIONS&OREXAMPLE IN /RACLE A'2/50"9ISUSUALLYMOREEFFICIENTTHANA$)34).#4!SYOUCANSEE WRITINGTHE MOSTEFFICIENT31,POSSIBLEREQUIRESSOMEDETAILEDKNOWLEDGEABOUTHOWTHEPARTICULAR $"-3BEINGUSEDPROCESSES31,STATEMENTS )NEACHOFTHESEEXAMPLES THESUBQUERYPRODUCESACOLUMNOFDATAVALUES ANDTHE 7(%2%CLAUSEOFTHEMAINQUERYCHECKSTOSEEWHETHERAVALUEFROMAROWOFTHEMAINQUERY MATCHESONEOFTHEVALUESINTHECOLUMN4HESUBQUERYFORMOFTHE).TESTTHUSWORKS EXACTLYLIKETHESIMPLE).TEST EXCEPTTHATTHESETOFVALUESISPRODUCEDBYASUBQUERY INSTEADOFBEINGEXPLICITLYLISTEDINTHESTATEMENT
4HEõ%XISTENCEõ4ESTõ%8)343 4HEEXISTENCETEST%8)343 CHECKSWHETHERASUBQUERYPRODUCESANYROWSOFQUERYRESULTS ASSHOWNIN&IGURE .OSIMPLECOMPARISONTESTRESEMBLESTHEEXISTENCETESTITISUSED ONLYWITHSUBQUERIES (EREISANEXAMPLEOFAREQUESTTHATCANBEEXPRESSEDNATURALLYUSINGANEXISTENCETEST ,ISTTHEPRODUCTSFORWHICHANORDEROF ORMOREHASBEENRECEIVED 4HEREQUESTCOULDEASILYBEREPHRASEDAS ,ISTTHEPRODUCTSFORWHICHTHEREEXISTSATLEASTONEORDERINTHE/2$%23TABLEA THATISFORTHE PRODUCTINQUESTIONANDB THATHASANAMOUNTOFATLEAST 4HE3%,%#4STATEMENTUSEDTORETRIEVETHEREQUESTEDLISTOFPRODUCTSCLOSELYRESEMBLES THEREPHRASEDREQUEST 3%,%#4$)34).#4$%3#2)04)/. &2/-02/$5#43 7(%2%%8)3433%,%#4/2$%2?.5- &2/-/2$%23 7(%2%02/$5#402/$5#4?)$ !.$-&2-&2?)$ !.$!-/5.4 $%3#2)04)/.
LB"RACE ,EFT(INGE 2IGHT(INGE 7IDGET2EMOVER
#HAPTERçç
1, ÊxÊ Ê
ÝÃÌiViÊÌiÃÌÊ %8)343®ÊÃÞÌ>ÝÊ `>}À>
3UBQUERIESçANDç1UERYç%XPRESSIONSç
,ISTTHEPRODUCTSFORWHICHANORDEROF ORMOREHASBEENRECEIVED 3%,%#4$%3#2)04)/. &2/-02/$5#43 7(%2%%8)3433%,%#4 &2/-/2$%23 7(%2%02/$5#402/$5#4?)$ !.$-&2-&2?)$ !.$!-/5.4
)NPRACTICE THESUBQUERYINAN%8)343TESTISUSUALLYWRITTENUSINGTHE3%,%#4 NOTATION (EREARESOMEADDITIONALEXAMPLESOFQUERIESTHATUSE%8)343 ,ISTANYCUSTOMERSASSIGNEDTO3UE3MITHWHOHAVENOTPLACEDANORDERFOROVER 3%,%#4#/-0!.9 &2/-#534/-%23 7(%2%#534?2%03%,%#4%-0,?.5- &2/-3!,%32%03 7(%2%.!-%g3UE3MITHg !.$./4%8)3433%,%#4 &2/-/2$%23 7(%2%#534#534?.5- !.$!-/5.4 #/-0!.9
#ARTER3ONS &RED,EWIS#ORP
0!24ç))
#ONCEPTUALLY 31,PROCESSESTHISQUERYBYGOINGTHROUGHTHE02/$5#43TABLEAND PERFORMINGTHESUBQUERYFOREACHPRODUCT4HESUBQUERYPRODUCESACOLUMNCONTAININGTHE ORDERNUMBERSOFANYORDERSFORTHEhCURRENTvPRODUCTTHATAREOVER )FTHEREAREANY SUCHORDERSTHATIS IFTHECOLUMNISNOTEMPTY THE%8)343TESTIS425%)FTHESUBQUERY PRODUCESNOROWS THE%8)343TESTIS&!,3%4HE%8)343TESTCANNOTPRODUCEA.5,,VALUE 9OUCANREVERSETHELOGICOFTHE%8)343TESTUSINGTHE./4%8)343FORM)NTHISCASE THETESTIS425%IFTHESUBQUERYPRODUCESNOROWS AND&!,3%OTHERWISE .OTICETHATTHE%8)343SEARCHCONDITIONDOESNTREALLYUSETHERESULTSOFTHESUBQUERYAT ALL)TMERELYTESTSTOSEEWHETHERTHESUBQUERYPRODUCESANYRESULTS&ORTHISREASON 31, RELAXESTHERULETHAThSUBQUERIESMUSTRETURNASINGLECOLUMNOFDATAvANDALLOWSYOUTOUSE THE3%,%#4 FORMINTHESUBQUERYOFAN%8)343TEST4HEPREVIOUSSUBQUERYCOULDTHUS HAVEBEENWRITTENAS
ç
0ARTç))ç
2ETRIEVINGç$ATA
,ISTTHEOFlCESWHERETHEREISASALESPERSONWHOSEQUOTAREPRESENTSMORETHANPERCENTOFTHEOFlCES TARGET 3%,%#4#)49 &2/-/&&)#%3 7(%2%%8)3433%,%#4 &2/-3!,%32%03 7(%2%2%0?/&&)#%/&&)#% !.$15/4! 4!2'%4 #)49
$ENVER !TLANTA
.OTETHATINEACHOFTHESEEXAMPLES THESUBQUERYINCLUDESANOUTERREFERENCETOA COLUMNOFTHETABLEINTHEMAINQUERY)NPRACTICE THESUBQUERYINAN%8)343TESTWILL ALWAYSCONTAINANOUTERREFERENCETHATLINKSTHESUBQUERYTOTHEROWCURRENTLYBEINGTESTED BYTHEMAINQUERY
1UANTIFIEDõ4ESTSõ!.9õANDõ!,,
4HESUBQUERYVERSIONOFTHE).TESTCHECKSWHETHERADATAVALUEISEQUALTOSOMEVALUEINA COLUMNOFSUBQUERYRESULTS31,PROVIDESTWOQUANTIFIEDTESTS !.9AND!,, THATEXTEND THISNOTIONTOOTHERCOMPARISONOPERATORS SUCHASGREATERTHAN ANDLESSTHAN "OTHOF THESETESTSCOMPAREADATAVALUEWITHTHECOLUMNOFDATAVALUESPRODUCEDBYASUBQUERY AS SHOWNIN&IGURE
1, ÊÈÊ +Õ>Ìwi`ÊV«>ÀÃÊÌiÃÌÃÊ!.9Ê>`Ê!,,®ÊÃÞÌ>ÝÊ`>}À>Ã
#HAPTERçç
3UBQUERIESçANDç1UERYç%XPRESSIONSç
4HEõ!.9õ4EST
4HE!.9TESTISUSEDINCONJUNCTIONWITHONEOFTHESIX31,COMPARISONOPERATORS TOCOMPAREASINGLETESTVALUEWITHACOLUMNOFDATAVALUESPRODUCEDBYASUBQUERY 4OPERFORMTHETEST 31,USESTHESPECIFIEDCOMPARISONOPERATORTOCOMPARETHETESTVALUEWITH EACHDATAVALUEINTHECOLUMN ONEATATIME)FANYOFTHEINDIVIDUALCOMPARISONSYIELDSA425% RESULT THE!.9TESTRETURNSA425%RESULT (EREISANEXAMPLEOFAREQUESTTHATCANBEHANDLEDWITHTHE!.9TEST ,ISTTHESALESPEOPLEWHOHAVETAKENANORDERTHATREPRESENTSMORETHANPERCENTOFTHEIRQUOTA
#ONCEPTUALLY THEMAINQUERYTESTSEACHROWOFTHE3!,%32%03TABLE ONEBYONE4HE SUBQUERYFINDSALLOFTHEORDERSTAKENBYTHECURRENTSALESPERSONANDRETURNSACOLUMN CONTAININGTHEORDERAMOUNTSFORTHOSEORDERS4HE7(%2%CLAUSEOFTHEMAINQUERYTHEN COMPUTESPERCENTOFTHECURRENTSALESPERSONSQUOTAANDUSESITASATESTVALUE COMPARINGITWITHEVERYORDERAMOUNTPRODUCEDBYTHESUBQUERY)FANYORDERAMOUNT EXCEEDSTHECALCULATEDTESTVALUE THE!.9TESTRETURNS425% ANDTHESALESPERSONISINCLUDED INTHEQUERYRESULTS)FNOT THESALESPERSONISNOTINCLUDEDINTHEQUERYRESULTS4HEKEYWORD 3/-%ISANALTERNATIVEFOR!.9SPECIFIEDBYTHE!.3))3/31,STANDARD%ITHERKEYWORD GENERALLYCANBEUSED BUTSOME$"-3BRANDSDONOTSUPPORT3/-% 4HE!.9TESTCANSOMETIMESBEDIFFICULTTOUNDERSTANDBECAUSEITINVOLVESANENTIRESET OFCOMPARISONS NOTJUSTONE)THELPSIFYOUREADTHETESTINASLIGHTLYDIFFERENTWAYTHANIT APPEARSINTHESTATEMENT)FTHIS!.9TESTAPPEARS 7(%2%8!.93%,%#49x
INSTEADOFREADINGTHETESTLIKETHIS WHERE8ISLESSTHANANYSELECT9x
TRYREADINGITLIKETHIS WHERE FORSOME9 8ISLESSTHAN9
7HENYOUUSETHISTRICK THEPRECEDINGQUERYBECOMES 3ELECTTHESALESPEOPLEWHERE FORSOMEORDERTAKENBYTHESALESPERSON PERCENTOFTHE SALESPERSONSQUOTAISLESSTHANTHEORDERAMOUNT )FTHESUBQUERYINAN!.9TESTPRODUCESNOROWSOFQUERYRESULTS ORIFTHEQUERYRESULTS INCLUDE.5,,VALUES THEOPERATIONOFTHE!.9TESTMAYVARYFROMONE$"-3TOANOTHER
0!24ç))
3%,%#4.!-% &2/-3!,%32%03 7(%2% 15/4! !.93%,%#4!-/5.4 &2/-/2$%23 7(%2%2%0%-0,?.5- .!-%
3AM#LARK ,ARRY&ITCH .ANCY!NGELLI
ç
0ARTç))ç
2ETRIEVINGç$ATA
4HE!.3))3/31,STANDARDSPECIFIESTHESEDETAILEDRULESDESCRIBINGTHERESULTSOFTHE!.9 TESTWHENTHETESTVALUEISCOMPAREDWITHTHECOLUMNOFSUBQUERYRESULTS s )FTHESUBQUERYPRODUCESANEMPTYCOLUMNOFQUERYRESULTS THE!.9TESTRETURNS &!,3%NOVALUEISPRODUCEDBYTHESUBQUERYFORWHICHTHECOMPARISONTESTHOLDS s )FTHECOMPARISONTESTIS425%FORATLEASTONEOFTHEDATAVALUESINTHECOLUMN THEN THE!.9SEARCHCONDITIONRETURNS425%INDEEDSOMEVALUEISPRODUCEDBYTHE SUBQUERYFORWHICHTHECOMPARISONTESTHOLDS s )FTHECOMPARISONTESTIS&!,3%FOREVERYDATAVALUEINTHECOLUMN THENTHE!.9 SEARCHCONDITIONRETURNS&!,3%)NTHISCASE YOUCANCONCLUSIVELYSTATETHATNO VALUEISPRODUCEDBYTHESUBQUERYFORWHICHTHECOMPARISONTESTHOLDS s )FTHECOMPARISONTESTISNOT425%FORANYDATAVALUEINTHECOLUMN BUTITIS.5,, UNKNOWN FORONEORMOREOFTHEDATAVALUES THENTHE!.9SEARCHCONDITIONRETURNS .5,,)NTHISSITUATION YOUCANNOTCONCLUSIVELYSTATEWHETHERAVALUEISPRODUCED BYTHESUBQUERYFORWHICHTHECOMPARISONTESTHOLDSITMAYORMAYNOTBE DEPENDINGONTHEhACTUALvBUTCURRENTLYUNKNOWN VALUESFORTHE.5,,DATA 4HE!.9COMPARISONOPERATORCANBEVERYTRICKYTOUSEINPRACTICE ESPECIALLYINCONJUNCTION WITHTHEINEQUALITY COMPARISONOPERATOR(EREISANEXAMPLETHATSHOWSTHEPROBLEM ,ISTTHENAMESANDAGESOFALLTHEPEOPLEINTHESALESFORCEWHODONOTMANAGEANOFlCE )TSTEMPTINGTOEXPRESSTHISQUERYASSHOWNINTHISEXAMPLE 3%,%#4.!-% !'% &2/-3!,%32%03 7(%2%%-0,?.5-!.93%,%#4-'2 &2/-/&&)#%3
4HESUBQUERY 3%,%#4-'2 &2/-/&&)#%3
OBVIOUSLYPRODUCESTHEEMPLOYEENUMBERSOFTHEMANAGERS ANDTHEREFORETHEQUERYSEEMS TOBESAYING &INDEACHSALESPERSONWHOISNOTTHEMANAGEROFANYOFlCE "UTTHATSNOTWHATTHEQUERYSAYS7HATITDOESSAYISTHIS &INDEACHSALESPERSONWHO FORSOMEOFlCE ISNOTTHEMANAGEROFTHATOFlCE /FCOURSEFORANYGIVENSALESPERSON ITSPOSSIBLETOFINDSOMEOFFICEWHERETHAT SALESPERSONISNOTTHEMANAGER4HEQUERYRESULTSWOULDINCLUDEALLTHESALESPEOPLEAND THEREFOREFAILTOANSWERTHEQUESTIONTHATWASPOSED4HECORRECTQUERYIS 3%,%#4.!-% !'% &2/-3!,%32%03 7(%2%./4%-0,?.5-!.93%,%#4-'2 &2/-/&&)#%3
#HAPTERçç
3UBQUERIESçANDç1UERYç%XPRESSIONSç
.!-%!'%
-ARY*ONES 3UE3MITH $AN2OBERTS 4OM3NYDER 0AUL#RUZ .ANCY!NGELLI
3%,%#4.!-% !'% &2/-3!,%32%03 7(%2%./4%8)3433%,%#4 &2/-/&&)#%3 7(%2%%-0,?.5--'2 .!-%!'%
-ARY*ONES 3UE3MITH $AN2OBERTS 4OM3NYDER 0AUL#RUZ .ANCY!NGELLI
4HEõ!,,õ4EST
,IKETHE!.9TEST THE!,,TESTISUSEDINCONJUNCTIONWITHONEOFTHESIX31,COMPARISON OPERATORS TOCOMPAREASINGLETESTVALUEWITHACOLUMNOFDATAVALUES PRODUCEDBYASUBQUERY4OPERFORMTHETEST 31,USESTHESPECIFIEDCOMPARISONOPERATORTO COMPARETHETESTVALUEWITHEACHDATAVALUEINTHECOLUMN ONEATATIME)FALLOFTHE INDIVIDUALCOMPARISONSYIELDA425%RESULT THE!,,TESTRETURNSA425%RESULT (EREISANEXAMPLEOFAREQUESTTHATCANBEHANDLEDWITHTHE!,,TEST ,ISTTHEOFlCESANDTHEIRTARGETSWHEREALLOFTHESALESPEOPLEHAVESALESTHATEXCEEDPERCENTOFTHE OFlCESTARGET 3%,%#4#)49 4!2'%4 &2/-/&&)#%3 7(%2% 4!2'%4 !,,3%,%#43!,%3 &2/-3!,%32%03 7(%2%2%0?/&&)#%/&&)#% #)494!2'%4
$ENVER .EW9ORK !TLANTA
0!24ç))
9OUCANALWAYSTURNAQUERYWITHAN!.9TESTINTOAQUERYWITHAN%8)343TESTBY MOVINGTHECOMPARISONINSIDETHESEARCHCONDITIONOFTHESUBQUERY4HISISUSUALLYAVERY GOODIDEABECAUSEITELIMINATESERRORSLIKETHEONEJUSTDESCRIBED(EREISANALTERNATIVEFORM OFTHEQUERY USINGTHE%8)343TEST
ç
0ARTç))ç
2ETRIEVINGç$ATA
#ONCEPTUALLY THEMAINQUERYTESTSEACHROWOFTHE/&&)#%3TABLE ONEBYONE4HE SUBQUERYFINDSALLOFTHESALESPEOPLEWHOWORKINTHECURRENTOFFICEANDRETURNSACOLUMN CONTAININGTHESALESFOREACHSALESPERSON4HE7(%2%CLAUSEOFTHEMAINQUERYTHEN COMPUTESPERCENTOFTHEOFFICESTARGETANDUSESITASATESTVALUE COMPARINGITWITHEVERY SALESVALUEPRODUCEDBYTHESUBQUERY)FALLOFTHESALESVALUESEXCEEDTHECALCULATEDTEST VALUE THE!,,TESTRETURNS425% ANDTHEOFFICEISINCLUDEDINTHEQUERYRESULTS)FNOT THE OFFICEISNOTINCLUDEDINTHEQUERYRESULTS ,IKETHE!.9TEST THE!,,TESTCANBEDIFFICULTTOUNDERSTANDBECAUSEITINVOLVESAN ENTIRESETOFCOMPARISONS NOTJUSTONE!GAIN ITHELPSIFYOUREADTHETESTINASLIGHTLY DIFFERENTWAYTHANITAPPEARSINTHESTATEMENT)FTHIS!,,TESTAPPEARS 7(%2%8!,,3%,%#49x
INSTEADOFREADINGITLIKETHIS WHERE8ISLESSTHANALLSELECT9x
TRYREADINGTHETESTLIKETHIS WHERE FORALL9 8ISLESSTHAN9
7HENYOUUSETHISTRICK THEPRECEDINGQUERYBECOMES 3ELECTTHEOFlCESWHERE FORALLSALESPEOPLEWHOWORKINTHEOFlCE PERCENTOFTHEOFlCESTARGET ISLESSTHANTHESALESPERSONSSALES )FTHESUBQUERYINAN!,,TESTPRODUCESNOROWSOFQUERYRESULTS ORIFTHEQUERYRESULTS INCLUDE.5,,VALUES THEOPERATIONOFTHE!,,TESTMAYVARYFROMONE$"-3TOANOTHER 4HE!.3))3/31,STANDARDSPECIFIESTHESEDETAILEDRULESDESCRIBINGTHERESULTSOFTHE!,, TESTWHENTHETESTVALUEISCOMPAREDWITHTHECOLUMNOFSUBQUERYRESULTS s )FTHESUBQUERYPRODUCESANEMPTYCOLUMNOFQUERYRESULTS THE!,,TESTRETURNS 425%4HECOMPARISONTESTDOESHOLDFOREVERYVALUEPRODUCEDBYTHESUBQUERY THEREJUSTARENTANYVALUES s )FTHECOMPARISONTESTIS425%FOREVERYDATAVALUEINTHECOLUMN THENTHE!,, SEARCHCONDITIONRETURNS425%!GAIN THECOMPARISONTESTHOLDSTRUEFOREVERY VALUEPRODUCEDBYTHESUBQUERY s )FTHECOMPARISONTESTIS&!,3%FORANYDATAVALUEINTHECOLUMN THENTHE!,, SEARCHCONDITIONRETURNS&!,3%)NTHISCASE YOUCANCONCLUSIVELYSTATETHATTHE COMPARISONTESTDOESNOTHOLDTRUEFOREVERYDATAVALUEPRODUCEDBYTHEQUERY s )FTHECOMPARISONTESTISNOT&!,3%FORANYDATAVALUEINTHECOLUMN BUTITIS.5,, FORONEORMOREOFTHEDATAVALUES THENTHE!,,SEARCHCONDITIONRETURNS.5,,)N THISSITUATION YOUCANNOTCONCLUSIVELYSTATEWHETHERAVALUEISPRODUCEDBYTHE SUBQUERYFORWHICHTHECOMPARISONTESTDOESNOTHOLDTRUETHEREMAYORMAYNOT BE DEPENDINGONTHEhACTUALvBUTCURRENTLYUNKNOWN VALUESFORTHE.5,,DATA 4HESUBTLEERRORSTHATCANOCCURWHENTHE!.9TESTISCOMBINEDWITHTHEINEQUALITY COMPARISONOPERATORALSOOCCURWITHTHE!,,TEST!SWITHTHE!.9TEST THE!,,TESTCAN ALWAYSBECONVERTEDINTOANEQUIVALENT%8)343TESTBYMOVINGTHECOMPARISONINSIDETHE SUBQUERY
#HAPTERçç
3UBQUERIESçANDç1UERYç%XPRESSIONSç
3UBQUERIESõANDõ*OINS 9OUMAYHAVENOTICEDASYOUREADTHROUGHTHISCHAPTERTHATMANYOFTHEQUERIESTHATWERE WRITTENUSINGSUBQUERIESCOULDALSOHAVEBEENWRITTENASMULTITABLEQUERIES ORJOINS4HISISOFTEN THECASE AND31,ALLOWSYOUTOWRITETHEQUERYEITHERWAY4HISEXAMPLEILLUSTRATESTHEPOINT ,ISTTHENAMESANDAGESOFSALESPEOPLEWHOWORKINOFlCESINTHE7ESTERNREGION
4HISFORMOFTHEQUERYCLOSELYPARALLELSTHESTATEDREQUEST4HESUBQUERYYIELDSALISTOF OFFICESINTHE7ESTERNREGION ANDTHEMAINQUERYFINDSTHESALESPEOPLEWHOWORKINONEOF THEOFFICESINTHELIST(EREISANALTERNATIVEFORMOFTHEQUERY USINGATWO TABLEJOIN ,ISTTHENAMESANDAGESOFSALESPEOPLEWHOWORKINOFlCESINTHE7ESTERNREGION 3%,%#4.!-% !'% &2/-3!,%32%03 /&&)#%3 7(%2%2%0?/&&)#%/&&)#% !.$2%')/.g7ESTERNg .!-%!'%
3UE3MITH ,ARRY&ITCH .ANCY!NGELLI
4HISFORMOFTHEQUERYJOINSTHE3!,%32%03TABLETOTHE/&&)#%3TABLETOFINDTHE REGIONWHEREEACHSALESPERSONWORKS ANDTHENELIMINATESTHOSEWHODONOTWORKINTHE 7ESTERNREGION!NOTHERWAYTOWRITETHISQUERYISWITHTHE%8)343OPERATOR ,ISTTHENAMESANDAGESOFSALESPEOPLEWHOWORKINOFlCESINTHE7ESTERNREGION 3%,%#4.!-% !'% &2/-3!,%32%03 7(%2%%8)3433%,%#4 &2/-/&&)#%3 7(%2%2%')/.g7ESTERNg !.$2%0?/&&)#%/&&)#% .!-%!'%
3UE3MITH ,ARRY&ITCH .ANCY!NGELLI
0!24ç))
3%,%#4.!-% !'% &2/-3!,%32%03 7(%2%2%0?/&&)#%).3%,%#4/&&)#% &2/-/&&)#%3 7(%2%2%')/.g7ESTERNg .!-%!'%
3UE3MITH ,ARRY&ITCH .ANCY!NGELLI
ç
0ARTç))ç
2ETRIEVINGç$ATA
!NYOFTHETHREEQUERIESWILLFINDTHECORRECTSALESPEOPLE ANDNONEOFTHEMISRIGHTOR WRONG-ANYPEOPLEWILLFINDTHEFIRSTFORMWITHTHESUBQUERY MORENATURAL BECAUSETHE %NGLISHREQUESTDOESNTASKFORANYINFORMATIONABOUTOFFICES ANDBECAUSEITSEEMSALITTLE STRANGETOJOINTHE3!,%32%03AND/&&)#%3TABLESTOANSWERTHEREQUEST/FCOURSEIFTHE REQUESTISCHANGEDTOASKFORSOMEINFORMATIONFROMTHE/&&)#%3TABLE ,ISTTHENAMESANDAGESOFTHESALESPEOPLEWHOWORKINOFlCESINTHE7ESTERNREGIONANDTHE CITIESWHERETHEYWORK THESUBQUERYFORMWILLNOLONGERWORK ANDTHETWO TABLEQUERYMUSTBEUSED#ONVERSELY MANYQUERIESWITHSUBQUERIESCANNOTBETRANSLATEDINTOANEQUIVALENTJOIN(EREISASIMPLE EXAMPLE ,ISTTHENAMESANDAGESOFSALESPEOPLEWHOHAVEABOVEAVERAGEQUOTAS 3%,%#4.!-% !'% &2/-3!,%32%03 7(%2%15/4!3%,%#4!6'15/4! &2/-3!,%32%03 .!-%!'%
"ILL!DAMS 3UE3MITH ,ARRY&ITCH
)NTHISCASE THEINNERQUERYISASUMMARYQUERYANDTHEOUTERQUERYISNOT SOTHEREIS NOWAYTHETWOQUERIESCANBECOMBINEDINTOASINGLEJOIN
.ESTEDõ3UBQUERIES !LLOFTHEQUERIESDESCRIBEDTHUSFARINTHISCHAPTERHAVEBEENTWO LEVELQUERIES INVOLVINGA MAINQUERYANDASUBQUERY*USTASYOUCANUSEASUBQUERYINSIDEAMAINQUERY YOUCAN USEASUBQUERYINSIDEANOTHERSUBQUERY(EREISANEXAMPLEOFAREQUESTTHATISNATURALLY REPRESENTEDASATHREE LEVELQUERY WITHAMAINQUERY ASUBQUERY ANDASUB SUBQUERY ,ISTTHECUSTOMERSWHOSESALESPEOPLEAREASSIGNEDTOOFlCESINTHE%ASTERNSALESREGION 3%,%#4#/-0!.9 &2/-#534/-%23 7(%2%#534?2%0).3%,%#4%-0,?.5- &2/-3!,%32%03 7(%2%2%0?/&&)#%).3%,%#4/&&)#% &2/-/&&)#%3 7(%2%2%')/.g%ASTERNg #/-0!.9
&IRST#ORP 3MITHSON#ORP !!!)NVESTMENTS *#0)NC #HEN!SSOCIATES
#HAPTERçç
3UBQUERIESçANDç1UERYç%XPRESSIONSç
1-!!SSOC )AN3CHMIDT !CME-FG
)NTHISEXAMPLE THEINNERMOSTSUBQUERY 3%,%#4/&&)#% &2/-/&&)#%3 7(%2%2%')/.g%ASTERNg
3%,%#4%-0,?.5- &2/-3!,%32%03 7(%2%2%0?/&&)#%).SUBQUERY
PRODUCESACOLUMNCONTAININGTHEEMPLOYEENUMBERSOFTHESALESPEOPLEWHOWORKINONE OFTHESELECTEDOFFICES&INALLY THEOUTERMOSTQUERY 3%,%#4#/-0!.9 &2/-#534/-%23 7(%2%#534?2%0).SUBQUERY
FINDSTHECUSTOMERSWHOSESALESPEOPLEHAVEONEOFTHESELECTEDEMPLOYEENUMBERS 4HESAMETECHNIQUEUSEDINTHISTHREE LEVELQUERYCANBEUSEDTOBUILDQUERIESWITHFOUR ORMORELEVELS4HE!.3))3/31,STANDARDDOESNOTSPECIFYAMAXIMUMNUMBEROF NESTINGLEVELS BUTINPRACTICE AQUERYBECOMESMUCHMORETIME CONSUMINGASTHENUMBER OFLEVELSINCREASES4HEQUERYALSOBECOMESMOREDIFFICULTTOREAD UNDERSTAND ANDMAINTAIN WHENITINVOLVESMORETHANONEORTWOLEVELSOFSUBQUERIES-ANY31,IMPLEMENTATIONS RESTRICTTHENUMBEROFSUBQUERYLEVELSTOARELATIVELYSMALLNUMBER
#ORRELATEDõ3UBQUERIES
)NCONCEPT 31,PERFORMSASUBQUERYOVERANDOVERAGAINONCEFOREACHROWOFTHEMAIN QUERY&ORMANYSUBQUERIES HOWEVER THESUBQUERYPRODUCESTHESAMERESULTSFOREVERYROW ORROWGROUP(EREISANEXAMPLE ,ISTTHESALESOFlCESWHOSESALESAREBELOWTHEAVERAGETARGET 3%,%#4#)49 &2/-/&&)#%3 7(%2%3!,%33%,%#4!6'4!2'%4 &2/-/&&)#%3 #)49
$ENVER !TLANTA
0!24ç))
PRODUCESACOLUMNCONTAININGTHEOFFICENUMBERSOFTHEOFFICESINTHE%ASTERNREGION4HE NEXTSUBQUERY
ç
0ARTç))ç
2ETRIEVINGç$ATA
)NTHISQUERY ITWOULDBESILLYTOPERFORMTHESUBQUERYFIVETIMESONCEFOREACH OFFICE 4HEAVERAGETARGETDOESNTCHANGEWITHEACHOFFICEITSCOMPLETELYINDEPENDENT OFTHEOFFICECURRENTLYBEINGTESTED!SARESULT 31,CANHANDLETHEQUERYBYFIRST PERFORMINGTHESUBQUERY YIELDINGTHEAVERAGETARGET ANDTHENCONVERTING THEMAINQUERYINTO 3%,%#4#)49 &2/-/&&)#%3 7(%2%3!,%3
#OMMERCIAL31,IMPLEMENTATIONSAUTOMATICALLYDETECTTHISSITUATIONANDUSETHISSHORTCUT WHENEVERPOSSIBLETOREDUCETHEAMOUNTOFPROCESSINGREQUIREDBYASUBQUERY(OWEVER THE SHORTCUTCANNOTBEUSEDIFTHESUBQUERYCONTAINSANOUTERREFERENCE ASINTHISEXAMPLE ,ISTALLOFTHEOFlCESWHOSETARGETSEXCEEDTHESUMOFTHEQUOTASOFTHESALESPEOPLEWHOWORKINTHEM 3%,%#4#)49 &2/-/&&)#%3 7(%2%4!2'%43%,%#435-15/4! &2/-3!,%32%03 7(%2%2%0?/&&)#%/&&)#% #)49
#HICAGO ,OS!NGELES
&OREACHROWOFTHE/&&)#%3TABLETOBETESTEDBYTHE7(%2%CLAUSEOFTHEMAINQUERY THE/&&)#%COLUMNWHICHAPPEARSINTHESUBQUERYASANOUTERREFERENCE HASADIFFERENT VALUE4HUS 31,HASNOCHOICEBUTTOCARRYOUTTHISSUBQUERYFIVETIMESONCEFOREACH ROWINTHE/&&)#%3TABLE!SUBQUERYCONTAININGANOUTERREFERENCEISCALLEDACORRELATED SUBQUERYBECAUSEITSRESULTSARECORRELATEDWITHEACHINDIVIDUALROWOFTHEMAINQUERY &ORTHESAMEREASON ANOUTERREFERENCEISSOMETIMESCALLEDACORRELATEDREFERENCE !SUBQUERYCANCONTAINANOUTERREFERENCETOATABLEINTHE&2/-CLAUSEOFANYQUERY THATCONTAINSTHESUBQUERY NOMATTERHOWDEEPLYTHESUBQUERIESARENESTED!COLUMN NAMEINAFOURTH LEVELSUBQUERY FOREXAMPLE MAYREFERTOONEOFTHETABLESNAMEDINTHE &2/-CLAUSEOFTHEMAINQUERY ORTOATABLENAMEDINTHE&2/-CLAUSEOFTHESECOND LEVEL SUBQUERYORTHETHIRD LEVELSUBQUERYTHATCONTAINSIT2EGARDLESSOFTHELEVELOFNESTING AN OUTERREFERENCEALWAYSTAKESONTHEVALUEOFTHECOLUMNINTHECURRENTROWOFTHETABLE BEINGTESTED "ECAUSEASUBQUERYCANCONTAINOUTERREFERENCES THEREISEVENMOREPOTENTIALFOR AMBIGUOUSCOLUMNNAMESINASUBQUERYTHANINAMAINQUERY7HENANUNQUALIFIED COLUMNNAMEAPPEARSWITHINASUBQUERY 31,MUSTDETERMINEWHETHERITREFERSTOATABLE INTHESUBQUERYSOWN&2/-CLAUSE ORTOA&2/-CLAUSEINAQUERYCONTAININGTHESUBQUERY 4OMINIMIZETHEPOSSIBILITYOFCONFUSION 31,ALWAYSINTERPRETSACOLUMNREFERENCEIN
#HAPTERçç
3UBQUERIESçANDç1UERYç%XPRESSIONSç
ASUBQUERYUSINGTHENEAREST&2/-CLAUSEPOSSIBLE4OILLUSTRATETHISPOINT INTHISEXAMPLE THESAMETABLEISUSEDINTHEQUERYANDINTHESUBQUERY ,ISTTHESALESPEOPLEWHOAREOVERANDWHOMANAGEASALESPERSONWHOISOVERQUOTA
4HE-!.!'%2 15/4! AND3!,%3COLUMNSINTHESUBQUERYAREREFERENCESTOTHE 3!,%32%03TABLEINTHESUBQUERYSOWN&2/-CLAUSE31,DOESNOTINTERPRETTHEMASOUTER REFERENCES ANDTHESUBQUERYISNOTACORRELATEDSUBQUERY31,CANPERFORMTHESUBQUERY FIRSTINTHISCASE FINDINGTHESALESPEOPLEWHOAREOVERQUOTAANDGENERATINGALISTOFTHE EMPLOYEENUMBERSOFTHEIRMANAGERS31,CANTHENTURNITSATTENTIONTOTHEMAINQUERY SELECTINGMANAGERSWHOSEEMPLOYEENUMBERSAPPEARINTHEGENERATEDLIST )FYOUWANTTOUSEANOUTERREFERENCEWITHINASUBQUERYLIKETHEONEINTHEPREVIOUS EXAMPLE YOUMUSTUSEATABLEALIASTOFORCETHEOUTERREFERENCE4HISREQUEST WHICHADDS ONEMOREQUALIFYINGCONDITIONTOTHEPREVIOUSONE SHOWSHOW ,ISTTHEMANAGERSWHOAREOVERANDWHOMANAGEASALESPERSONWHOISOVERQUOTAANDWHODOES NOTWORKINTHESAMESALESOFlCEASTHEMANAGER 3%,%#4.!-% &2/-3!,%32%03-'23 7(%2%!'% !.$-'23%-0,?.5-).3%,%#4-!.!'%2 &2/-3!,%32%03%-03 7(%2%%-0315/4!%-033!,%3 !.$%-032%0?/&&)#%-'232%0?/&&)#% .!-%
3AM#LARK ,ARRY&ITCH
4HECOPYOFTHE3!,%32%03TABLEUSEDINTHEMAINQUERYNOWHASTHETAG-'23 AND THECOPYINTHESUBQUERYHASTHETAG%-034HESUBQUERYCONTAINSONEADDITIONALSEARCH CONDITION REQUIRINGTHATTHEEMPLOYEESOFFICENUMBERDOESNOTMATCHTHATOFTHEMANAGER 4HEQUALIFIEDCOLUMNNAME-'232%0?/&&)#%INTHESUBQUERYISANOUTERREFERENCE AND THISSUBQUERYISACORRELATEDSUBQUERY
0!24ç))
3%,%#4.!-% &2/-3!,%32%03 7(%2%!'% !.$%-0,?.5-).3%,%#4-!.!'%2 &2/-3!,%32%03 7(%2%3!,%315/4! .!-%
3AM#LARK ,ARRY&ITCH
ç
0ARTç))ç
2ETRIEVINGç$ATA
3UBQUERIESõINõTHEõ(!6).'õ#LAUSE
!LTHOUGHSUBQUERIESAREMOSTOFTENFOUNDINTHE7(%2%CLAUSE THEYCANALSOBEUSEDINTHE (!6).'CLAUSEOFAQUERY7HENASUBQUERYAPPEARSINTHE(!6).'CLAUSE ITWORKSASPARTOF THEROWGROUPSELECTIONPERFORMEDBYTHE(!6).'CLAUSE#ONSIDERTHISQUERYWITHASUBQUERY ,ISTTHESALESPEOPLEWHOSEAVERAGEORDERSIZEFORPRODUCTSMANUFACTUREDBY!#)ISHIGHERTHANTHE OVERALLAVERAGEORDERSIZE 3%,%#4.!-% !6'!-/5.4 &2/-3!,%32%03 /2$%23 7(%2%%-0,?.5-2%0 !.$-&2g!#)g '2/50"9.!-% (!6).'!6'!-/5.4 3%,%#4!6'!-/5.4 &2/-/2$%23 .!-%!6'!-/5.4
3UE3MITH 4OM3NYDER
&IGURE SHOWSCONCEPTUALLYHOWTHISQUERYWORKS4HESUBQUERYCALCULATESTHEOVERALL AVERAGEORDERSIZE)TISASIMPLESUBQUERYANDCONTAINSNOOUTERREFERENCES SO31,CANCALCULATE THEAVERAGEONCEANDTHENUSEITREPEATEDLYINTHE(!6).'CLAUSE4HEMAINQUERYGOESTHROUGH !&'+) !&'+)
" $ "!&'+) %" 5 5 5
5 5 5
!&'+)
&-.')021 &-.')021
*++(&,1 *++(&,1 *++(&,1 *++(&,1 *++(&,1
"!
1, ÊÇÊ -ÕLµÕiÀÞÊ«iÀ>ÌÊÊÌ
iÊ(!6).'ÊV>ÕÃi
#
5 5 5
5 5 5
#
5 5 5
5 5 5
3'/3)04 ! #"!
#HAPTERçç
3UBQUERIESçANDç1UERYç%XPRESSIONSç
,ISTTHESALESPEOPLEWHOSEAVERAGEORDERSIZEFORPRODUCTSMANUFACTUREDBY!#)ISATLEASTASBIGAS THATSALESPERSONSOVERALLAVERAGEORDERSIZE 3%,%#4.!-% !6'!-/5.4 &2/-3!,%32%03 /2$%23 7(%2%%-0,?.5-2%0 !.$-&2g!#)g '2/50"9.!-% %-0,?.5- (!6).'!6'!-/5.4 3%,%#4!6'!-/5.4 &2/-/2$%23 7(%2%2%0%-0,?.5- .!-%!6'!-/5.4
"ILL!DAMS 3UE3MITH 4OM3NYDER
)NTHISNEWEXAMPLE THESUBQUERYMUSTPRODUCETHEOVERALLAVERAGEORDERSIZEFORTHE SALESPERSONWHOSEROWGROUPISCURRENTLYBEINGTESTEDBYTHE(!6).'CLAUSE4HESUBQUERY SELECTSORDERSFORTHATPARTICULARSALESPERSON USINGTHEOUTERREFERENCE%-0,?.5-4HEOUTER REFERENCEISLEGALBECAUSE%-0,?.5-HASTHESAMEVALUEINALLROWSOFAGROUPPRODUCEDBY THEMAINQUERY
3UBQUERYõ3UMMARY 4HISCHAPTERSOFARHASDESCRIBEDSUBQUERIES WHICHALLOWYOUTOUSETHERESULTSOFONE QUERYTOHELPDEFINEANOTHERQUERY"EFOREMOVINGONTOTHEADVANCEDQUERYFACILITIESOFTHE 31,SPECIFICATION LETSSUMMARIZESUBQUERIES s !SUBQUERYISAhQUERYWITHINAQUERYv3UBQUERIESAPPEARWITHINONEOFTHE SUBQUERYSEARCHCONDITIONSINTHE7(%2%OR(!6).'CLAUSE s 7HENASUBQUERYAPPEARSINTHE7(%2%CLAUSE THERESULTSOFTHESUBQUERYAREUSED TOSELECTTHEINDIVIDUALROWSTHATCONTRIBUTEDATATOTHEQUERYRESULTS s 7HENASUBQUERYAPPEARSINTHE(!6).'CLAUSE THERESULTSOFTHESUBQUERYARE USEDTOSELECTTHEROWGROUPSTHATCONTRIBUTEDATATOTHEQUERYRESULTS s 3UBQUERIESCANBENESTEDWITHINOTHERSUBQUERIES
0!24ç))
THE/2$%23TABLE FINDINGALLORDERSFOR!#)PRODUCTS ANDGROUPSTHEMBYSALESPERSON4HE (!6).'CLAUSETHENCHECKSEACHROWGROUPTOSEEWHETHERTHEAVERAGEORDERSIZEINTHATGROUP ISBIGGERTHANTHEAVERAGEFORALLORDERS CALCULATEDEARLIER)FSO THEROWGROUPISRETAINEDIFNOT THEROWGROUPISDISCARDED&INALLY THE3%,%#4CLAUSEPRODUCESONESUMMARYROWFOREACH GROUP SHOWINGTHENAMEOFTHESALESPERSONANDTHEAVERAGEORDERSIZEFOREACH 9OUCANALSOUSEACORRELATEDSUBQUERYINTHE(!6).'CLAUSE"ECAUSETHESUBQUERYIS EVALUATEDONCEFOREACHROWGROUP HOWEVER ALLOUTERREFERENCESINTHECORRELATEDSUBQUERY MUSTBESINGLE VALUEDFOREACHROWGROUP%FFECTIVELY THISMEANSTHATTHEOUTERREFERENCE MUSTEITHERBEAREFERENCETOAGROUPINGCOLUMNOFTHEOUTERQUERYORBECONTAINEDWITHIN ACOLUMNFUNCTION)NTHELATTERCASE THEVALUEOFTHECOLUMNFUNCTIONFORTHEROWGROUP BEINGTESTEDISCALCULATEDASPARTOFTHESUBQUERYPROCESSING )FTHEPREVIOUSREQUESTISCHANGEDSLIGHTLY THESUBQUERYINTHE(!6).'CLAUSEBECOMES ACORRELATEDSUBQUERY
ç
0ARTç))ç
2ETRIEVINGç$ATA
s 4HESUBQUERYFORMOFTHECOMPARISONTESTUSESONEOFTHESIMPLECOMPARISON OPERATORSTOCOMPAREATESTVALUEWITHTHESINGLEVALUERETURNEDBYASUBQUERY s 4HESUBQUERYFORMOFTHESETMEMBERSHIPTEST). MATCHESATESTVALUETOTHESETOF VALUESRETURNEDBYASUBQUERY s 4HEEXISTENCETEST%8)343 CHECKSWHETHERASUBQUERYRETURNSANYVALUES s 4HEQUANTIFIEDTESTS!.9AND!,, USEONEOFTHESIMPLECOMPARISONOPERATORSTO COMPAREATESTVALUEWITHALLOFTHEVALUESRETURNEDBYASUBQUERY CHECKINGTOSEE WHETHERTHECOMPARISONHOLDSFORSOMEORALLOFTHEVALUES s !SUBQUERYMAYINCLUDEANOUTERREFERENCETOATABLEINANYOFTHEQUERIESTHAT CONTAINSIT LINKINGTHESUBQUERYTOTHECURRENTROWOFTHATQUERY &IGURE SHOWSTHEFINALVERSIONOFTHERULESFOR31,QUERYPROCESSING EXTENDEDTO INCLUDESUBQUERIES)TPROVIDESACOMPLETEDEFINITIONOFTHEQUERYRESULTSPRODUCEDBYA 3%,%#4STATEMENT "!%''$(%+%&('&"%&'' !'
'&'' !'& "&'' !'&##+'#&'%"( '""' &'' !'&'"!%''%!)($(%+%&('&
"% '#%"('"''&! !' (&' (&! &&! ''#%"('&'''
'%& (&##+'&&%"!'"!'"%"*"'#%"('' %'!!'"&%"*&"%*'&%"!'"!&!&%!'"&"%* '&"% ' (&"!'!&&($(%+'&($(%+&#%"% "% %"*&'&'&'
'%&(&%%!'% !!%"*&"'#%"(''!'"%"* %"(#&&"'''%"*&!%"(#)!')(&!"'%"(#!"( !&
'%&
(&##+'&&%"!'"!'"%"*%"(#%'!!'"& %"(#&"%*'&%"!'"!&!&%!'"&"%*'&"%
'
(&"!'!&&($(%+'&($(%+&#%"% "%%"* %"(#&'&'&'
"%% !!%"*"%%"*%"(#('')("' !'&'&''" #%"(&!%"*"$(%+%&('&"%& #"( !%%!(&')("' "( !!'(%%!'%"*"%%"*%"(#"%"( !(!'"!(&'(%%!'%"*%"(# &'&%( !'&"'%*&(&'!'%&'"%"*&
& !'!+(#'%"*&"$(%+%&('&''*% #%"(
'&'' !'& "&'' !'& %'$(%+%&('&"%'!)( &'' !'&!'"&!'"$(%+%&('& !'(#'%"*&(!&& &
'%&!(&&"%''$(%+%&('&&
%"*&!%'+'&#%"(%" #%&'$(%+%&('&
1, ÊnÊ -+ʵÕiÀÞÊ«ÀViÃÃ}ÊÀÕiÃÊw>ÊÛiÀî
#HAPTERçç
3UBQUERIESçANDç1UERYç%XPRESSIONSç
!DVANCEDõ1UERIES
4HE31,QUERIESDESCRIBEDTHUSFARIN#HAPTERSTHROUGHARETHEMAINSTREAMCAPABILITIES PROVIDEDBYMOST31,IMPLEMENTATIONS4HECOMBINATIONOFFEATURESTHEYREPRESENT COLUMNSELECTIONINTHE3%,%#4CLAUSE ROWSELECTIONCRITERIAINTHE7(%2%CLAUSE MULTITABLEJOINSINTHE&2/-CLAUSE SUMMARYQUERIESINTHE'2/50"9AND(!6).'CLAUSES ANDSUBQUERIESFORMORECOMPLEXREQUESTSGIVETHEUSERAPOWERFULSETOFDATARETRIEVAL ANDDATAANALYSISCAPABILITIES(OWEVER DATABASEEXPERTSHAVEPOINTEDOUTMANY LIMITATIONSOFTHESEMAINSTREAMQUERYCAPABILITIES INCLUDINGTHESE
s ,IMITEDUSEOFSUBQUERIES 4HESIMPLESTEXAMPLEOFTHISLIMITATIONISTHE31, RESTRICTIONTHATASUBQUERYCANAPPEARONLYONTHERIGHTSIDEOFACOMPARISONTESTINA 7(%2%CLAUSE4HEDATABASEREQUESTh,ISTTHEOFFICESWHERETHESUMOFTHESALESPEOPLES QUOTASISLESSTHANTHEOFFICETARGETvISMOSTDIRECTLYEXPRESSEDASTHISQUERY 3%,%#4/&&)#% &2/-/&&)#%3 7(%2%3%,%#435-15/4! &2/-3!,%32%03 7(%2%2%0?/&&)#%/&&)#% 4!2'%4
7HILETHISISNTALEGAL31,STATEMENT ITISSUPPORTEDINSUBSEQUENTVERSIONSOFTHE 31,STANDARD.ONETHELESS MOSTPEOPLEUNDERSTANDITMOREREADILYIFYOUTURNTHE INEQUALITYAROUND 3%,%#4/&&)#% &2/-/&&)#%3 7(%2%4!2'%43%,%#435-15/4! &2/-3!,%32%03 7(%2%2%0?/&&)#%/&&)#%
)NTHISSIMPLEEXAMPLE ITISNTHARDTOTURNTHELOGICAROUND BUTTHERESTRICTIONISA NUISANCEATBEST ANDITDOESPREVENTYOUFROMCOMPARINGTHERESULTSOFTWOSUBQUERIES FOREXAMPLE
0!24ç))
s .ODECISIONMAKINGWITHINQUERIES 3UPPOSEYOUWANTEDTOGENERATEATWO COLUMNREPORTFROMTHESAMPLEDATABASESHOWINGTHENAMEOFEACHSALESOFFICEAND EITHERITSANNUALSALESTARGETORITSYEAR TO DATESALES WHICHEVERISLARGER7ITHTHE MAINSTREAM31,QUERYFEATURES THISISHARDTODO/RSUPPOSEYOUHADADATABASE THATKEPTTRACKOFSALESBYQUARTERFOURCOLUMNSOFDATAFOREACHOFFICE ANDWANTED TOWRITEAPROGRAMTHATDISPLAYEDOFFICESANDTHEIRSALESFORASPECIFICUSER SUPPLIED QUARTER!GAIN THISPROGRAMISMOREDIFFICULTTOWRITEUSINGMAINSTREAM 31,QUERIES9OUMUSTINCLUDEFOURSEPARATE31,QUERIESONEFOREACHQUARTER ANDTHEPROGRAMLOGICMUSTSELECTWHICHQUERYTORUN BASEDONUSERINPUT4HIS SIMPLECASEISNTTOODIFFICULT BUTINAMOREGENERALCASE THEPROGRAMCOULDBECOME MUCHMORECOMPLEX
ç
0ARTç))ç
2ETRIEVINGç$ATA
s ,IMITED ROWEXPRESSIONS 3UPPOSEYOUWANTEDTOLISTTHESUPPLIERS ITEMNUMBERS ANDPRICESFORASETOFPRODUCTSTHATARESUBSTITUTESFORONEANOTHER#ONCEPTUALLY THESEAREASETOFPRODUCTSWHOSEIDENTIFICATIONAMANUFACTURER )$PRODUCT )$PAIR MATCHESONEOFASETOFVALUES ANDITWOULDBENATURALTOWRITETHEQUERYUSINGASET MEMBERSHIPTEST 3%,%#4-&2?)$ 02/$5#4?)$ 02)#% &2/-02/$5#43 7(%2%-&2?)$ 02/$5#4?)$ ).g!#)g g")#g x
4HE31,STANDARDDOESNTPERMITTHISKINDOFSETMEMBERSHIPTEST)NSTEAD YOU MUSTCONSTRUCTTHEQUERYASALONGSETOFINDIVIDUALCOMPARISONS CONNECTEDBY !.$SAND/2S s ,IMITED TABLEEXPRESSIONS 31,ALLOWSYOUTODEFINEAVIEWLIKETHISONEFORLARGE ORDERS 3%,%#4 &2/-/2$%23 7(%2%!-/5.4
ANDTHENTOUSETHEVIEWASIFITWEREAREALTABLEINTHE&2/-CLAUSEOFAQUERYTO FINDOUTWHICHPRODUCTS INWHICHQUANTITIES WEREORDEREDINTHESELARGEORDERS 3%,%#4-&2 02/$5#4 35-149 &2/-")'/2$%23 '2/50"9-&2 02/$5#4
#ONCEPTUALLY 31,SHOULDLETYOUSUBSTITUTETHEVIEWDEFINITIONRIGHTINTOTHEQUERY LIKETHIS 3%,%#4-&2 02/$5#4 35-149 &2/-3%,%#4 &2/-/2$%237(%2%!-/5.4 ! '2/50"9-&2 02/$5#4
"UTTHE31,STANDARDDOESNTALLOWASUBQUERYINTHISPOSITIONINTHE7(%2%CLAUSE 9ETCLEARLY THE$"-3SHOULDBEABLETODETERMINETHEMEANINGOFTHISQUERY SINCEITMUST BASICALLYDOTHESAMEPROCESSINGTOINTERPRETTHE")'/2$%23VIEWDEFINITION !STHESEEXAMPLESSHOW THE31,STANDARDAND$"-3PRODUCTSTHATIMPLEMENTTOTHIS LEVELOFTHESTANDARDARERELATIVELYRESTRICTIVEINTHEIRPERMITTEDUSEOFEXPRESSIONSINVOLVING INDIVIDUALDATAITEMS SETSOFDATAITEMS ROWS ANDTABLES3UBSEQUENTVERSIONSOFTHE31, STANDARDINCLUDEANUMBEROFADVANCEDQUERYCAPABILITIESTHATAREFOCUSEDONREMOVING THESERESTRICTIONSANDMAKINGTHE31,LANGUAGEMOREGENERAL4HESPIRITOFTHESECAPABILITIES TENDSTOBETHATAUSERSHOULDBEABLETOWRITEAQUERYEXPRESSIONTHATMAKESSENSEAND HAVETHEQUERYEXPRESSIONBEALEGAL31,QUERY"ECAUSETHESECAPABILITIESCONSTITUTEMAJOR EXPANSIONSOFTHELANGUAGEOVERTHEORIGINAL31,STANDARD MOSTOFTHEMAREREQUIRED ONLYATAFULLLEVELOFTHESTANDARD
#HAPTERçç
3UBQUERIESçANDç1UERYç%XPRESSIONSç
3CALAR 6ALUEDõ%XPRESSIONS 4HESIMPLESTEXTENDEDQUERYCAPABILITIESIN31,ARETHOSETHATPROVIDEMOREDATAMANIPULATION ANDCALCULATIONPOWERINVOLVINGINDIVIDUALDATAVALUESCALLEDSCALARSINTHE31,STANDARD 7ITHINTHE31,LANGUAGE INDIVIDUALDATAVALUESTENDTOHAVETHREESOURCES s 4HEVALUEOFANINDIVIDUALCOLUMNWITHINANINDIVIDUALROWOFATABLE s !LITERALVALUE SUCHASOR!"# s !USER SUPPLIEDDATAVALUE ENTEREDINTOAPROGRAM )NTHIS31,QUERY
0!24ç))
3%,%#4.!-% %-0,?.5- ()2%?$!4% 15/4! &2/-3!,%32%03 7(%2%2%0?/&&)#% /24)4,%g603ALESg
THECOLUMNNAMES.!-% %-0,?.5- ()2%?$!4% AND15/4!GENERATEINDIVIDUALDATA VALUESFOREACHROWOFQUERYRESULTS ASDOTHECOLUMNNAMES2%0?/&&)#%AND4)4,%IN THE7(%2%CLAUSE4HENUMBERSANDANDTHECHARACTERSTRINGh603ALESvSIMILARLY GENERATEINDIVIDUALDATAVALUES)FTHIS31,STATEMENTWERETOAPPEARWITHINANEMBEDDED 31,PROGRAMDESCRIBEDIN#HAPTER THEPROGRAMVARIABLEOFFICE?NUMMIGHTCONTAIN ANINDIVIDUALDATAVALUE ANDTHEQUERYMIGHTAPPEARAS 3%,%#4.!-% %-0,?.5- ()2%?$!4% 15/4! &2/-3!,%32%03 7(%2%2%0?/&&)#%OFFICE?NUM /24)4,%g603!,%3g
!STHISQUERYANDMANYPREVIOUSEXAMPLESHAVESHOWN INDIVIDUALDATAVALUESCANBE COMBINEDINSIMPLEEXPRESSIONS LIKETHECALCULATEDVALUE15/4! 4OTHESEBASIC EXPRESSIONS THE31,STANDARDADDSTHE#!34OPERATORFOREXPLICITDATATYPECONVERSION THE #!3%OPERATORFORDECISIONMAKING THE#/!,%3#%OPERATORFORCONDITIONALLYCREATINGNON .5,,VALUES ANDTHE.5,,)&OPERATIONFORCONDITIONALLYCREATINGA.5,,VALUE
4HEõ#!34õ%XPRESSION 4HE31,STANDARDHASFAIRLYRESTRICTIVERULESABOUTCOMBININGDATAOFDIFFERENTTYPESIN EXPRESSIONS)TSPECIFIESTHATTHE$"-3SHALLAUTOMATICALLYCONVERTAMONGVERYSIMILARDATA TYPES SUCHAS BYTEAND BYTEINTEGERS(OWEVER IFYOUTRYTOCOMPARENUMBERSAND CHARACTERDATA FOREXAMPLE THESTANDARDSAYSTHATTHE$"-3SHOULDGENERATEANERROR4HE STANDARDCONSIDERSTHISANERRORCONDITIONEVENIFTHECHARACTERSTRINGCONTAINSNUMERIC DATA9OUCAN HOWEVER EXPLICITLYASKTHE$"-3TOCONVERTAMONGDATATYPESUSINGTHE #!34EXPRESSION WHICHHASTHESYNTAXSHOWNIN&IGURE
1, ÊÊ Ê #!34ÊiÝ«ÀiÃÃÊ ÃÞÌ>ÝÊ`>}À>
ç
0ARTç))ç
2ETRIEVINGç$ATA
4HE#!34EXPRESSIONTENDSTOBEOFLITTLEIMPORTANCEWHENYOUARETYPING31, STATEMENTSDIRECTLYINTOANINTERACTIVE31,INTERFACE(OWEVER ITCANBECRITICALWHENUSING 31,FROMWITHINAPROGRAMMINGLANGUAGEWHEREDATATYPESDONTMATCHTHEDATATYPES SUPPORTEDBYTHE31,STANDARD&OREXAMPLE THE#!34EXPRESSIONINTHE3%,%#4CLAUSEOF THISQUERYCONVERTSTHEVALUESFOR2%0?/&&)#%INTEGERSINTHESAMPLEDATABASE AND()2%? $!4%ADATEINTHESAMPLEDATABASE INTOCHARACTERSTRINGSFORTHERETURNEDQUERYRESULTS 3%,%#4.!-% #!342%0?/&&)#%!3#(!2 #!34()2%?$!4%!3#(!2 &2/-3!,%32%03
3UPPORTFORTHE#!34EXPRESSIONVARIESACROSS31,IMPLEMENTATIONS&OREXAMPLE /RACLEREQUIRESTHAT#(!2AND6!2#(!2DATATYPESUSEDINA#!34EXPRESSIONINCLUDEA LENGTHSPECIFICATION WHILE-Y31,AND$"5$"DONOTSUPPORTTHE$!4%DATATYPEINA #!34EXPRESSION 4HE#!34EXPRESSIONCANGENERALLYAPPEARANYWHERETHATASCALAR VALUEDEXPRESSIONCAN APPEARWITHINA31,STATEMENT)NTHISEXAMPLE ITSUSEDINTHE7(%2%CLAUSETOCONVERTA CHARACTER STRINGCUSTOMERNUMBERINTOANINTEGER SOTHATITCANBECOMPAREDWITHTHEDATA INTHEDATABASE 3%,%#402/$5#4 149 !-/5.4 &2/-/2$%23 7(%2%#534#!34gg!3).4%'%2
)NSTEADOFSPECIFYINGADATATYPEINTHE#!34EXPRESSION YOUCANSPECIFYADOMAIN $OMAINSARESPECIFICCOLLECTIONSOFLEGALDATAVALUESTHATCANBEDEFINEDINTHEDATABASE 4HEYAREFULLYDESCRIBEDIN#HAPTERBECAUSEOFTHEROLETHEYPLAYIN31,DATAINTEGRITY .OTETHATYOUCANALSOGENERATEA.5,,VALUEOFTHEAPPROPRIATEDATATYPEFORUSEIN31, EXPRESSIONSUSINGTHE#!34EXPRESSION 4HEMOSTCOMMONUSESFORTHE#!34EXPRESSIONARE s 4OCONVERTDATAFROMWITHINADATABASETABLEWHERETHECOLUMNISDEFINEDWITHTHE WRONGDATATYPE FOREXAMPLE WHENACOLUMNISDEFINEDASACHARACTERSTRING BUT YOUKNOWITACTUALLYCONTAINSNUMBERSTHATIS STRINGSOFDIGITS ORDATESSTRINGS THATCANBEINTERPRETEDASACALENDARDATE s 4OCONVERTDATAFROMDATATYPESSUPPORTEDBYTHE$"-3THATARENOTSUPPORTEDBYA HOSTPROGRAMMINGLANGUAGE&OREXAMPLE MOSTHOSTPROGRAMMINGLANGUAGESDO NOTHAVEEXPLICITDATEANDTIMEDATATYPESANDREQUIRETHATDATETIMEVALUESBE CONVERTEDINTOCHARACTERSTRINGSFORHANDLINGBYAPROGRAM s 4OELIMINATEDIFFERENCESBETWEENDATATYPESINTWODIFFERENTTABLES&OREXAMPLE IF ANORDERDATEISSTOREDINONETABLEAS$!4%DATA BUTAPRODUCTAVAILABILITYDATEIS STOREDINADIFFERENTTABLEASACHARACTERSTRING YOUCANSTILLCOMPARETHECOLUMNS FROMTHETWOTABLESBY#!34INGONEOFTHECOLUMNSINTOTHEDATATYPEOFTHEOTHER 3IMILARLY IFYOUWANTTOCOMBINEDATAFROMTWODIFFERENTTABLESWITHA5.)/. OPERATION THEIRCOLUMNSMUSTHAVEIDENTICALDATATYPES9OUCANACHIEVETHISBY #!34INGTHECOLUMNSOFONEOFTHETABLES
#HAPTERçç
3UBQUERIESçANDç1UERYç%XPRESSIONSç
1, Ê£äÊ #!3%ÊiÝ«ÀiÃÃÊÃÞÌ>ÝÊ`>}À>
4HEõ#!3%õ%XPRESSION
3%,%#4#/-0!.9 #!3%7(%.#2%$)4?,)-)44(%.g!g 7(%.#2%$)4?,)-)44(%.g"g %,3%g#g %.$!3#2%$)4?2!4).' &2/-#534/-%23
&OREACHROWOFQUERYRESULTS THE$"-3EVALUATESTHE#!3%EXPRESSIONBYFIRST COMPARINGTHECREDITLIMITWITH ANDIFTHECOMPARISONIS425% RETURNINGAN!INTHE SECONDCOLUMNOFQUERYRESULTS)FTHATCOMPARISONFAILS THECOMPARISONTO ISMADE ANDA"ISRETURNEDIFTHISSECONDCOMPARISONIS425%/THERWISE THETHIRDCOLUMNOFQUERY RESULTSRETURNSA# 4HISISAVERYSIMPLEEXAMPLEOFA#!3%EXPRESSION4HERESULTSOFTHE#!3% EXPRESSIONAREALLLITERALSHERE BUTINGENERAL THEYCANBEANY31,EXPRESSION3IMILARLY THEREISNOREQUIREMENTTHATTHETESTSINEACH7(%.CLAUSEBESIMILAR ASTHEYAREHERE 4HE#!3%EXPRESSIONCANALSOAPPEARINOTHERCLAUSESOFAQUERYPROVIDEDTHE31, IMPLEMENTATIONSUPPORTSSUCHUSE(EREISANEXAMPLEOFAQUERYWHERETHE#!3% EXPRESSIONISUSEFULINTHE7(%2%CLAUSE3UPPOSEYOUWANTTOFINDTHETOTALOFTHE SALESPEOPLESSALES BYOFFICE)FASALESPERSONISNOTYETASSIGNEDTOANOFFICE THATPERSON
0!24ç))
4HE#!3%EXPRESSIONPROVIDESFORLIMITEDDECISION MAKINGWITHIN31,EXPRESSIONS)TSBASIC STRUCTURE SHOWNIN&IGURE ISSIMILARTOTHE)&x4(%.x%,3%STATEMENTFOUNDINMANY PROGRAMMINGLANGUAGES7HENTHE$"-3ENCOUNTERSA#!3%EXPRESSION ITEVALUATESTHE FIRSTSEARCHCONDITION ANDIFITIS425% THENTHEVALUEOFTHE#!3%EXPRESSIONISTHEVALUEOF THEFIRSTRESULTEXPRESSION)FTHERESULTOFTHEFIRSTSEARCHCONDITIONISNOT425% THE$"-3 PROCEEDSTOTHESECONDSEARCHCONDITIONANDCHECKSWHETHERITIS425%)FSO THEVALUEOF THE#!3%EXPRESSIONISTHEVALUEOFTHESECONDRESULTEXPRESSION ANDSOON (EREISASIMPLEEXAMPLEOFTHEUSEOFTHE#!3%EXPRESSION3UPPOSEYOUWANTTODOAN !"#ANALYSISOFTHECUSTOMERSFROMTHESAMPLEDATABASEACCORDINGTOTHEIRCREDITLIMITS 4HE!CUSTOMERSARETHEONESWITHCREDITLIMITSOVER THE"CUSTOMERSARETHOSEWITH LIMITSOVER ANDTHE#CUSTOMERSARETHEOTHERS7ITHOUTTHE#!3%EXPRESSION YOU WOULDHAVETORETRIEVECUSTOMERNAMESANDCREDITLIMITSFROMTHEDATABASEANDTHENRELY ONANAPPLICATIONPROGRAMTOLOOKATTHECREDITLIMITVALUESANDASSIGNAN! " OR#RATING 5SINGA#!3%EXPRESSION YOUCANHAVETHE$"-3DOTHEWORKFORYOU
ç
0ARTç))ç
2ETRIEVINGç$ATA
SHOULDBEINCLUDEDINTHETOTALFORHISORHERMANAGERSOFFICE(EREISAQUERYTHAT GENERATESTHEAPPROPRIATEOFFICEGROUPINGS 3%,%#4#)49 35-3!,%32%033!,%3 &2/-/&&)#%3 3!,%32%03 7(%2%/&&)#% #!3%7(%.2%0?/&&)#%)3./4.5,, 4(%.2%0?/&&)#% %,3%3%,%#42%0?/&&)#% &2/-3!,%32%03-'23 7(%2%-'23%-0,?.5--!.!'%2 %.$ '2/50"9#)49
4HE31,STANDARDPROVIDESASHORTHANDVERSIONOFTHE#!3%EXPRESSIONFORTHECOMMON SITUATIONWHEREYOUWANTTOCOMPAREATESTVALUEOFSOMEKINDWITHASEQUENCEOFDATA VALUESUSUALLYLITERALS 4HISVERSIONOFTHE#!3%SYNTAXISSHOWNIN&IGURE )NSTEADOF REPEATINGASEARCHCONDITIONOFTHEFORM TEST?VALUEVALUE
INEACH7(%.CLAUSE ITLETSYOUSPECIFYTHETEST?VALUECALCULATIONONCE&OREXAMPLE SUPPOSEYOUWANTEDTOGENERATEALISTOFALLOFTHEOFFICES SHOWINGTHENAMESOFTHEIR MANAGERSANDTHECITIESANDSTATESWHERETHEYARE4HESAMPLEDATABASEDOESNTINCLUDE STATENAMES SOTHEQUERYMUSTGENERATETHISINFORMATIONITSELF(EREISAQUERY WITHA#!3% EXPRESSIONINTHE3%,%#4LIST THATDOESTHEJOB 3%,%#4.!-% #)49 #!3%/&&)#%7(%.4(%.g.EW9ORKg 7(%.4(%.g)LLINOISg 7(%.4(%.g'EORGIAg 7(%.4(%.g#ALIFORNIAg 7(%.4(%.g#OLORADOg %.$!334!4% &2/-/&&)#%3 3!,%32%03 7(%2%-'2%-0,?.5-
4HEõ#/!,%3#%õ%XPRESSION /NEOFTHEMOSTCOMMONUSESFORTHEDECISION MAKINGCAPABILITYOFTHE#!3%EXPRESSIONIS FORHANDLING.5,,VALUESWITHINTHEDATABASE&OREXAMPLE ITSFREQUENTLYDESIRABLETOHAVE A.5,,VALUEFROMTHEDATABASEREPRESENTEDBYSOMELITERALVALUESUCHASTHEWORD hMISSINGv ORBYSOMEDEFAULTVALUEWHENUSING31,TOGENERATEAREPORT(EREISAREPORT THATLISTSTHESALESPEOPLEANDTHEIRQUOTAS)FASALESPERSONHASNOTYETBEENASSIGNEDA QUOTA ASSUMETHATTHESALESPERSONSACTUALYEAR TO DATESALESSHOULDBELISTEDINSTEAD)FFOR
1, Ê££Ê #!3%ÊiÝ«ÀiÃÃÊ>ÌiÀ>ÌiÊÃÞÌ>Ý
1, Ê£ÓÊ Ê #/!,%3#%Ê iÝ«ÀiÃÃÊÃÞÌ>ÝÊ `>}À>
#HAPTERçç
3UBQUERIESçANDç1UERYç%XPRESSIONSç
SOMEREASONTHEACTUALYEAR TO DATESALESAREALSO.5,,UNKNOWN THENAZEROAMOUNT SHOULDBELISTED4HE#!3%STATEMENTGENERATESTHEDESIRED)&x4(%.x%,3%LOGIC
4HISTYPEOF.5,, HANDLINGLOGICISNEEDEDFREQUENTLY SOTHE31,STANDARDINCLUDES ASPECIALIZEDFORMOFTHE#!3%EXPRESSION THE#/!,%3#%EXPRESSION TOHANDLEIT4HE SYNTAXFORTHE#/!,%3#%EXPRESSIONISSHOWNIN&IGURE 4HEPROCESSINGRULESFOR THE#/!,%3#%EXPRESSIONAREVERYSTRAIGHTFORWARD4HE$"-3EXAMINESTHEFIRSTVALUE INTHELIST)FITSVALUEISNOT.5,, ITBECOMESTHEVALUEOFTHE#/!,%3#%EXPRESSION)F THEFIRSTVALUEIS.5,, THE$"-3MOVESTOTHESECONDVALUEANDCHECKSTOSEEWHETHER ITIS.5,,)FNOT ITBECOMESTHEVALUEOFTHEEXPRESSION/THERWISE THE$"-3MOVESTO THETHIRDVALUE ANDSOON(EREISTHESAMEEXAMPLEJUSTGIVEN EXPRESSEDWITHTHE #/!,%3#%EXPRESSIONINSTEADOFA#!3%EXPRESSION 3%,%#4.!-% #/!,%3#%15/4! 3!,%3 &2/-3!,%32%03
!SYOUCANSEEBYCOMPARINGTHETWOQUERIES THESIMPLICITYOFTHE#/!,%3#%SYNTAX MAKESITEASIERTOSEE ATAGLANCE THEMEANINGOFTHEQUERY(OWEVER THEOPERATIONOFTHE TWOQUERIESISIDENTICAL4HE#/!,%3#%EXPRESSIONADDSSIMPLICITY BUTNONEWCAPABILITY TO31,
4HEõ.5,,)&õ%XPRESSION *USTASTHE#/!,%3#%EXPRESSIONISUSEDTOELIMINATE.5,,VALUESWHENTHEYARENOTDESIRED FORPROCESSING SOMETIMESYOUMAYNEEDTOCREATE.5,,VALUES)NMANYDATAPROCESSING APPLICATIONSESPECIALLYOLDERONESTHATWEREDEVELOPEDBEFORERELATIONALDATABASESWERE POPULAR MISSINGDATAISNOTREPRESENTEDBY.5,,VALUES)NSTEAD SOMESPECIALCODEVALUE THATISOTHERWISEINVALIDISUSEDTOINDICATETHATTHEDATAISMISSING &OREXAMPLE SUPPOSETHATINTHESAMPLEDATABASE THESITUATIONWHEREASALESPERSONHAD NOTYETBEENASSIGNEDAMANAGERWASINDICATEDBYAZERO VALUEINTHE-!.!'%2COLUMN INSTEADOFA.5,,VALUE)NSOMECIRCUMSTANCES YOUWILLWANTTODETECTTHISSITUATIONWITHIN A31,QUERYANDSUBSTITUTETHE.5,,VALUEFORTHEZEROhCODEv4HE.5,,)&EXPRESSION SHOWNIN&IGURE ISUSEDFORTHISPURPOSE7HENTHE$"-3ENCOUNTERSA.5,,)& EXPRESSION ITEXAMINESTHEFIRSTVALUEUSUALLYACOLUMNNAME ANDCOMPARESITWITHTHE 1, Ê£ÎÊ Ê .5,,)&Ê iÝ«ÀiÃÃÊÃÞÌ>ÝÊ `>}À>
0!24ç))
3%,%#4.!-% #!3%7(%.15/4!)3./4.5,, 4(%.15/4! 7(%.3!,%3)3./4.5,, 4(%.3!,%3 %,3% %.$!3!$*534%$?15/4! &2/-3!,%32%03
ç
0ARTç))ç
2ETRIEVINGç$ATA
SECONDVALUEUSUALLYTHECODEVALUEUSEDTOINDICATEMISSINGDATA )FTHETWOVALUESAREEQUAL THEEXPRESSIONGENERATESA.5,,VALUE/THERWISE THEEXPRESSIONGENERATESTHEFIRSTVALUE (EREISAQUERYTHATHANDLESTHECASEWHEREMISSINGOFFICENUMBERSAREREPRESENTEDBY AZERO 3%,%#4#)49 35-3!,%32%033!,%3 &2/-/&&)#%3 3!,%32%03 7(%2%/&&)#%.5,,)&2%0?/&&)#% '2/50"9#)49
4OGETHER THE#!3% #/!,%3#% AND.5,,)&EXPRESSIONSPROVIDEASOLIDDECISION MAKINGLOGICCAPABILITYFORUSEWITHIN31,STATEMENTS4HEYFALLFARSHORTOFTHECOMPLETE LOGICALFLOWCONSTRUCTSPROVIDEDBYMOSTPROGRAMMINGLANGUAGESLOOPING BRANCHING AND SOON BUTDOPROVIDEFORMUCHGREATERFLEXIBILITYINQUERYEXPRESSIONS4HENETRESULTIS THATMOREPROCESSINGWORKCANBEDONEBYTHE$"-3ANDREFLECTEDINQUERYRESULTS LEAVING LESSWORKTOBEDONEBYTHEHUMANUSERORTHEAPPLICATIONPROGRAM
2OW 6ALUEDõ%XPRESSIONS !LTHOUGHCOLUMNSANDTHESCALARDATAVALUESTHEYCONTAINARETHEATOMICBUILDINGBLOCKSOFA RELATIONALDATABASE THESTRUCTURINGOFCOLUMNSINTOROWSTHATREPRESENTREAL WORLDENTITIES SUCHASINDIVIDUALOFFICESORCUSTOMERSORORDERS ISONEOFTHEMOSTIMPORTANTFEATURESOFTHE RELATIONALMODEL4HE31,STANDARD ANDMOSTMAINSTREAMCOMMERCIALDATABASEPRODUCTS CERTAINLYREFLECTTHISROWCOLUMNSTRUCTURE BUTTHEYPROVIDEVERYLIMITEDCAPABILITYTO ACTUALLYMANIPULATEROWSANDGROUPSOFROWS"ASICALLY 31,OPERATIONSALLOWYOUTOINSERT AROWINTOATABLE ORTORETRIEVE UPDATE ORDELETEGROUPSOFROWSFROMADATABASEUSINGTHE ).3%24 3%,%#4 50$!4% OR$%,%4%STATEMENTS .EWERVERSIONSOFTHE31,STANDARDGOWELLBEYONDTHESECAPABILITIES ALLOWINGYOUTO GENERALLYUSEROWSIN31,EXPRESSIONSINMUCHTHESAMEWAYTHATYOUCANUSESCALARVALUES 4HEYPROVIDESYNTAXFORCONSTRUCTINGROWSOFDATA4HEYALLOWROW VALUEDSUBQUERIES!ND THEYDEFINEROW VALUEDMEANINGSFORTHE31,COMPARISONOPERATORSANDOTHER31,STRUCTURES
4HEõ2OW 6ALUEõ#ONSTRUCTOR 31,ALLOWSYOUTOSPECIFYAROWOFDATAVALUESBYUSINGAROW VALUECONSTRUCTOREXPRESSION WHOSESYNTAXISSHOWNIN&IGURE )NITSMOSTCOMMONFORM THEROWCONSTRUCTORISA COMMA SEPARATEDLISTOFLITERALVALUES OREXPRESSIONS&OREXAMPLE HEREISAROW VALUE CONSTRUCTORFORAROWOFDATAWHOSESTRUCTUREMATCHESTHE/&&)#%3TABLEINTHESAMPLEDATABASE g3AN$IEGOg g7ESTERNg .5,, $%&!5,4 1, Ê£{Ê Ê ,ÜÛ>ÕiÊ VÃÌÀÕVÌÀÊÃÞÌ>ÝÊ `>}À>
#HAPTERçç
3UBQUERIESçANDç1UERYç%XPRESSIONSç
4HERESULTOFTHISEXPRESSIONISASINGLEROWOFDATAWITHSIXCOLUMNS4HE.5,,KEYWORDIN THEFOURTHCOLUMNPOSITIONINDICATESTHATTHEFOURTHCOLUMNINTHECONSTRUCTEDROWSHOULD CONTAINA.5,,UNKNOWN VALUE4HE$%&!5,4KEYWORDINTHEFIFTHCOLUMNPOSITIONINDICATES THATTHEFIFTHCOLUMNINTHECONSTRUCTEDROWSHOULDCONTAINTHEDEFAULTVALUEFORTHECOLUMN 4HISKEYWORDMAYAPPEARINAROW VALUECONSTRUCTORONLYINCERTAINSITUATIONSFOREXAMPLE WHENTHEROW VALUECONSTRUCTORAPPEARSINAN).3%24STATEMENTTOADDANEWROWTOATABLE 7HENAROWCONSTRUCTORISUSEDINTHE7(%2%CLAUSEOFA31,STATEMENT COLUMNNAMES CANALSOAPPEARASINDIVIDUALDATAITEMSWITHINTHEROWCONSTRUCTOR ORASPARTOFAN EXPRESSIONWITHINTHEROWCONSTRUCTOR&OREXAMPLE CONSIDERTHISQUERY
3%,%#4/2$%2?.5- 149 !-/5.4 &2/-/2$%23 7(%2%-'2 02/$5#4 g!#)g gg
.OTETHATWHILETHISSYNTAXISSPECIFIEDINTHE31,STANDARD VERYFEW31,IMPLEMENTATIONS SUPPORTIT5NDERTHENORMALRULESOF31,QUERY PROCESSING THE7(%2%CLAUSEISAPPLIEDTO EACHROWOFTHE/2$%23TABLE ONEBYONE4HEFIRSTROW VALUECONSTRUCTORINTHE7(%2%CLAUSE TOTHELEFTOFTHEEQUALSIGN GENERATESATWO COLUMNROW CONTAININGTHEMANUFACTURERCODE ANDTHEPRODUCTNUMBERFORTHECURRENTORDERBEINGCONSIDERED4HESECONDROW VALUE CONSTRUCTORTOTHERIGHTOFTHEEQUALSIGN GENERATESATWO COLUMNROW CONTAININGTHELITERAL MANUFACTURERCODE!#)ANDPRODUCTNUMBER4HEEQUALSIGNISNOWCOMPARINGTWO ROWSOFVALUES NOTTWOSCALARVALUES4HE31,STANDARDDEFINESTHISTYPEOFROW VALUED COMPARISONFOREQUALITY WHICHISPROCESSEDBYCOMPARING PAIRWISE EACHOFTHECOLUMNSINTHE TWOROWS4HERESULTOFTHECOMPARISONIS425%ONLYIFALLOFTHEPAIRWISECOLUMNCOMPARISONS ARE425%/FCOURSE ITSPOSSIBLETOWRITETHEQUERYWITHOUTTHEROW VALUECONSTRUCTORS LIKETHIS ,ISTTHEORDERNUMBER QUANTITY ANDAMOUNTOFALLORDERSFOR!#) WIDGETS 3%,%#4/2$%2?.5- 149 !-/5.4 &2/-/2$%23 7(%2%-&2g!#)g !.$02/$5#4gg
ANDINTHISSIMPLEEXAMPLE THEMEANINGOFTHEQUERYISPROBABLYEQUALLYCLEARWITHEITHER FORM(OWEVER ROW VALUECONSTRUCTORSCANBEVERYUSEFULINSIMPLIFYINGTHEAPPEARANCEOF MORECOMPLEXQUERIES ANDTHEYBECOMEEVENMOREUSEFULWHENCOMBINEDWITHROW VALUED SUBQUERIES
2OW 6ALUEDõ3UBQUERIES !SDESCRIBEDTHROUGHOUTTHEEARLIERPARTSOFTHISCHAPTER THE31,STANDARDPROVIDESA SUBQUERYCAPABILITYFOREXPRESSINGMORECOMPLEXDATABASEQUERIES4HESUBQUERYTAKESTHE SAMEFORMASA31,QUERYTHATIS A3%,%#4STATEMENT BUTA31,SUBQUERYMUSTBE SCALAR VALUEDTHATIS ITMUSTPRODUCEASINGLEDATAVALUEASITSQUERYRESULTS4HEVALUE GENERATEDBYTHESUBQUERYISTHENUSEDASPARTOFANEXPRESSIONWITHINTHEMAIN31, STATEMENTTHATCONTAINSTHESUBQUERY4HISUSEOFSUBQUERIESISSUPPORTEDBYTHEMAJOR ENTERPRISE CLASSRELATIONALDATABASESYSTEMSTODAY 3UBSEQUENTVERSIONSOFTHE31,STANDARDDRAMATICALLYEXPANDTHESUBQUERYFACILITY INCLUDINGSUPPORTFORROW VALUEDSUBQUERIES!ROW VALUEDSUBQUERYRETURNSNOTJUSTASINGLE DATAITEM BUTAROWOFDATAITEMS WHICHCANBEUSEDIN31,EXPRESSIONSANDCOMPARED
0!24ç))
,ISTTHEORDERNUMBER QUANTITY ANDAMOUNTOFALLORDERSFOR!#) WIDGETS
ç
0ARTç))ç
2ETRIEVINGç$ATA
WITHOTHERROWS&OREXAMPLE SUPPOSEYOUWANTEDTOSHOWTHEORDERNUMBERSANDDATES FORALLOFTHEORDERSPLACEDAGAINSTTHEHIGHEST PRICEDPRODUCTINTHESAMPLEDATABASE !LOGICALWAYTOSTARTBUILDINGTHEAPPROPRIATE31,QUERYISTOFINDANEXPRESSIONTHATWILL GIVEYOUTHEIDENTITYMANUFACTURER)$ANDPRODUCT)$ OFTHEHIGH PRICEDPRODUCTIN QUESTION(EREISAQUERYTHATFINDSTHERIGHTPRODUCT &INDTHEMANUFACTURER)$ANDPRODUCT)$OFTHEPRODUCTWITHTHEHIGHESTUNITPRICE 3%,%#4-&2?)$ 02/$5#4?)$ &2/-02/$5#43 7(%2%02)#%3%,%#4-!802)#% &2/-02/$5#43
)GNORINGTHEPOSSIBILITYOFATIEFORTHEMOSTEXPENSIVEPRODUCTFORAMOMENT THISQUERY WILLGENERATEASINGLEROWOFQUERYRESULTS CONSISTINGOFTWOCOLUMNS5SING31,SROW VALUED SUBQUERYCAPABILITY YOUCANEMBEDTHISENTIREQUERYASASUBQUERYWITHINA3%,%#4STATEMENT TORETRIEVETHEORDERINFORMATION ASSHOWNINTHENEXTEXAMPLE ,ISTTHEORDERNUMBERSANDDATESOFALLORDERSPLACEDFORTHEHIGHEST PRICEDPRODUCT 3%,%#4/2$%2?.5- /2$%2?$!4% &2/-/2$%23 7(%2%-&2 02/$5#4 3%,%#4-&2?)$ 02/$5#4?)$ &2/-02/$5#43 7(%2%02)#%3%,%#4-!802)#% &2/-02/$5#43
4HETOP LEVEL7(%2%CLAUSEINTHISQUERYCONTAINSAROW VALUEDCOMPARISON/NTHELEFT SIDEOFTHEEQUALSIGNISAROW VALUECONSTRUCTORCONSISTINGOFTWOCOLUMNNAMES%ACHTIME THE7(%2%CLAUSEISEXAMINEDTOCARRYOUTTHETOP LEVELQUERY THEVALUEOFTHISROW VALUED EXPRESSIONISAMANUFACTURER )$PRODUCT )$PAIRFROMAROWOFTHE/2$%23TABLE/NTHE RIGHTSIDEOFTHEEQUALSIGNISTHESUBQUERYTHATGENERATESTHEIDENTITYOFTHEPRODUCTWITHTHE HIGHESTDOLLARVALUE4HERESULTOFTHISSUBQUERYISAGAINAROWVALUE WITHTWOCOLUMNS WHOSEDATATYPESMATCHTHOSEOFTHEROW VALUEDEXPRESSIONONTHELEFTSIDEOFTHEEQUALSIGN )TSPOSSIBLETOEXPRESSTHISQUERYWITHOUTTHEROW VALUEDSUBQUERY BUTTHERESULTING QUERYWILLBEMUCHLESSSTRAIGHTFORWARD ,ISTTHEORDERNUMBERSANDDATESOFALLORDERSPLACEDFORTHEHIGHEST PRICEDPRODUCTS 3%,%#4/2$%2?.5- /2$%2?$!4% &2/-/2$%23 7(%2%-&2).3%,%#4-&2?)$ &2/-02/$5#43 7(%2%02)#%3%,%#4-!802)#% &2/-02/$5#43 !.$02/$5#4).3%,%#402/$5#4?)$ &2/-02/$5#43 7(%2%02)#%3%,%#4-!802)#% &2/-02/$5#43
)NSTEADOFASINGLEROW VALUEDCOMPARISONINTHE7(%2%CLAUSE THERESULTINGQUERYHAS TWOSEPARATESCALAR VALUEDCOMPARISONS ONEFORTHEMANUFACTURER)$ANDONEFORTHE PRODUCT)$"ECAUSETHECOMPARISONMUSTBESPLIT THELOWER LEVELSUBQUERYTOFINDTHE
#HAPTERçç
3UBQUERIESçANDç1UERYç%XPRESSIONSç
MAXIMUMPRICEMUSTBEREPEATEDTWICEASWELL/VERALL THEFORMOFTHEQUERYUSINGTHE ROW VALUEDEXPRESSIONISAMOREDIRECTTRANSLATIONOFTHE%NGLISH LANGUAGEREQUEST ANDITS EASIERTOREADANDUNDERSTAND
2OW 6ALUEDõ#OMPARISONS
g!#)g gg g2%)g g!2g BASEDONlRSTCOLUMN g!#)g gg g!#)g gg BASEDONSECONDCOLUMN g!#)g gg g!#)g gg BASEDONTHIRDCOLUMN
4ABLE 6ALUEDõ%XPRESSIONS )NADDITIONTOITSEXTENDEDCAPABILITIESFOREXPRESSIONSINVOLVINGSIMPLESCALARDATAVALUES ANDROWVALUES THE31,STANDARDDRAMATICALLYEXTENDSTHE31,CAPABILITIESFORTABLE PROCESSING)TPROVIDESAMECHANISMFORCONSTRUCTINGATABLEOFDATAVALUESINPLACEWITHIN A31,STATEMENT)TALLOWSTABLE VALUEDSUBQUERIESANDEXTENDSTHE31,SUBQUERYTESTSTO HANDLETHEM)TALSOALLOWSSUBQUERIESTOAPPEARINMANYMOREPLACESWITHINA31, STATEMENTFOREXAMPLE ASUBQUERYCANAPPEARINTHE&2/-CLAUSEOFA3%,%#4STATEMENT ASONEORMOREOFITSSOURCETABLES&INALLY ITPROVIDESEXPANDEDCAPABILITIESFORCOMBINING TABLES INCLUDINGTHE5.)/. ).4%23%#4)/. AND$)&&%2%.#%OPERATIONS
4HEõ4ABLE 6ALUEõ#ONSTRUCTOR 31,ALLOWSYOUTOSPECIFYATABLEOFDATAVALUESWITHINA31,STATEMENTBYUSINGATABLE VALUECONSTRUCTOREXPRESSION WHOSESYNTAXISSHOWNIN&IGURE )NITSSIMPLESTFORM THE TABLE VALUECONSTRUCTORISACOMMA SEPARATEDLISTOFROW VALUECONSTRUCTORS EACHOFWHICH CONTAINSACOMMA SEPARATEDSETOFLITERALSTHATFORMINDIVIDUALCOLUMNVALUES&OREXAMPLE THE31,).3%24STATEMENTUSESATABLE VALUECONSTRUCTORASTHESOURCEOFTHEDATATOBE INSERTEDINTOADATABASE7HILETHE31,).3%24STATEMENTDESCRIBEDIN#HAPTER ALLOWSYOUTOINSERTONLYASINGLEROWOFDATA THE31,ANDBEYOND STANDARD).3%24
1, Ê£xÊ Ê />LiÛ>ÕiÊ VÃÌÀÕVÌÀÊÃÞÌ>ÝÊ `>}À>
0!24ç))
4HEMOSTCOMMONUSEOFROW VALUEDEXPRESSIONSINTHE7(%2%OR(!6).'CLAUSEISWITHINA TESTFOREQUALITY ASILLUSTRATEDBYTHELASTFEWEXAMPLES!CONSTRUCTEDROWOFTENCONSISTING OFCOLUMNVALUESFROMACANDIDATEROWOFQUERYRESULTS ISCOMPAREDWITHANOTHER CONSTRUCTEDROWPERHAPSAROWOFSUBQUERYRESULTSORAROWOFLITERALVALUES ANDIFTHE ROWSAREEQUAL THECANDIDATEROWISINCLUDEDINTHEQUERYRESULTS4HE31,STANDARDALSO PROVIDESFORROW VALUEDFORMSOFTHEINEQUALITYCOMPARISONTESTSANDTHERANGETEST7HEN COMPARINGTWOROWSFORINEQUALITY 31,USESTHESAMERULESTHATITWOULDUSEIFTHECOLUMNS WEREBEINGUSEDTOSORTTHEROWS)TCOMPARESTHECONTENTSOFTHEFIRSTCOLUMNINTHETWO ROWS ANDIFTHEYAREUNEQUAL USESTHEMTOORDERTHEROWS)FTHEYAREEQUAL THECOMPARISON MOVESTOTHESECONDCOLUMN ANDTHENTHETHIRD ANDSOON(EREARETHERESULTING COMPARISONSFORSOMETHREE COLUMNCONSTRUCTEDROWSDERIVEDFROMTHE/2$%23TABLE
ç
0ARTç))ç
2ETRIEVINGç$ATA
STATEMENTINSERTSTHREEROWSINTOTHE/&&)#%3TABLE(OWEVER NOTALL31,IMPLEMENTATIONS SUPPORTTHISSYNTAX !DDTHREEOFlCESTOTHE/&&)#%3TABLE ).3%24).4//&&)#%3/&&)#% #)49 2%')/. -'2 3!,%3 6!,5%3 g3AN$IEGOg g7ESTERNg g3EATTLEg g7ESTERNg g"OSTONg g%ASTERNg .5,,
.OTETHATTHEINDIVIDUALROWSINTHETABLE VALUECONSTRUCTORARENOTRESTRICTEDTOCONTAIN ONLYLITERALVALUES4HESOURCEOFADATAVALUECANBEASCALAR VALUEDSUBQUERY ORANENTIRE ROWCANBETHERESULTOFAROW VALUEDSUBQUERY!LTHOUGHITDOESNTMAKEMUCHSENSEINTHE SAMPLEDATABASE ANDTHESYNTAXISNTSUPPORTEDBYANYOFTHELEADING$"-3BRANDS THISIS ALEGAL31,STANDARD).3%24STATEMENTTHATILLUSTRATESTHESECAPABILITIES !DDTHREEOFlCESTOTHE/&&)#%3TABLE ).3%24).4//&&)#%3/&&)#% #)49 2%')/. -'2 3!,%3 6!,5%3 g3AN$IEGOg g7ESTERNg g3EATTLEg g7ESTERNg 3%,%#4-!.!'%2 &2/-3!,%32%03 7(%2%%-0,?.5- 3%,%#4 g"/34/.g 2%')/. -'2 &2/-/&&)#%3 7(%2%/&&)#%
!SINTHEPRECEDINGEXAMPLE THE6!,5%3CLAUSEINTHIS).3%24STATEMENTGENERATESA THREE ROWTABLETOBEINSERTED4HEFIRSTROWISSPECIFIEDWITHLITERALVALUES)NTHESECOND ROW THEFOURTHCOLUMNISSPECIFIEDASASCALAR VALUEDSUBQUERYTHATRETRIEVESTHEMANAGER OFEMPLOYEENUMBER)NTHETHIRDROW THEENTIREROWISGENERATEDBYAROW VALUED SUBQUERY)NTHISCASE THREEOFTHECOLUMNVALUESINTHESUBQUERYS3%,%#4CLAUSEARE ACTUALLYLITERALVALUES BUTTHETHIRDANDFOURTHCOLUMNSAREPRODUCEDBYTHESUBQUERY WHICHRETRIEVESTHEMANAGERANDREGIONFORTHE.EW9ORKOFFICENUMBER
4ABLE 6ALUEDõ3UBQUERIES *USTASNEWERVERSIONSOFTHE31,STANDARDEXPANDTHEUSEOFSCALARSUBQUERIESINTOROW VALUEDSUBQUERIES THEYALSOEXTENDTHE31,SUBQUERYFACILITYTOSUPPORTTABLE VALUED SUBQUERIESTHATIS SUBQUERIESTHATRETURNAFULLTABLEOFRESULTS.OTETHAT31,3ERVERDOES NOTSUPPORTTHISSYNTAX BUT/RACLE -Y31, AND$"5$"DO /NEUSEFULROLEFORTABLE VALUEDSUBQUERIESISWITHINTHE7(%2%OR(!6).'CLAUSE WHERETHETABLE VALUEDSUBQUERY ISCOMBINEDWITHEXTENDEDFORMSOFTHESUBQUERYTESTS&OREXAMPLE SUPPOSEYOUWANTED TOLISTTHEDESCRIPTIONSANDPRICESOFALLPRODUCTSWITHORDERSEXCEEDING INTHE SAMPLEDATABASE0ERHAPSTHEMOSTSTRAIGHTFORWARDWAYTOEXPRESSTHISREQUESTISINTHIS 31,STATEMENTTHATUSESATABLE VALUEDSUBQUERY ,ISTTHEDESCRIPTIONANDPRICEOFALLPRODUCTSWITHINDIVIDUALORDERSOVER 3%,%#4$%3#2)04)/. 02)#% &2/-02/$5#43 7(%2%-&2?)$ 02/$5#4?)$ ).3%,%#4-&2 02/$5#4 &2/-/2$%23 7(%2%!-/5.4
#HAPTERçç
3UBQUERIESçANDç1UERYç%XPRESSIONSç
4HETOP LEVELQUERYISASTRAIGHTFORWARDSTATEMENTOFTHE%NGLISH LANGUAGEREQUESTIT ASKSFORTHEDESCRIPTIONANDPRICEOFTHOSEPRODUCTSWHOSEIDENTIFICATIONASINPREVIOUS EXAMPLES AMANUFACTURER )$PRODUCT )$PAIR MATCHESSOMESETOFPRODUCTS4HISIS EXPRESSEDASASUBQUERYSETMEMBERSHIPTESTINTHE7(%2%CLAUSE4HESUBQUERYGENERATESA TWO COLUMNTABLEOFSUBQUERYRESULTS WHICHARETHEIDENTIFICATIONSOFTHEPRODUCTSTHAT MEETTHESTATEDORDERSIZECRITERION )TSCERTAINLYPOSSIBLETOEXPRESSTHISQUERYINOTHERWAYS&ROMTHEDISCUSSIONIN #HAPTER YOUPROBABLYRECOGNIZETHATITCANBESTATEDASAJOINOFTHE02/$5#43AND /2$%23TABLESWITHACOMPOUNDSEARCHCONDITION
3%,%#4$)34).#4$%3#2)04)/. 02)#% &2/-02/$5#43 /2$%23 7(%2%-&2?)$-&2 !.$02/$5#4?)$02/$5#4 !.$!-/5.4
.OTETHATWEHADTOADDTHE$)34).#4KEYWORDBECAUSETHEREARETWOORDERSOVER FORTHEh2IGHT(INGEvPRODUCT4HISISANEQUALLYVALIDSTATEMENTOFTHEQUERY BUT ITSALOTFURTHERREMOVEDFROMTHE%NGLISH LANGUAGEREQUEST ANDTHEREFOREMOREDIFFICULTTO UNDERSTANDFORMOSTPEOPLE!SQUERIESBECOMEMORECOMPLEX THEABILITYTOUSETABLE VALUEDSUBQUERIESBECOMESEVENMOREUSEFULTOSIMPLIFYANDCLARIFY31,REQUESTS
4HEõ31,õ1UERYõ3PECIFICATION 4HE31,STANDARDFORMALIZESTHEDEFINITIONOFWHATWEHAVELOOSELYBEENCALLINGA3%,%#4 STATEMENTORAQUERYINTHELASTTHREECHAPTERSINTOABASICBUILDINGBLOCKCALLEDAQUERY SPECIFICATION&ORACOMPLETEUNDERSTANDINGOFTHE31,TABLEEXPRESSIONCAPABILITIESINTHE NEXTSECTION ITSUSEFULTOUNDERSTANDTHISFORMALDEFINITION4HEFORMOFA31,QUERY SPECIFICATIONISSHOWNIN&IGURE )TSCOMPONENTSSHOULDBEFAMILIARFROMTHEEARLIER CHAPTERS s !SELECTLISTSPECIFIESTHECOLUMNSOFQUERYRESULTS%ACHCOLUMNISSPECIFIEDBYAN EXPRESSIONTHATTELLSTHE$"-3HOWTODETERMINEITSVALUE4HECOLUMNCANBE ASSIGNEDANOPTIONALALIASWITHTHE!3CLAUSE s 4HEKEYWORDS!,,OR$)34).#4CONTROLDUPLICATE ROWELIMINATIONINTHEQUERY RESULTS s 4HE&2/-CLAUSESPECIFIESTHETABLESTHATCONTRIBUTETOTHEQUERYRESULTS s 4HE7(%2%CLAUSEDESCRIBESHOWTHE$"-3SHOULDDETERMINEWHICHROWSARE INCLUDEDINTHEQUERYRESULTSANDWHICHSHOULDBEDISCARDED s 4HE'2/50"9AND(!6).'CLAUSESTOGETHERCONTROLTHEGROUPINGOFINDIVIDUAL QUERYRESULTSROWSINAGROUPEDQUERY ANDTHESELECTIONOFROWGROUPSFORINCLUSION OREXCLUSIONINTHEFINALRESULTS s 4HE/2$%2"9CLAUSESPECIFIESTHEDESIREDSEQUENCEOFTHEROWSINTHEQUERYRESULTS
0!24ç))
,ISTTHEDESCRIPTIONANDPRICEOFALLPRODUCTSWITHINDIVIDUALORDERSOVER
ç
0ARTç))ç
2ETRIEVINGç$ATA
1, Ê£ÈÊ -+ʵÕiÀÞÊëiVwV>Ì\ÊvÀ>Ê`iwÌ
4HEQUERYSPECIFICATIONISTHEBASICQUERYBUILDINGBLOCKINTHE31,STANDARD #ONCEPTUALLY ITDESCRIBESTHEPROCESSOFCOMBININGDATAFROMTHETABLESINTHE&2/-CLAUSE INTOAROWCOLUMNTABLEOFQUERYRESULTS4HEVALUEOFTHEQUERYSPECIFICATIONISATABLEOF DATA)NTHESIMPLESTCASE A31,QUERYCONSISTSOFASIMPLEQUERYSPECIFICATION)NASLIGHTLY MORECOMPLEXCASE AQUERYSPECIFICATIONISUSEDTODESCRIBEASUBQUERY WHICHAPPEARS WITHINANOTHERHIGHER LEVEL QUERYSPECIFICATION&INALLY QUERYSPECIFICATIONSCANBE COMBINEDUSINGTABLE VALUEDOPERATIONSTOFORMGENERAL PURPOSEQUERYEXPRESSIONS AS DESCRIBEDINTHENEXTSECTION
1UERYõ%XPRESSIONS 4HE31,STANDARDDEFINESAQUERYEXPRESSIONASTHEFULL GENERAL PURPOSEWAYTHATYOUCAN SPECIFYATABLEOFQUERYRESULTSIN31,4HEBASICBUILDINGBLOCKSYOUCANUSETOCREATEA QUERYEXPRESSIONARETHEFOLLOWING s !QUERYSPECIFICATION ASDESCRIBEDINTHEPRECEDINGSECTION3%,%#4x&2/-x )TS VALUEISATABLEOFQUERYRESULTS s !TABLE VALUECONSTRUCTOR ASPREVIOUSLYDESCRIBED6!,5%3x )TSVALUEISATABLE OFCONSTRUCTEDVALUES s !NEXPLICITTABLEREFERENCE4!",%TBLNAME )TSVALUEISTHECONTENTSOFTHENAMED TABLE
#HAPTERçç
3UBQUERIESçANDç1UERYç%XPRESSIONSç
5SINGTHESEBUILDINGBLOCKS 31,LETSYOUCOMBINETHEIRTABLEVALUESUSINGTHE FOLLOWINGOPERATIONS s */). 31,PROVIDESEXPLICITSUPPORTFORFULLCROSS PRODUCTJOINSCROSSJOINS NATURALJOINS INNERJOINS ANDALLTYPESOFOUTERJOINSLEFT RIGHT ANDFULL AS DESCRIBEDIN#HAPTER!*/).OPERATIONTAKESTWOTABLESASITSINPUTANDPRODUCES ATABLEOFCOMBINEDQUERYRESULTSACCORDINGTOTHEJOINSPECIFICATION
s %8#%04 4HE31,%8#%04OPERATIONTAKESTWOTABLESASITSINPUTANDPRODUCESAS ITSOUTPUTATABLECONTAININGTHEROWSTHATAPPEARINTHEFIRSTTABLEBUTTHATDONOT APPEARINANOTHERTABLETHATIS THEROWSTHATAREMISSINGFROMTHESECONDTABLE #ONCEPTUALLY THE%8#%04OPERATIONISLIKETABLESUBTRACTION4HEROWSOFTHESECOND TABLEARETAKENAWAYFROMTHEROWSOFTHEFIRSTTABLE ANDTHEANSWERISTHE REMAININGROWSOFTHEFIRSTTABLE s ).4%23%#4 4HE31,).4%23%#4OPERATIONTAKESTWOTABLESASITSINPUTAND PRODUCESASITSOUTPUTATABLECONTAININGTHEROWSTHATAPPEARINBOTHINPUTTABLES
5.)/. õ).4%23%#4 õANDõ%8#%04õ/PERATIONS 4HE5.)/. ).4%23%#4 AND%8#%04OPERATIONSPROVIDESETOPERATIONSFORCOMBININGTWO INPUTTABLESTOFORMANOUTPUTTABLE.EARLYALLVENDORSSUPPORT5.)/. BUTSUPPORTFOR ).4%23%#4AND%8#%04ISINCONSISTENTACROSSVENDORS&OREXAMPLE /RACLEUSESTHE KEYWORD-).53INSTEADOF%8#%04!LLTHREEOFTHEOPERATIONSREQUIRETHATTHETWOINPUT TABLESBEUNION COMPATIBLETHEYMUSTHAVETHESAMENUMBEROFCOLUMNS ANDTHE CORRESPONDINGCOLUMNSOFEACHTABLEMUSTHAVEIDENTICALDATATYPES(EREARESOMESIMPLE EXAMPLESOF31,QUERYEXPRESSIONSINVOLVING5.)/. ).4%23%#4 AND%8#%04OPERATIONS BASEDONTHESAMPLEDATABASE 3HOWALLPRODUCTSFORWHICHTHEREISANORDEROVER ORMORETHAN WORTHOFINVENTORY ONHAND 3%,%#4-&2 02/$5#4 &2/-/2$%23 7(%2%!-/5.4 5.)/. 3%,%#4-&2?)$ 02/$5#4?)$ &2/-02/$5#43 7(%2%02)#% 149?/.?(!.$
3HOWALLPRODUCTSFORWHICHTHEREISANORDEROVER ANDMORETHAN WORTHOF INVENTORYONHAND 3%,%#4-&2 02/$5#4 &2/-/2$%23 7(%2%!-/5.4 ).4%23%#4 3%,%#4-&2?)$ 02/$5#4?)$ &2/-02/$5#43 7(%2%02)#% 149?/.?(!.$
0!24ç))
s 5.)/. 4HE31,5.)/.OPERATIONPROVIDESEXPLICITSUPPORTFORMERGINGTHEROWS OFTWOCOMPATIBLETABLESTHATIS TWOTABLESHAVINGTHESAMENUMBEROFCOLUMNS ANDWITHCORRESPONDINGCOLUMNSHAVINGTHESAMEDATATYPES 4HE5.)/.OPERATION TAKESTWOTABLESASITSINPUTANDPRODUCESASINGLEMERGEDTABLEOFQUERYRESULTS
ç
0ARTç))ç
2ETRIEVINGç$ATA
3HOWALLPRODUCTSFORWHICHTHEREISANORDEROVER EXCEPTFORTHOSEPRODUCTSTHATSELLFOR UNDER 3%,%#4-&2 02/$5#4 &2/-/2$%23 7(%2%!-/5.4 %8#%04 3%,%#4-&2?)$ 02/$5#4?)$ &2/-02/$5#43 7(%2%02)#%
"YDEFAULT THE5.)/. ).4%23%#4 AND%8#%04OPERATIONSELIMINATEDUPLICATEROWS DURINGTHEIRPROCESSING4HISISUSUALLYTHEDESIREDRESULT ASITISINTHESEEXAMPLES BUT OCCASIONALLYYOUMAYNEEDTOSUPPRESSTHEELIMINATIONOFDUPLICATEROWS9OUCANDOTHIS BYSPECIFYINGTHE5.)/.!,, ).4%23%#4!,, OR%8#%04!,,FORMSOFTHEOPERATIONS .OTEEACHOFTHESEEXAMPLESPRODUCESATWO COLUMNTABLEOFQUERYRESULTS4HE RESULTSCOMEFROMTWODIFFERENTSOURCETABLESWITHINTHEDATABASETHE/2$%23TABLEAND THE02/$5#43TABLE(OWEVER THECOLUMNSSELECTEDFROMTHESETABLESHAVETHESAME CORRESPONDINGDATATYPES SOTHEYCANBECOMBINEDUSINGTHESEOPERATIONS)NTHE SAMPLEDATABASE THECORRESPONDINGCOLUMNSHAVEDIFFERENTNAMESINTHETWOTABLES 4HEMANUFACTURER )$COLUMNISNAMED-&2INTHE/2$%23TABLEBUTNAMED-&2?)$IN THE02/$5#43TABLE
1UERYõ%XPRESSIONSõINõTHEõ&2/-õ#LAUSE 31,QUERYEXPRESSIONSPROVIDEAMUCHMOREPOWERFULANDFLEXIBLEMETHODFORGENERATING ANDCOMBININGTABLESOFQUERYRESULTSTHANTHESIMPLESUBQUERYAND5.)/.OPERATIONS PROVIDEDBYTHE31,STANDARD4OMAKEQUERYEXPRESSIONSEVENMOREUSEFULANDMORE GENERALPURPOSE THE31,STANDARDNOWALLOWSTHEMTOAPPEARALMOSTANYWHERETHATATABLE REFERENCECOULDAPPEARINA31,QUERY)NPARTICULAR AQUERYEXPRESSIONCANAPPEARIN PLACEOFATABLENAMEINTHE&2/-CLAUSE(EREISASIMPLEEXAMPLEOFAQUERYFORTHESAMPLE DATABASETHATUSESTHISFEATURE 3HOWTHENAMESANDTOTALOUTSTANDINGORDERSOFALLCUSTOMERSWITHCREDITLIMITSOVER 3%,%#4#/-0!.9 4/4?/2$%23 &2/-#534/-%23 3%,%#4#534 35-!-/5.4 !34/4?/2$%23 &2/-/2$%23 '2/50"9#534 ! 7(%2%#2%$)4?,)-)4 !.$#534?.5-#534
4HESECONDhTABLENAMEvINTHE&2/-CLAUSEOFTHEMAINQUERYISNOTATABLENAMEATALL BUTAFULL BLOWNQUERYEXPRESSION)NFACT THEEXPRESSIONCOULDHAVEBEENMUCHMORE COMPLEX INVOLVING5.)/.OR*/).OPERATIONS7HENAQUERYEXPRESSIONAPPEARSINTHE&2/- CLAUSE ASITDOESHERE THE$"-3CONCEPTUALLYCARRIESITOUTFIRST BEFOREANYOTHERPROCESSING OFTHEQUERY ANDCREATESATEMPORARYTABLEOFTHEQUERYRESULTSGENERATEDBYTHEQUERY EXPRESSION)NTHISCASE THISTEMPORARYTABLECONSISTSOFTWOCOLUMNS LISTINGEACHCUSTOMER NUMBERANDTHETOTALOFORDERSFORTHATCUSTOMERNUMBER4HISTEMPORARYTABLETHENACTSAS ONEOFTHESOURCETABLESFORTHEMAINQUERY)NTHISEXAMPLE ITSCONTENTSAREJOINEDTOTHE #534/-%2TABLETOOBTAINTHECOMPANYNAMEANDGENERATETHEANSWERTOTHEMAINQUESTION
#HAPTERçç
3UBQUERIESçANDç1UERYç%XPRESSIONSç
31,õ1UERIESõ!õ&INALõ3UMMARY 4HISCONCLUDESTHEDISCUSSIONOFTHE31,QUERIESANDTHE3%,%#4STATEMENTTHATBEGANIN #HAPTER!SDESCRIBEDIN#HAPTERSTHROUGH THECLAUSESOFTHE3%,%#4STATEMENT PROVIDEAPOWERFUL FLEXIBLESETOFCAPABILITIESFORRETRIEVINGDATAFROMTHEDATABASE%ACH CLAUSEPLAYSASPECIFICROLEINDATARETRIEVAL s 4HE&2/-CLAUSESPECIFIESTHESOURCETABLESTHATCONTRIBUTEDATATOTHEQUERYRESULTS %VERYCOLUMNNAMEINTHEBODYOFTHE3%,%#4STATEMENTMUSTUNAMBIGUOUSLY IDENTIFYACOLUMNFROMONEOFTHESETABLES ORITMUSTBEANOUTERREFERENCETOA COLUMNFROMASOURCETABLEOFANOUTERQUERY s 4HE7(%2%CLAUSE IFPRESENT SELECTSINDIVIDUALCOMBINATIONSOFROWSFROMTHE SOURCETABLESTOPARTICIPATEINTHEQUERYRESULTS3UBQUERIESINTHE7(%2%CLAUSEARE EVALUATEDFOREACHINDIVIDUALROW s 4HE'2/50"9CLAUSE IFPRESENT GROUPSTHEINDIVIDUALROWSSELECTEDBYTHE7(%2% CLAUSEINTOROWGROUPS s 4HE(!6).'CLAUSE IFPRESENT SELECTSROWGROUPSTOPARTICIPATEINTHEQUERYRESULTS 3UBQUERIESINTHE(!6).'CLAUSEAREEVALUATEDFOREACHROWGROUP s 4HE3%,%#4CLAUSEDETERMINESWHICHDATAVALUESACTUALLYAPPEARASCOLUMNSINTHE FINALQUERYRESULTS s 4HE$)34).#4KEYWORD IFPRESENT ELIMINATESDUPLICATEROWSOFQUERYRESULTS s 4HE5.)/.OPERATOR IFPRESENT MERGESTHEQUERYRESULTSPRODUCEDBYINDIVIDUAL 3%,%#4STATEMENTSINTOASINGLESETOFQUERYRESULTS s 4HE/2$%2"9CLAUSE IFPRESENT SORTSTHEFINALQUERYRESULTSBASEDONONEORMORE COLUMNS s 4HE31,QUERYEXPRESSIONCAPABILITIESADDROW VALUEDANDTABLE VALUED EXPRESSIONSAND).4%23%#4AND%8#%04OPERATIONSTOTHE31,CAPABILITIES4HE FUNDAMENTALFLOWOFQUERYPROCESSINGISNOTCHANGED BUTTHECAPABILITYTOEXPRESS QUERIESWITHINQUERIESISGREATLYENHANCED
0!24ç))
4HEREAREMANYOTHERWAYSINWHICHTHISQUERYCOULDBEWRITTEN4HEENTIREQUERYCOULD BEWRITTENASONETOP LEVELGROUPEDQUERYTHATJOINSTHE#534/-%2AND/2$%23TABLE4HE JOINOPERATIONCOULDBEMADEEXPLICITWITHA*/).OPERATOR ANDTHENTHERESULTSOFTHEJOIN COULDBEGROUPEDINTHETOP LEVELQUERY!STHISEXAMPLESHOWS ONEOFTHEBENEFITSOFTHE 31,QUERYEXPRESSIONCAPABILITIESISTHATTHEYTYPICALLYPROVIDESEVERALDIFFERENTWAYSTO OBTAINTHESAMEQUERYRESULTS 4HEGENERALPHILOSOPHYBEHINDTHECAPABILITIESINTHISAREAISTHAT31,SHOULDPROVIDETHE FLEXIBILITYTOEXPRESSAQUERYINTHEMOSTNATURALFORM4HEUNDERLYING$"-3MUSTBEABLETO TAKETHEQUERY HOWEVEREXPRESSED BREAKITDOWNINTOITSFUNDAMENTALS ANDTHENDETERMINE THEMOSTEFFICIENTWAYTOCARRYOUTTHEQUERY4HISINTERNALQUERYEXECUTIONPLANMAYBEQUITE DIFFERENTFROMTHEAPPARENTPLANCALLEDFORBYTHEACTUAL31,STATEMENT BUTASLONGASIT PRODUCESTHESAMEQUERYRESULTS THENETEFFECTISTOSHIFTTHEOPTIMIZATIONWORKLOADFROMTHE HUMANUSERORPROGRAMMERTOTHE$"-3
This page intentionally left blank
***
0!24
5PDATINGç$ATA
3
1,ISNOTONLYAQUERYLANGUAGE BUTITSALSOACOMPLETE LANGUAGEFORRETRIEVINGANDMODIFYINGDATAINADATABASE #HAPTERSnFOCUSONDATABASEUPDATES#HAPTER DESCRIBES31,STATEMENTSTHATADDDATATOADATABASE REMOVEDATA FROMADATABASE ANDMODIFYEXISTINGDATABASEDATA#HAPTER DESCRIBESHOW31,MAINTAINSTHEINTEGRITYOFSTOREDDATAWHENTHE DATAISMODIFIED#HAPTERDESCRIBESTHE31,TRANSACTION PROCESSING FEATURESTHATSUPPORTCONCURRENTDATABASEUPDATESBYMANYDIFFERENT USERS
#(!04%2ç $ATABASE5PDATES #(!04%2ç $ATA)NTEGRITY #(!04%2ç 4RANSACTION0ROCESSING
This page intentionally left blank
#(!04%2
$ATABASEç5PDATES
3
1,ISACOMPLETEDATAMANIPULATIONLANGUAGETHATISUSEDNOTONLYFORDATABASE QUERIES BUTALSOTOMODIFYANDUPDATEDATAINTHEDATABASE#OMPAREDWITHTHE COMPLEXITYOFTHE3%,%#4STATEMENT WHICHSUPPORTS31,QUERIES THE31,STATEMENTS THATMODIFYDATABASECONTENTSAREEXTREMELYSIMPLE(OWEVER DATABASEUPDATESPOSESOME CHALLENGESFORA$"-3BEYONDTHOSEPRESENTEDBYDATABASEQUERIES4HE$"-3MUST PROTECTTHEINTEGRITYOFSTOREDDATADURINGCHANGES ENSURINGTHATONLYVALIDDATAIS INTRODUCEDINTOTHEDATABASE ANDTHATTHEDATABASEREMAINSSELF CONSISTENT EVENINTHE EVENTOFSYSTEMFAILURES4HE$"-3MUSTALSOCOORDINATESIMULTANEOUSUPDATESBYMULTIPLE USERS ENSURINGTHATTHEUSERSANDTHEIRCHANGESDONOTINTERFEREWITHONEANOTHER 4HISCHAPTERDESCRIBESTHETHREE31,STATEMENTSTHATAREUSEDTOMODIFYTHECONTENTSOF ADATABASE s ).3%24 !DDSNEWROWSOFDATATOATABLE s $%,%4% 2EMOVESROWSOFDATAFROMATABLE s 50$!4% -ODIFIESEXISTINGDATAINTHEDATABASE )N#HAPTER 31,FACILITIESFORMAINTAININGDATAINTEGRITYAREDESCRIBED#HAPTER COVERS31,SUPPORTFORMULTIUSERCONCURRENCY
!DDINGõ$ATAõTOõTHEõ$ATABASE !NEWROWOFDATAISTYPICALLYADDEDTOARELATIONALDATABASEWHENANEWENTITYREPRESENTED BYTHEROWAPPEARSINTHEOUTSIDEWORLD&OREXAMPLE INTHESAMPLEDATABASE s 7HENYOUHIREANEWSALESPERSON ANEWROWMUSTBEADDEDTOTHE3!,%32%03 TABLETOSTORETHESALESPERSONSDATA s 7HENASALESPERSONSIGNSANEWCUSTOMER ANEWROWMUSTBEADDEDTOTHE #534/-%23TABLE REPRESENTINGTHENEWCUSTOMER s 7HENACUSTOMERPLACESANORDER ANEWROWMUSTBEADDEDTOTHE/2$%23TABLETO CONTAINTHEORDERDATA
ç
0ARTç)))ç
5PDATINGç$ATA
)NEACHCASE THENEWROWISADDEDTOMAINTAINTHEDATABASEASANACCURATEMODELOFTHE REALWORLD4HESMALLESTUNITOFDATATHATCANBEADDEDTOARELATIONALDATABASEISASINGLEROW )NGENERAL A31, BASED$"-3PROVIDESTHREEWAYSTOADDNEWROWSOFDATATOADATABASE s 3INGLE ROW).3%24 !SINGLE ROW).3%24STATEMENTADDSASINGLENEWROWOFDATATO ATABLE)TISCOMMONLYUSEDINDAILYAPPLICATIONSFOREXAMPLE DATAENTRYPROGRAMS s -ULTIROW).3%24 !MULTIROW).3%24STATEMENTEXTRACTSROWSOFDATAFROM ANOTHERPARTOFTHEDATABASEANDADDSTHEMTOATABLE)TISCOMMONLYUSED FOR EXAMPLE INEND OF MONTHPROCESSINGWHENOLDROWSOFATABLEAREMOVEDTOAN INACTIVETABLE ORWHENMONTHLYRESULTSARESUMMARIZEDINTOATABLETHATHASBEEN SETUPTOHOLDTHEM s "ULKLOAD !BULKLOADUTILITYADDSDATATOATABLEFROMAFILETHATISOUTSIDEOFTHE DATABASE)TISCOMMONLYUSEDTOINITIALLYLOADTHEDATABASEORTOINCORPORATEDATA DOWNLOADEDFROMANOTHERCOMPUTERSYSTEMORCOLLECTEDFROMMANYSITES
4HEõ3INGLE 2OWõ).3%24õ3TATEMENT 4HESINGLE ROW).3%24STATEMENT SHOWNIN&IGURE ADDSANEWROWTOATABLE4HE ).4/CLAUSESPECIFIESTHETABLETHATRECEIVESTHENEWROWTHETARGETTABLE ANDTHE6!,5%3 CLAUSESPECIFIESTHEDATAVALUESTHATTHENEWROWWILLCONTAIN4HECOLUMNLISTINDICATES WHICHDATAVALUEGOESINTOWHICHCOLUMNOFTHENEWROW 3UPPOSEYOUJUSTHIREDANEWSALESPERSON (ENRY*ACOBSEN WITHTHEFOLLOWING PERSONALDATA >i\
iÀÞÊ>VLÃi
}i\
ÎÈ
«ÞiiÊ ÕLiÀ\
£££
/Ìi\
->iÃÊ>>}iÀ
"vvVi\
Ì>Ì>ÊvvViÊÕLiÀʣή
ÀiÊ >Ìi\
ÕÞÊÓx]ÊÓään
+ÕÌ>\
ÌÊÞiÌÊ>ÃÃ}i`
9i>ÀÌ >ÌiÊ->iÃ\
fä°ää
1, Ê£ä£Ê -}iÀÜÊ).3%24ÊÃÌ>ÌiiÌÊÃÞÌ>ÝÊ`>}À>
#HAPTERçç
$ATABASEç5PDATESç
(EREISTHE).3%24STATEMENTTHATADDS-R*ACOBSENTOTHESAMPLEDATABASE !DD(ENRY*ACOBSENASANEWSALESPERSON ).3%24).4/3!,%32%03.!-% !'% %-0,?.5- 3!,%3 4)4,% ()2%?$!4% 2%0?/&&)#% 6!,5%3g(ENRY*ACOBSENg g3ALES-GRg g g ROWINSERTED
%#%;+;/5/6; %$& &!%%$"% ") '%%#'!&&& ('%*/69>+-7,:/6
'*%+4/:09 '*
/=$7=
/69> +-7,:76
%+4/: 09
'
'
%%$"%&+,4/ ") '
244 .+5:
+9> 76/:
%