Coding Horror - A Visual Explanation of SQL Joins PDF
Coding Horror - A Visual Explanation of SQL Joins PDF
Coding Horror - A Visual Explanation of SQL Joins PDF
1 de 19
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...
programmingandhumanfactors
byJeAtwood
AVisualExplana onofSQLJoins
October11,2007
IthoughtLigayaTurmelle'spostonSQLjoinswasagreatprimerfornovicedevelopers.SinceSQLjoinsappeartobesetbased,theuseof
Venndiagramstoexplainthemseems,atfirstblush,tobeanaturalfit.However,likethecommenterstoherpost,IfoundthattheVenn
diagramsdidn'tquitematchtheSQLjoinsyntaxrealityinmytes ng.
Ilovetheconcept,though,solet'sseeifwecanmakeitwork.Assumewehavethefollowingtwotables.TableAisonthele ,andTableB
isontheright.We'llpopulatethemwithfourrecordseach.
id
-1
2
3
4
name
---Pirate
Monkey
Ninja
Spaghetti
id
-1
2
3
4
name
---Rutabaga
Pirate
Darth Vader
Ninja
Let'sjointhesetablesbythenamefieldinafewdierentwaysandseeifwecangetaconceptualmatchtothoseni yVenndiagrams.
name
---Pirate
Ninja
id
-2
4
name
---Pirate
Ninja
Innerjoinproducesonlythesetofrecordsthatmatch
inbothTableAandTableB.
name
---Pirate
Monkey
Ninja
Spaghetti
null
null
id
-2
null
4
null
1
3
name
---Pirate
null
Ninja
null
Rutabaga
Darth Vader
FullouterjoinproducesthesetofallrecordsinTableA
andTableB,withmatchingrecordsfrombothsides
whereavailable.Ifthereisnomatch,themissingside
willcontainnull.
2 de 19
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...
name
---Pirate
Monkey
Ninja
Spaghetti
id
-2
null
4
null
name
---Pirate
null
Ninja
null
Le outerjoinproducesacompletesetofrecordsfrom
TableA,withthematchingrecords(whereavailable)in
TableB.Ifthereisnomatch,therightsidewillcontain
null.
name
---Monkey
Spaghetti
id
-null
null
name
---null
null
ToproducethesetofrecordsonlyinTableA,butnotin
TableB,weperformthesamele outerjoin,then
excludetherecordswedon'twantfromtherightside
viaawhereclause.
name
---Monkey
Spaghetti
null
null
id
-null
null
1
3
name
---null
null
Rutabaga
Darth Vader
ToproducethesetofrecordsuniquetoTableAand
TableB,weperformthesamefullouterjoin,then
excludetherecordswedon'twantfrombothsidesvia
awhereclause.
There'salsoacartesianproductorcrossjoin,whichasfarasIcantell,can'tbeexpressedasaVenndiagram:
SELECT * FROM TableA
CROSS JOIN TableB
Thisjoins"everythingtoeverything",resul ngin4x4=16rows,farmorethanwehadintheoriginalsets.Ifyoudothemath,youcansee
whythisisaverydangerousjointorunagainstlargetables.
3 de 19
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...
PostedbyJeAtwood
Relatedposts:
AllAbstrac onsAreFailedAbstrac ons
Deadlocked!
GivemeparameterizedSQL,orgivemedeath
CompiledorBust?
StoredProceduresvs.AdHocSQL
4 de 19
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...
190Comments
Funny,Ijustexplainedthistoacoworkerinthesamemannerearlierintheweek.Iguessitneverdawnedonmethatothersmayhave
neverthoughtaboutjoinsintermsofthesediagrams.Goodpost,Je!
ShawnWheatleyonOctober12,20072:14AM
HeyJe,thanksforthegreatblogIthoroughlyenjoyreadingeverysingleoneofyourposts.
EventhoughIo enamfamiliarwiththeconceptsyoutalkof,Ifindthesimplemannerinwhichyoubreakdowntheissuesisalwaysa
greatrefresher.
Keepupthegreatwork.
capdogonOctober12,20072:32AM
ThepostismuchsimplerthantheWikipediaentrybecauseitomitsallthenontrivialcases.Alloftheseexamplesassumethateach
entryintableAwillbematchedbythejoinpredicatetoatmostoneentryintableB,andviceversa.
WeebleonOctober12,20073:35AM
SpeakingaboutOracle(+)syntaxandLEFT/RIGHT[OUTER]JOINsyntaxthereisadierence.Anditisnicelydescribedhere
h p://www.oreillynet.com/pub/a/network/2002/10/01/whatsinacondi on.html
SpeakingaboutANSIsyntaxwhereeveryonehastoexplicitlysaytomakeCROSSJOINtogetCartesianproductatleastinOracleitisnot
true,usingstupid(atleasttomymind)NATURALJOINclauseonecaneasilygetCROSSJOINandalsoJOINonsuchcolumnshenever
thoughtitreallyis.I'vebloggedaboutithere
h p://gplivna.blogspot.com/2007/10/naturaljoinsareevilmo oifyou.html
Don'tknowwehetheritisjustOraclespecificorasperANSISQLstandard.
SpeakingaboutINNNERJOINSasaCartesianproductandthenelimina ngallunnecessaryrows,atleasttherealmechanicsinOracleis
absolutelydierent,therearefollowingpossibili esfordoingthem:
NESTEDLOOPS(OUTER)
HASHJOIN(OUTER)
MERGEJOIN(OUTER)
andforCartesianproductitusesMERGEJOINCARTESIAN,andthat'swhenusuallytherealtrouble(fillingtemp)starts;)
TherealchoiceamongNestedloops,hashjoinormergejoinatleastdependsondata,sta s cs,availablememoryforasession,
explicitlygivenavailablememoryforhashjoinsormergejoins(btwthereispossibilitytogiveforonebutnotforother),system
workload,hints,ini aliza onparametersallowingceratainjointypes(atleastforhashjoins)andprobablysomethingother:)
5 de 19
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...
GintsPlivnaonOctober12,20073:51AM
HiJe,
Ithinkyourillustra onsmakeoneBIGassump on:TableAandTableBcontainuniquerows.Ifeithertablecontainedduplicate
matchingrecords,thenthewholeVenndiagramwillnothold(thecardinalityofthesetswillnotaddup).Iamafraidthisvisual
explana onwillleadsometothinkthatyoucanuseSQLjoinstodofilteropera onswhichshouldn'tbedonethisway.
Althoughit'snicea empttoexplainSQLjoins,overallIthinkitismisleading.
dt
dtonOctober12,20073:57AM
OneoftheworstthreemonthsofmyCStrainingwasaclassostensiblyondatabasetheorywhichwasreallyabootcampinSQLsyntax,
taughtbyaJohnnyonenoteprofessorwhothoughtSQLandRDMSswerethegreatestinven onofmankind.
Thisexperienceturnedmeodatabasesfor15yearsun lonedayintheshowerIrealizedthatjoinswereanalogoustosettheory,ina
roughway.(Yestheyare,allyounaysayers!"Givemeeverythingthat'sthereANDthere"or"Givemeeverythingthat'sthereORthere"
maynothandleallthepossibleinputs,butit'sagoodjumpingopointforexplaining"inner"and"outer."Andwhocameupwiththat
stupid,arbitraryterminologyanyway?)
Is llthinkSQLisanawfullanguage,though,andrela onaldatabasesareanuglyhackmandatedbyhardwarelimita onstrumping
elegantdesign.OLAP"cubes"aresoclearlyabe ersolu onsointui velyclearandobviousthenaturalgeneraliza ontohigher
dimensionsoftheflatfiledatabase.
AlexChamberlainonOctober12,20074:09AM
Tome,aCartesianProductwouldbebestillustratedbybothcirclesbeingblank.
Granted,alltheSQLguruswillprobablyspitfeathersatmyoutrageoussugges on,butforme,it'sabeau fullysimplemethodof
explainingsimplejoinsandI'llbeusingitinmetechnicaldocumenta on!
Thanksforthisar cle,Je.
KevinonOctober12,20074:12AM
HeyNowJe,
Thesediagramsmakemethinkofwhenlearningofclassicbooleanlogic.
CodingHorrorFan,
Ca o
Ca oonOctober12,20074:37AM
6 de 19
Well,thedatabaseprac
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...
onerrejoice,andthesetrela onistscringe.
Thereisonlyonejoin,whichisthecrossproduct(eachrowofthefirsttableconcatenatedtoeachrowofthesecondtable).TheINNER
JOINexampleonlydiscardssomerowsbythewhereclause,otherwiseitis(orshouldbe)thesameastheCROSSJOIN.Theouterjoinisa
hackthatisn'tveryfirmlyrootedinrela onalalgebra.
AndreasKreyonOctober12,20074:47AM
NiceJe,thankyousomuchforthispost!
IalwaysgotconfusedwithJOINSandhowtheywork,that'soneofthesethingsthatarehardtobeexpainedinabookoramanual.
Butthesediagramsmakeitpre yclear,theyaregreat!
jan.gonOctober12,20075:10AM
Verystrange.Inmy"DatabaseManagement"classatArizonaStateUniversityastudentaskedaboutJoin'sandmyprofessorsaid"I
neverusethem.Justs ckwiththeWHEREsyntax".
Thiswasamoretheore calcoursethough.WespentFARmore meinrela onalalgebra/calculusandalgorithmsforensuringatomic
transac onsthanwedidinmoreprac calstulikedatabasenormaliza on.
Hmm...lotsofpeoplesaythetheore calstuisawasteof me.Forme,well,IalmostbecameamathmajorinsteadofCS,soIfindthe
theore calstumoreinteres ng.
KGonOctober12,20075:21AM
Ifyoudon'tuseranyjoinfeatureandjustdo"select*fromTableA,TableB",youhaveyourcrossjoin.
7 de 19
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...
joskeonOctober12,20075:26AM
Venndiagrams.
wow,sosimple,soobvious;howcomeIhaven'tseenthisanywhereelse?
davidonOctober12,20075:42AM
HiJe
that'sannicediagramandanewwayofpresen ngthesqljoinfunc on.
RockonOctober12,20075:47AM
Yetanothercaseoftheblindleadingtheblind(downtheblindalleyofignoranceandarrogance);theoriginal,BTW.Atleastyoumade
anda empttofixitup.Butreadingallthose"nowIgetit"comments,makesitclearerwhyYahooslikeGWBushgetawaywithbald
facedlies."Peoplebelievewhattheywanttobelieve,whenitmakesnosenseatall"/Mellencamp.
Nowwe'llhaveanothergaggleoffolksrunningaroundfawningonAmblerandFowler.Gad.TheHorror,theHorror.
BuggyFunBunnyonOctober12,20076:22AM
ThankstothisI'mnowskippingmerrilydownthepathofBOMmanagementandstockcontrol,ratherthanflickingfuriouslythrough
Teachyourselfbooks,thanks
ChrisonOctober12,20076:36AM
Ilikeit
thanksforyourwork.
cocobearonOctober12,20076:42AM
Excellentpost.
Everyonewhohasfollowed(andpassed)acomputersciencebeginnercourseshouldbeabletounderstandthis.
RasmusonOctober12,20076:45AM
It'simportanttonotethatwhenjoiningtwotablesonnonindexedcolumnsmostdatabasesperformtheequivalentofacrossjoinand
thenweedouttherowsthatdon'tmatchthejoin/wherecriteria.Whilethisdoesntreallyimpactthequeryresults,ithasabigimpact
onqueryperformance.
InMySqlyoucanrun:explainmyquerytodetermineifthequeryisusingindexesandreviewperformanceofallyourqueries.
CRonOctober12,20076:59AM
8 de 19
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...
WombatonOctober12,20077:13AM
dtis100%right.Youreallyneedadisclaimerthatindicatesthatyoursetdiagramsonlyholdwhenthereisatbestaonetoone
correspondencebetweenjoincriteriavaluesinthetables.
Thesecondyouhavetwoorthreepiratesinoneofthetables(an_extremely_commonrealworldscenario,probablymuchmore
commonthanthesimplifiedcaseyoushowhere)yourVenndiagramsbreakdown.
Ma WigdahlonOctober12,20077:29AM
WhatagreatwaytoexplainJOINs,I'mcertaintherearethousandsofstudentsthatwouldbenefitfromthis...apictureistrulywortha
thousandwords(especiallyincaseslikethis).
ThomasBorzeckionOctober12,20077:38AM
IsitjustmeorOracle'ssyntaxismuchsimplerthanthat?Like:
select*fromTableA,TableB
whereTableA.Name=TableB.Name
I'mfamiliarwithboth,bothIalwayslikedthatonebe er.
RicardoonOctober12,20077:48AM
Je,
ThisisgreatforthoseSQLtypesthatdidn'ttakeasettheory,rela onalcalculusorevendiscretemathincollege.
I'dlovetoseeyouvisualizeacrossproduct:)
JayR.WrenonOctober12,20077:57AM
Ricardo,thatsyntaxispreANSI.Mostdatabasess llsupportitbuttheadvantagesoftheINNERJOIN,etc.syntaxare:itmakesthe
queriesmoreportableacrossdatabases;itallowssepara onofthejoincriteriafromthefiltercriteria,whichimprovesreadability;and
allowsfullouterjoinswithoutsyntac chacks.
AnotherhugebenefitisthatifyouwanttodoaCROSS(Cartesian)JOIN,andusuallyyoudon't,youhavetocallitoutspecifically.Inthe
oldsyntax,ifyouscreweduptheWHEREclauseyoucouldgetwildlyhugeresultsetsduetoinadvertentCartesianjoins.
Ma WigdahlonOctober12,20078:02AM
JoeBeam,
9 de 19
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...
TheonlyuseIhavefoundforRIGHTOUTERiswheni'mtoolazytoreordermyquery.;)Otherthenthatitmakesmoresensetouseonly
onetype.
IuseLEFTJOINtoo,asdomycompany.
IagreewithotherresponseshereJe,whileit'sareallynicesimplewaytorepresentjoins,itdoesn'thandlemanytomanyoroneto
manyverywellandlet'snottalkaboutmalformedjoins.
It'sagoodprimer,butshouldperhapscontainawarning.
EdKennyonOctober12,20078:08AM
Exceptthatvenndiagramsexplainsetlogic,andSQLJoinshaveveryli letodowithsetlogic.
Scaryhowmanypeopleareagreeingwiththis.
Wya onOctober12,20078:29AM
Actually,I'vealwaysbeenabitshakyonjoinsmyself.Ialwayshavetolookthemupany meIneedtousingajointhatisn'tastandard
filteredcrossproduct.Butseeingthisvisualguidehasreallyhelpedmetograspitmuchbe er.IjustwentbackandreadtheWikipedia
entryforjoinsanditmakescompletesensetomenow.Beforeseeingthisvisualrepresenta onImighthavejustglazedoverwhen
readingtheWikipediaar cle.
Soeveniftheyaren'texactlyrighthavingavisualrepresenta onhasreallyhelpedmetounderstandwhatisgoingon.
Thanks!
Ma onOctober12,20078:29AM
AnicetrickisyoucanwritearbitraryfiltersintheONclauseofthejoin.Iusethiswhenwri ngtrulyawfuljoinsorwhenIneedthele
joinwithanalreadyfilteredtable.
JoshuaonOctober12,20079:17AM
FromoneJetoanother,thisisabrilliantessayonasimpletopicsimplebutvexingtonewbies.IamaDB2DBA,andexplainingouter
joinstothenewbiedevelopersIencounterconstantlywillbemucheasierwithmaterialslikethis.Thanks,keepitcoming.
JereyBenneronOctober12,20079:25AM
Ihaveneverseensuchagoodillustra onofSQLjoins.Goodwork.
10 de 19
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...
JeonOctober12,20079:28AM
Imustagreethatwhilethediagramsareafairlygoodillustra onsofwhathappenswithajoin,they'renotVenndiagramsinthestrict
sensebecausethat'sjustnotwhat'shappening.WhatthefirstdiagramsaystomeisthatyougetallrecordsthatarebothinsetAandset
B(akaintersec on).That'sjustnottrue.Yougetasetofnewrecords,thatareneitherinsetAnorinsetB,buttheycontaina
combina onofthea ributesofbothsets.
AaronG:joinsareconceptuallyaspecialcaseofthecartesianproduct.Howthedatabaseserveractuallycomputesthemisanother
ma eren rely.
Conceptually,inrela onalalgebra,aninnerjoinisacrossproductfollowedbyaselec ononthejoincondi on.That'saterribly
inecientwaytocomputeit,butconceptually,that'swhatitis.
SvenGrootonOctober12,200710:09AM
ThemoronsrunningmydatabasefundamentalsclassatmyuniversitythoughtthatteachingtheCartesianproductasamethodof
joining,thenfilteringtheresults,wasavalidalterna vetotheinsanelysimpleinnerjoin.Somanypoorstudentsaregoingtohavea
hard meintheindustryasaresult.
LachlanMcDonOctober12,200710:21AM
JonRaynor:
Outofcuriosity,butwhatdatabasesotherthanOraclesupport+forjoins?
Anyway,Ipreferthe"TableAaINNERJOINTableBbONa.something=b.somethingelse"syntaxover"TableAa,TableBbWHERE
a.something=b.somethingelse"
(MostDBsalsosupport"USING(something)"insteadof"ONa.something=b.something"ifthecolumnshavethesamename)
ManyDBswillthrowanerrorifIaccidentlyomittheONstatementinsteadofgivingmeacrossjointhatIdidn'twant.Iimaginethatthe
queryparserwouldalsoparseitfaster,asIspecifyupfrontwhichtypeofjoinI'mdoing;thequeryparserdoesn'thavetofigureitout.
PowerlordonOctober12,200710:31AM
Je,
Ilikehowyoucanregurgitateanotherauthor'scontent,andgetawaywithit.
PhilihponOctober12,200710:45AM
Bigdeal,SQLfinallycaughtupwiththe1980's.UsedaveryfineDBMSandlanguage,NOMAD2,onmainframesthatdidthisstubut
onlymuchbe erandmorethoroughly.
SteveonOctober12,200710:58AM
nicelydone.ThoughIdohavetoadmittofindingithumorousthatwhatstartedoutasafast,dirtywaytotrytoclarifytosomeone(on
anIRCchannel)whytheywerege ngthewronginforma onforajoinnowhasotherscorrec ngandlinkingtome.
LigayaTurmelleonOctober12,200710:59AM
11 de 19
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...
Bindun!
h p://www.khankennels.com/blog/index.php/archives/2007/04/20/ge ngjoins/
Nicepostthough;)
BarryonOctober12,200711:04AM
"IwasundertheimpressionthatINNERJOINsuseahashmatchinternally(infact,I'mquitecertainofthis).CROSSJOINsobviouslydon't.
ThereforeIdon'tseehowit'sreasonabletosaythatanIJisjustaspecialcaseoftheCJ.Isupposeinbreadandbu ersettheory,where
there'snono onofahashoranindex,thiscouldwork,butthisistheworldofCS,wherethecleanacademicsolu onisalmostnever
themostprac calone.TheIJyouspeakofisthenaivestpossiblealgorithm,onlyusedwhentherearenoindexes(andifyou're
designingdatabaseswithoutanyindexes,well...stopdesigningdatabases)."AaronG
AnIJisdefinedasbeingtheequivalentofafilteredCJ.Thefactthatthiswouldnotbeareasonableimplementa ondoesnotmakea
dierence.
IJsareABSOLUTELYNOTimplementedexclusivelywithhashalgorithms.Sortmergealgorithmsandnestedloopalgorithmsareused
frequently.
RevMikeonOctober12,200711:10AM
Je:
Niceillustra on.Ithinkyourexamplewouldbeminutelymorereadableifthele handtablehadanIDcolumncontainingvalues
1,2,3,4(asitdoes)buttherighthandtablehadanIDcolumncontainingvaluesA,B,C,D(insteadofnumbers).Itjustmakesthat nybit
easiertotellwhat'swhatbyavoidingthetwosimilarlookingbutdierentcolumns.
MichaelChermsideonOctober12,200712:04PM
Verynicear cle.IuseaSqlitedatabase(viathecommandline)tomanagemydatabaseofcomicsandthiswouldhavebeenaverynice
thingtohavewhenIstartedout.Hopefully,thiswillhelppeopleingraspingSQLjoins.
JeFlowersonOctober12,200712:07PM
TheOracle(+),actuallypredatesOracle'susage,wasbecausewhenimplementedtherewasANSInoouterjoinsyntax.
InOracle8,theyaddedtheANSIsyntax.Nooneshouldbeusingtheoldsyntaxsohopfullyyouwillnotbeingseeingitoutinthewide.
willdieterichonOctober12,200712:17PM
12 de 19
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...
Veryhelpful,thanks!!!
SpeedmasteronOctober12,20071:04PM
Excellentvisualrepresenta on.Thisshouldhelpthenoviceseeaconcretepictureintheirmindofthedierentjoins.WhileLINQisn't
quitesetbased(butclose)thesesamevisualiza onswouldworktheretoo.
ShawnWildermuthonOctober13,20073:40AM
Excellentar cle.
Thanksalot.
canyouwritesomethingsimilarforindexes.
mpunaskaratgmaildotcom
MandaronOctober13,20075:30AM
Somethingyoumayormaynotknow....
Duringthelate70'sMathswasrepackagedtoinclude
VennDiagrams
Matrices
andsoon,
withtheideaofpreparingforthecomingofcomputers.
AtleastinEnglandthathappened...
Wowman,yourdesignisstellar.Contentisgreattoo...you'vegotanewreader.
WillHarrisonOctober13,20078:40AM
13 de 19
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...
HolycrapthisisWAYoverdue!I'vereadTONSofSQLbooksandNONEofthemhadthissimplediagram!
TerrySmithonOctober13,20079:33AM
IthinktheCartesianequa onorCrossProductinVennDiagramformwouldbebothcirclescombiningtoformasphere.
TokesonOctober13,20079:35AM
Thankyou!I'vebeenusingSQLforsolongandhavemanybooksonSQLandIhaveneverseensuchsimpleexamples.Iloveit!
MitchellHashimotoonOctober13,200710:36AM
ThereasonmanypeoplewhodoDBdevelopmenthavesuchainadequateunderstandingofthissimpletopicisbecausetheSQL
languageisaninadequatetooltotrytoabsorbitfrom.So,ifyouneverweretaughtthisinschooloronthejob,it'skindofasurprise.
SomeDBMS'hassyntaxwithmoredescrip veverbs(e.g.,'Merge','Subset','Reject'),andVenndiagramsaswellinthevendor
documenta on.
SQL2005isanimprovementover2000.Butthesadfactisismanypeoplelearnaboutrela onalalgebrabywri ngSQLstatements.
Alesspre yversionofmuchofwhatJeissayingcanbefoundhere:
h p://db.grussell.org/sec on010.html
SteveonOctober13,200711:21AM
WithallrespecttoJeAtwood,bewareifyou'vereadthispostandthink,"wow,that'seasywhydidnooneexplainitlikethatbefore?"
Well,there'sareasonwhysomanySQLtutorialsandbooksdon'tusethesediagramsthey'reaninadequateexplana onofwhat
databasejoinsareallabout.
Joinsareindeedanalogoustosetopera ons,butitisonlyananalogy.Understandwhat'sreallygoingon,oryouwillgetburnedwhen
youactuallyhavetousethethings.
Ma onOctober13,200711:48AM
Verynicefirstpostonthesubject.IthinkmanyofthecommentsarevalidandIthinkitwouldbegoodtocon nuethisasaseriesthat
buildsupthemorecomplexissuesofSQLjoins.
I,wholearnedthisstuthehardway,reallyapprecieatetheseprimers!
RobCromaronOctober13,20071:18PM
14 de 19
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...
IfonlysomeonehadexplainedSQLtomelikethiswhenIstarted...greatblog.
SteveonOctober13,20071:38PM
Greatstu,
thanks
VladonOctober14,20073:05AM
verycoolvisualisa on,pleasedomoreofthat
ravemanonOctober14,20077:44AM
theproblemwithvenndiagramsisthatardbmstableisnotthesamethingasaset.
WesleyTanakaonOctober14,20078:37AM
You'rerightJe.
Thisisausefulexplana on,asfarasge ngpeopletounderstandjoinsintermsofsomethingtheyalreadyunderstand(rudimentaryset
theory).However,itshouldbemadeclearthatthisisnotwhatismeantbythestatementthat"therela onaldatabasemodelisbased
onsettheory".Foralong me,IthoughtIunderstoodthatstatementbecauseIhadthisVenndiagramunderstandingofjoins.
Joinsdonotmapdirectlytothebasicaddi veopera onsofsettheory(union,intersect,dierence),whichcreatenewsetsbywayof
simplyincludingorexcludingelementsofothersets.TherearewaystogetthoseinSQL,butitinvolveschainingUNIONandMINUS
statements.
Joins,rather,aremappingopera ons,whichcreatenewsetsbytakinganelementfromeachset,accordingtoasetofrules,andlumping
themtogetherinanewelementforthenewsetthatisactuallyitselfasmallsetcontainingtheoriginaltwoelementsfromtheother
sets.
IfAisanaddi vesetopera on(representablebyaVenndiagram),thentheresultofAonsetsXandYisasetofmembersofXandY.
A(X,Y)={x1,y1,x2,x3,y4,y5,...}
Indatabaseterms,eachelementoftheresul ngsetissimplyarowfromeitherXorY.
Inrealworldterms,it'slikesor ngjellybeans.Throwthemallintoabucket,throughasieve.Thesieveeliminatesallbutthe
appropriateshapedones,butwhatgetsthroughiss llwhatyoustartedwith:anassortmentofjellybeans.
IfBisamappingsetopera on(representablebyalinedrawingmatchingques on),thentheresultofBonsetsXandYisasetofsets
eachcontainingamemberfromXandamemberofY.
B(X,Y)={{x1,y1},{x2,y2},{x3,y3},...}
Indatabaseterms,eachelementoftheresul ngsetisanewtypeofrowthatisalumpingtogetherofarowfromXandarowfromY.
15 de 19
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...
Inrealworldterms,anexamplewouldbetakingabucketoforangesandabucketofapples,andpullingoutpairsofoneofeachthatare
thesamesize,pu ngthepairstogetherinli lebags,andthenpu ngthosebagsintoathirdbucket.Youdon'tgetabucketofapples
andoranges.Yougetabucketofpairsofanappleandanorange.
Lookingatitthisway,itshouldbereasonablyeasytoseethatthereisafundamentaldierencebetweenjoinsandthesimple
union/intersect/dierencesetopera ons.
WaterBreathonOctober15,20075:40AM
"Exceptthatvenndiagramsexplainsetlogic,andSQLJoinshaveveryli letodowithsetlogic.
Scaryhowmanypeopleareagreeingwiththis.
Wya onOctober12,200707:29AM"
Mythoughtsexactly!
cloud9ineonOctober15,20075:58AM
Je,thisisgreat!HowaboutvisuallyexplainingwhyyouhaveSELECTallthecolumnsyouareGROUPingby?Ialwayshaveahard me
explainingthatonetopeople!
JFonOctober15,20078:39AM
I'mafraidthisconceptismisleadingonthereasonsmen onedbySvenGroot.
TheresultofajoinisnotthoseitemsintableAandthoseitemsintableB,itisa"joined"combina onofthetwo.Thediagramsyou
havedrawnaresetdiagramsandarecreatedinSQLusingthesetoperatorsUNIONandINTERSECT.
JoinsareacompletelydierentconceptwhichIbelievearebestexplainedusingjustthetableoutputsyouhaveabovewithoutadding
theincorrectvenndiagrams.
JF,theexplana onbehindSELECTandGROUPBYcanbedescribedsimply.
SELECTCOUNT(*)FROMPeople
Thiswillreturnacountof100people
SELECTEyeColour,COUNT(*)FROMPeopleGROUPBYEyeColour
ThiswillreturnBlue20,Green50,Brown30
SELECTCOUNT(*)FROMPeopleGROUPBYEyeColour
Thiswillreturn20,50,30whilstthiscontainsthecountsthatyouarelookingfor,theyareuselessasthereisnorela ontoeachcount
andwhattherepresent.
RobinDayonOctober15,200710:53AM
AssumingPirateandNinjaareiden calrecordsinbothtables,theveryfirstthingthatcametomindaswhatresultIwouldwantwhenI
joinTablesABwas
Pirate
Monkey
Ninja
Spaghe
Rutabaga
16 de 19
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...
DarthVader
Thisseemstobetheintui vemeaningofjoin.Venn'sdon'twork.
jamesmaidaonOctober15,200712:09PM
Thisisaverylikablear cle,Ipersonallyreallylikethewayyou'vedonethis...
DanielonOctober16,200711:01AM
Itneverceasestoamazemehowmanyfolksbecome"experts"onatechnicaltopiconcesomebodytakesthe metowriteaboutone.
Igivepropstotheauthorofthear clepresentedhere.Ineededtounderstandthisinforma on,anditwasputtomevisuallyinawayI
couldparsequiteeasily.
Asforthefolksdissec ngthisar cle,nitpickingeventhepremise,Iaskthatyoupleasewriteabe erone,andpostthelinkinsteadof
complaining.Iwillthendropbyandpickitapartoutofprofessionaldiscourtesy.
Thanks.
DadonOctober18,200711:48AM
TheCartesianproductof2setsisthesetofallcombina onsoforderedpairswhichcanbeproducedfromtheelementsofbothsets.So
theVennrepresenta onwouldlookliketwopilesofpokerchipsnexttoeachother,eachpilenumberingthenumberofdatapointsin
theotherbo omchip.
BarfoRamaonOctober19,20071:25PM
ThanksforthisgreatTutorial:)
LeononOctober22,200710:58AM
Nicewaytoexplainthingsinjoins.Byseeingtheexamplenobodycannotforgetjoins.
Keepitup.Hopeyouwillpublishmanymorear clewhichwillbeusefultoall.
Thanks,
Satheesh.
SatheeshonOctober27,200711:49AM
thanksforthis,IaminaclassforcrystalreportsandIshowedmanyandithelpedthem
BrianonOctober30,20079:28AM
17 de 19
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...
nicequicklessononjoins.Thisisexactlywhatiwanted.
JaxonOctober31,200711:25AM
Greatexplana onofthebasicsofinnerandouterjoins.
I'llbereferringito enandpassingiton.
Alsoverybravetoraiseanythinghereasnot100%perfectequalsrubbish
Mar n
Mar nonNovember2,20075:21AM
ThankgodforVenndiagrams!Goodjobmate.
LukeonNovember13,20078:19AM
Wow!Terrifictutorial.I'veneverunderstoodJOINSbeyondtheconceptofthem.Thankyoufordemys fying!
Clay
ClayonNovember13,20078:52AM
Thankyousomuchformakingthisavailable.CheersfromtheUK
JamesPrinteronNovember14,20072:54AM
VERYGOODEXAMPLE,PLZSENDAFEWEXAMPLETOEMAILID.
myidissuresh_worldcom@yahoo.co.in
sureshonNovember15,20077:09AM
Onehelpfulsteptounderstandcomplexqueriestoindentthesubqueries.Thiscanbedoneautoma callywiththisfreeSQLForma er
ath p://www.sqlinform.com
GuidoMarcelonNovember22,200711:45AM
thisisawesome..
ArunaonDecember2,20073:00AM
18 de 19
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...
Thisar cleisgreat!Apictureisworthathousandwords,andyourpictureshavehelpedmetounderstandSQLjoins.Thanks.
DerekonDecember7,200711:46AM
HeythatwasaCLEARexplana on...juststartedupwithsqlite
anddidntgetwhyiwasnotge ngtheselec oniwanted.
Nowido!
HennieonDecember8,20079:05AM
howdoyoujointwocolumnstogetherandgetonecolumninaquery.ForEX:ihavelastnameandfirstnamecolumnsinatable.iwant
tojointhesetwocolumnstogetherandgetlastnameandfirstnameinonecolumn??
InquisitoronDecember13,200712:15PM
Goodjob.
GurmeetonJanuary2,20089:45AM
AlthoughI'mfamiliarwiththetopic,Is lllikeyourniceandeasywayofexplainingthings,nicework.
A.NETDeveloper'sBlogonJanuary6,20089:35AM
ThiswasaGREATexplana on.IamworkingwithajuniorDBAandthishashelpedtremendously.Iwillhavetogobackandreadsomeof
yourotherblogs.
AWESOMEJOB!!!!!
SHALLonJanuary8,20088:58AM
Thereisaquerybuildertoolthatcomeswithoracleapex.Checkitout.
OracleTube.comonJanuary16,200810:44AM
It'sagreatwaytoexplainthings....
thanks
PrajeeshonFebruary9,20085:05AM
19 de 19
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...
ThanksforthisJe,wasstrugglingabitwiththeconceptbutyou'vemadeitclearenoughthatevenIcangetmyheadaroundit:)
AndyonFebruary18,20085:29AM
Awesome!
JulieMcBrienonMarch4,200810:09AM
IreallyhavetohandittoyouJe,thewayyoubreakthingsdownisjustgreat.Ireadtheblogsevery meyoupostone.Thisonein
par cularcameinhandyjusttheotherday.OurQAteamwashavingtroubleunderstandingwhatwasgoingoninthedatabaseandwe
developerswouldsendthemqueriestoruntofindthedatatheyneeded.TheQAteamhasarudimentaryunderstandingofSQL,but
couldn'tquitegraspjoins.Isentalinktothisar cletoourleadQA,andnowyourar cleisfirmlypostedonhercubewallforreference.
Justwantedtosaythankyoufortheblogs!
ArcondonMarch11,20088:56AM
Morecomments
Thecommentstothisentryareclosed.
Content2012JeAtwood.Logoimageusedwithpermissionoftheauthor.1993StevenC.McConnell.AllRightsReserved.