coding horror_ a visual explanation of sql joins.pdf

19
programming and human factors by JeAtwood A Visual ExplanaƟon of SQL Joins October 11, 2007 I thought Ligaya Turmelle's post on SQL joins was a great primer for novice developers. Since SQL joins appear to be setbased, the use of Venn diagrams to explain them seems, at rst blush, to be a natural t. However, like the commenters to her post, I found that the Venn diagrams didn't quite match the SQL join syntax reality in my tesƟng. I love the concept, though, so let's see if we can make it work. Assume we have the following two tables. Table A is on the leŌ, and Table B is on the right. We'll populate them with four records each. id name id name -- ---- -- ---- 1 Pirate 1 Rutabaga 2 Monkey 2 Pirate 3 Ninja 3 Darth Vader 4 Spaghetti 4 Ninja Let's join these tables by the name eld in a few dierent ways and see if we can get a conceptual match to those niŌy Venn diagrams. SELECT * FROM TableA INNER JOIN TableB ON TableA.name = TableB.name id name id name -- ---- -- ---- 1 Pirate 2 Pirate 3 Ninja 4 Ninja Inner join produces only the set of records that match in both Table A and Table B. SELECT * FROM TableA FULL OUTER JOIN TableB ON TableA.name = TableB.name id name id name -- ---- -- ---- 1 Pirate 2 Pirate 2 Monkey null null 3 Ninja 4 Ninja 4 Spaghetti null null null null 1 Rutabaga null null 3 Darth Vader Full outer join produces the set of all records in Table A and Table B, with matching records from both sides where available. If there is no match, the missing side will contain null. Coding Horror: A Visual Explanation of SQL Joins http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j... 1 de 19 31/08/2012 07:18 a.m.

Upload: alvarezd

Post on 05-Nov-2015

224 views

Category:

Documents


3 download

TRANSCRIPT

  • programmingandhumanfactorsbyJeAtwood

    AVisualExplanaonofSQLJoinsOctober11,2007

    IthoughtLigayaTurmelle'spostonSQLjoinswasagreatprimerfornovicedevelopers.SinceSQLjoinsappeartobesetbased,theuseofVenndiagramstoexplainthemseems,atfirstblush,tobeanaturalfit.However,likethecommenterstoherpost,IfoundthattheVenndiagramsdidn'tquitematchtheSQLjoinsyntaxrealityinmytesng.

    Ilovetheconcept,though,solet'sseeifwecanmakeitwork.Assumewehavethefollowingtwotables.TableAisonthele,andTableBisontheright.We'llpopulatethemwithfourrecordseach.

    id name id name-- ---- -- ----1 Pirate 1 Rutabaga2 Monkey 2 Pirate3 Ninja 3 Darth Vader4 Spaghetti 4 Ninja

    Let'sjointhesetablesbythenamefieldinafewdierentwaysandseeifwecangetaconceptualmatchtothoseniyVenndiagrams.

    SELECT * FROM TableAINNER JOIN TableBON TableA.name = TableB.nameid name id name-- ---- -- ----1 Pirate 2 Pirate3 Ninja 4 Ninja

    InnerjoinproducesonlythesetofrecordsthatmatchinbothTableAandTableB.

    SELECT * FROM TableAFULL OUTER JOIN TableBON TableA.name = TableB.nameid name id name-- ---- -- ----1 Pirate 2 Pirate2 Monkey null null3 Ninja 4 Ninja4 Spaghetti null nullnull null 1 Rutabaga null null 3 Darth Vader

    FullouterjoinproducesthesetofallrecordsinTableAandTableB,withmatchingrecordsfrombothsideswhereavailable.Ifthereisnomatch,themissingsidewillcontainnull.

    Coding Horror: A Visual Explanation of SQL Joins http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...

    1 de 19 31/08/2012 07:18 a.m.

  • SELECT * FROM TableALEFT OUTER JOIN TableBON TableA.name = TableB.nameid name id name-- ---- -- ----1 Pirate 2 Pirate2 Monkey null null3 Ninja 4 Ninja4 Spaghetti null null

    LeouterjoinproducesacompletesetofrecordsfromTableA,withthematchingrecords(whereavailable)inTableB.Ifthereisnomatch,therightsidewillcontainnull.

    SELECT * FROM TableALEFT OUTER JOIN TableBON TableA.name = TableB.nameWHERE TableB.id IS nullid name id name-- ---- -- ----2 Monkey null null4 Spaghetti null null

    ToproducethesetofrecordsonlyinTableA,butnotinTableB,weperformthesameleouterjoin,thenexcludetherecordswedon'twantfromtherightsideviaawhereclause.

    SELECT * FROM TableAFULL OUTER JOIN TableBON TableA.name = TableB.nameWHERE TableA.id IS null OR TableB.id IS nullid name id name-- ---- -- ----2 Monkey null null4 Spaghetti null nullnull null 1 Rutabaganull null 3 Darth Vader

    ToproducethesetofrecordsuniquetoTableAandTableB,weperformthesamefullouterjoin,thenexcludetherecordswedon'twantfrombothsidesviaawhereclause.

    There'salsoacartesianproductorcrossjoin,whichasfarasIcantell,can'tbeexpressedasaVenndiagram:

    SELECT * FROM TableACROSS JOIN TableB

    Thisjoins"everythingtoeverything",resulngin4x4=16rows,farmorethanwehadintheoriginalsets.Ifyoudothemath,youcanseewhythisisaverydangerousjointorunagainstlargetables.

    Coding Horror: A Visual Explanation of SQL Joins http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...

    2 de 19 31/08/2012 07:18 a.m.

  • PostedbyJeAtwood

    Relatedposts:

    AllAbstraconsAreFailedAbstraconsDeadlocked!GivemeparameterizedSQL,orgivemedeathCompiledorBust?StoredProceduresvs.AdHocSQL

    Coding Horror: A Visual Explanation of SQL Joins http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...

    3 de 19 31/08/2012 07:18 a.m.

  • 190Comments

    Funny,Ijustexplainedthistoacoworkerinthesamemannerearlierintheweek.Iguessitneverdawnedonmethatothersmayhaveneverthoughtaboutjoinsintermsofthesediagrams.Goodpost,Je!

    ShawnWheatleyonOctober12,20072:14AM

    HeyJe,thanksforthegreatblogIthoroughlyenjoyreadingeverysingleoneofyourposts.

    EventhoughIoenamfamiliarwiththeconceptsyoutalkof,Ifindthesimplemannerinwhichyoubreakdowntheissuesisalwaysagreatrefresher.

    Keepupthegreatwork.

    capdogonOctober12,20072:32AM

    linkedfromjoin(SQL)enwikipediatoyourblogentry...yourpostismuchbeer(orsimplisc)thanthetechtalkonthatwikipediaentry;)

    hackckonOctober12,20073:00AM

    ThepostismuchsimplerthantheWikipediaentrybecauseitomitsallthenontrivialcases.AlloftheseexamplesassumethateachentryintableAwillbematchedbythejoinpredicatetoatmostoneentryintableB,andviceversa.

    WeebleonOctober12,20073:35AM

    I'mnotevensophiscatedenoughtousedatabasesanymore(mycareerasadeveloperhasdevolved),butwhenIwas,99%ofthemeIusedinnerjoinsandjustthoughtofitasthedatacommontobothtables.EverynowandthenIwantedsomedatathatdidn'tfitthatkindofjoinandI'ddoaleouterjointogetthedatathatwas"leout".

    BradonOctober12,20073:47AM

    SpeakingaboutOracle(+)syntaxandLEFT/RIGHT[OUTER]JOINsyntaxthereisadierence.Anditisnicelydescribedherehp://www.oreillynet.com/pub/a/network/2002/10/01/whatsinacondion.html

    SpeakingaboutANSIsyntaxwhereeveryonehastoexplicitlysaytomakeCROSSJOINtogetCartesianproductatleastinOracleitisnottrue,usingstupid(atleasttomymind)NATURALJOINclauseonecaneasilygetCROSSJOINandalsoJOINonsuchcolumnsheneverthoughtitreallyis.I'vebloggedaboutitherehp://gplivna.blogspot.com/2007/10/naturaljoinsareevilmooifyou.htmlDon'tknowwehetheritisjustOraclespecificorasperANSISQLstandard.

    SpeakingaboutINNNERJOINSasaCartesianproductandtheneliminangallunnecessaryrows,atleasttherealmechanicsinOracleisabsolutelydierent,therearefollowingpossibiliesfordoingthem:NESTEDLOOPS(OUTER)HASHJOIN(OUTER)MERGEJOIN(OUTER)andforCartesianproductitusesMERGEJOINCARTESIAN,andthat'swhenusuallytherealtrouble(fillingtemp)starts;)TherealchoiceamongNestedloops,hashjoinormergejoinatleastdependsondata,stascs,availablememoryforasession,explicitlygivenavailablememoryforhashjoinsormergejoins(btwthereispossibilitytogiveforonebutnotforother),systemworkload,hints,inializaonparametersallowingceratainjointypes(atleastforhashjoins)andprobablysomethingother:)

    Coding Horror: A Visual Explanation of SQL Joins http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...

    4 de 19 31/08/2012 07:18 a.m.

  • GintsPlivnaonOctober12,20073:51AM

    HiJe,

    IthinkyourillustraonsmakeoneBIGassumpon:TableAandTableBcontainuniquerows.Ifeithertablecontainedduplicatematchingrecords,thenthewholeVenndiagramwillnothold(thecardinalityofthesetswillnotaddup).IamafraidthisvisualexplanaonwillleadsometothinkthatyoucanuseSQLjoinstodofilteroperaonswhichshouldn'tbedonethisway.

    Althoughit'sniceaempttoexplainSQLjoins,overallIthinkitismisleading.

    dt

    dtonOctober12,20073:57AM

    OneoftheworstthreemonthsofmyCStrainingwasaclassostensiblyondatabasetheorywhichwasreallyabootcampinSQLsyntax,taughtbyaJohnnyonenoteprofessorwhothoughtSQLandRDMSswerethegreatestinvenonofmankind.

    Thisexperienceturnedmeodatabasesfor15yearsunlonedayintheshowerIrealizedthatjoinswereanalogoustosettheory,inaroughway.(Yestheyare,allyounaysayers!"Givemeeverythingthat'sthereANDthere"or"Givemeeverythingthat'sthereORthere"maynothandleallthepossibleinputs,butit'sagoodjumpingopointforexplaining"inner"and"outer."Andwhocameupwiththatstupid,arbitraryterminologyanyway?)

    IsllthinkSQLisanawfullanguage,though,andrelaonaldatabasesareanuglyhackmandatedbyhardwarelimitaonstrumpingelegantdesign.OLAP"cubes"aresoclearlyabeersoluonsointuivelyclearandobviousthenaturalgeneralizaontohigherdimensionsoftheflatfiledatabase.

    AlexChamberlainonOctober12,20074:09AM

    Tome,aCartesianProductwouldbebestillustratedbybothcirclesbeingblank.

    Granted,alltheSQLguruswillprobablyspitfeathersatmyoutrageoussuggeson,butforme,it'sabeaufullysimplemethodofexplainingsimplejoinsandI'llbeusingitinmetechnicaldocumentaon!

    Thanksforthisarcle,Je.

    KevinonOctober12,20074:12AM

    Je,youare_the_masterofwellcraedblogpoststhatsomemesdon'tsaymuch,butsomehowgatherscadsofinanecomments!Thisoneandthepreviouspost(onexercise)aregreatexamples.

    Now,notallofyourpostsareinthiscategory,thankGod!ButI'mwatchingyou...

    SteveonOctober12,20074:25AM

    HeyNowJe,Thesediagramsmakemethinkofwhenlearningofclassicbooleanlogic.CodingHorrorFan,Cao

    CaoonOctober12,20074:37AM

    Coding Horror: A Visual Explanation of SQL Joins http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...

    5 de 19 31/08/2012 07:18 a.m.

  • Well,thedatabasepraconerrejoice,andthesetrelaonistscringe.

    Thereisonlyonejoin,whichisthecrossproduct(eachrowofthefirsttableconcatenatedtoeachrowofthesecondtable).TheINNERJOINexampleonlydiscardssomerowsbythewhereclause,otherwiseitis(orshouldbe)thesameastheCROSSJOIN.Theouterjoinisahackthatisn'tveryfirmlyrootedinrelaonalalgebra.

    AndreasKreyonOctober12,20074:47AM

    NiceJe,thankyousomuchforthispost!

    IalwaysgotconfusedwithJOINSandhowtheywork,that'soneofthesethingsthatarehardtobeexpainedinabookoramanual.

    Butthesediagramsmakeitpreyclear,theyaregreat!

    jan.gonOctober12,20075:10AM

    Don'tforgetEXCEPT!Whichwas(andaddionallysllis)MINUSinOracle.ForyearsIthinkOraclewastheonlyRDBMSthatimplementeditandIhad,innearly20years,useditallof,oh,once.Unllastweek,whenIuseditthesecondme.

    It'sthesameasyourfourthexample:insteadof

    SELECT*FROMTableALEFTOUTERJOINTableBONTableA.name=TableB.nameWHERETableB.idISnull

    wecansay

    SELECT*FROMTableAMINUSSELECT*FROMTableB

    (IusedtheoldOracleoperatorit'smoreexpressivetomyeyes)

    Noteveryplaormimplementstheoperatoryet:MySQL(whichIjustchecked)doesn't,forexample.MSSQLServer2005does.SQLIte?Hangon...yup,thatworksinv3atleast.

    MikeWoodhouseonOctober12,20075:21AM

    Verystrange.Inmy"DatabaseManagement"classatArizonaStateUniversityastudentaskedaboutJoin'sandmyprofessorsaid"Ineverusethem.JustsckwiththeWHEREsyntax".

    Thiswasamoretheorecalcoursethough.WespentFARmoremeinrelaonalalgebra/calculusandalgorithmsforensuringatomictransaconsthanwedidinmorepraccalstulikedatabasenormalizaon.

    Hmm...lotsofpeoplesaythetheorecalstuisawasteofme.Forme,well,IalmostbecameamathmajorinsteadofCS,soIfindthetheorecalstumoreinteresng.

    KGonOctober12,20075:21AM

    Ifyoudon'tuseranyjoinfeatureandjustdo"select*fromTableA,TableB",youhaveyourcrossjoin.

    Coding Horror: A Visual Explanation of SQL Joins http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...

    6 de 19 31/08/2012 07:18 a.m.

  • joskeonOctober12,20075:26AM

    Venndiagrams.

    wow,sosimple,soobvious;howcomeIhaven'tseenthisanywhereelse?

    davidonOctober12,20075:42AM

    HiJethat'sannicediagramandanewwayofpresenngthesqljoinfuncon.

    RockonOctober12,20075:47AM

    Yetanothercaseoftheblindleadingtheblind(downtheblindalleyofignoranceandarrogance);theoriginal,BTW.Atleastyoumadeandaempttofixitup.Butreadingallthose"nowIgetit"comments,makesitclearerwhyYahooslikeGWBushgetawaywithbaldfacedlies."Peoplebelievewhattheywanttobelieve,whenitmakesnosenseatall"/Mellencamp.

    Nowwe'llhaveanothergaggleoffolksrunningaroundfawningonAmblerandFowler.Gad.TheHorror,theHorror.

    BuggyFunBunnyonOctober12,20076:22AM

    ThankstothisI'mnowskippingmerrilydownthepathofBOMmanagementandstockcontrol,ratherthanflickingfuriouslythroughTeachyourselfbooks,thanks

    ChrisonOctober12,20076:36AM

    Ilikeitthanksforyourwork.

    cocobearonOctober12,20076:42AM

    Excellentpost.

    Everyonewhohasfollowed(andpassed)acomputersciencebeginnercourseshouldbeabletounderstandthis.

    RasmusonOctober12,20076:45AM

    It'simportanttonotethatwhenjoiningtwotablesonnonindexedcolumnsmostdatabasesperformtheequivalentofacrossjoinandthenweedouttherowsthatdon'tmatchthejoin/wherecriteria.Whilethisdoesntreallyimpactthequeryresults,ithasabigimpactonqueryperformance.

    InMySqlyoucanrun:explainmyquerytodetermineifthequeryisusingindexesandreviewperformanceofallyourqueries.

    CRonOctober12,20076:59AM

    Perfectming.IjusthadanewprojectthrownonmydeskthatwillrequireworkingwithSQLsomethingIknowlileaboutandhaveavoided.Termsthathaveglazedmyeyesinweekspastsuddenlymakesense.

    Coding Horror: A Visual Explanation of SQL Joins http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...

    7 de 19 31/08/2012 07:18 a.m.

  • WombatonOctober12,20077:13AM

    dtis100%right.Youreallyneedadisclaimerthatindicatesthatyoursetdiagramsonlyholdwhenthereisatbestaonetoonecorrespondencebetweenjoincriteriavaluesinthetables.

    Thesecondyouhavetwoorthreepiratesinoneofthetables(an_extremely_commonrealworldscenario,probablymuchmorecommonthanthesimplifiedcaseyoushowhere)yourVenndiagramsbreakdown.

    MaWigdahlonOctober12,20077:29AM

    WhatagreatwaytoexplainJOINs,I'mcertaintherearethousandsofstudentsthatwouldbenefitfromthis...apictureistrulyworthathousandwords(especiallyincaseslikethis).

    ThomasBorzeckionOctober12,20077:38AM

    Ialwaysuseleouterjoinsandneverreallylikedtherightouterjoin.Isthereanymetheyareuseful?Italwaysseemsbassackwardstousearightouterjoin.

    Ofcourseotherdevelopersusevisualquerydesignerswhichuserightouterjoins...

    JoeBeamonOctober12,20077:39AM

    IsitjustmeorOracle'ssyntaxismuchsimplerthanthat?Like:

    select*fromTableA,TableBwhereTableA.Name=TableB.Name

    I'mfamiliarwithboth,bothIalwayslikedthatonebeer.

    RicardoonOctober12,20077:48AM

    Je,

    ThisisgreatforthoseSQLtypesthatdidn'ttakeasettheory,relaonalcalculusorevendiscretemathincollege.

    I'dlovetoseeyouvisualizeacrossproduct:)

    JayR.WrenonOctober12,20077:57AM

    Ricardo,thatsyntaxispreANSI.MostdatabasessllsupportitbuttheadvantagesoftheINNERJOIN,etc.syntaxare:itmakesthequeriesmoreportableacrossdatabases;itallowsseparaonofthejoincriteriafromthefiltercriteria,whichimprovesreadability;andallowsfullouterjoinswithoutsyntacchacks.

    AnotherhugebenefitisthatifyouwanttodoaCROSS(Cartesian)JOIN,andusuallyyoudon't,youhavetocallitoutspecifically.Intheoldsyntax,ifyouscreweduptheWHEREclauseyoucouldgetwildlyhugeresultsetsduetoinadvertentCartesianjoins.

    MaWigdahlonOctober12,20078:02AM

    JoeBeam,

    Coding Horror: A Visual Explanation of SQL Joins http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...

    8 de 19 31/08/2012 07:18 a.m.

  • TheonlyuseIhavefoundforRIGHTOUTERiswheni'mtoolazytoreordermyquery.;)Otherthenthatitmakesmoresensetouseonlyonetype.

    IuseLEFTJOINtoo,asdomycompany.

    IagreewithotherresponseshereJe,whileit'sareallynicesimplewaytorepresentjoins,itdoesn'thandlemanytomanyoronetomanyverywellandlet'snottalkaboutmalformedjoins.

    It'sagoodprimer,butshouldperhapscontainawarning.

    EdKennyonOctober12,20078:08AM

    Thecommenterspoinngoutthatthediagramsbreakdownincaseofmulpleandorduplicateresults,areabsolutelyright.Iwasactuallythinkingofjoinsalongtheprimarykey,whichtendstobeuniquebydefinion,althoughtheexamplesarenotexpressedthatway.

    Likethecartesianorcrossproduct,anythingthatresultsinmorerowsthanyouoriginallystartedwithdoesabsolutelybreaksthewholevenndiagramconcept.Sokeepthatinmind.

    JeAtwoodonOctober12,20078:11AM

    Exceptthatvenndiagramsexplainsetlogic,andSQLJoinshaveveryliletodowithsetlogic.

    Scaryhowmanypeopleareagreeingwiththis.

    WyaonOctober12,20078:29AM

    Actually,I'vealwaysbeenabitshakyonjoinsmyself.IalwayshavetolookthemupanymeIneedtousingajointhatisn'tastandardfilteredcrossproduct.Butseeingthisvisualguidehasreallyhelpedmetograspitmuchbeer.IjustwentbackandreadtheWikipediaentryforjoinsanditmakescompletesensetomenow.BeforeseeingthisvisualrepresentaonImighthavejustglazedoverwhenreadingtheWikipediaarcle.

    Soeveniftheyaren'texactlyrighthavingavisualrepresentaonhasreallyhelpedmetounderstandwhatisgoingon.

    Thanks!

    MaonOctober12,20078:29AM

    AnicetrickisyoucanwritearbitraryfiltersintheONclauseofthejoin.IusethiswhenwringtrulyawfuljoinsorwhenIneedthelejoinwithanalreadyfilteredtable.

    JoshuaonOctober12,20079:17AM

    FromoneJetoanother,thisisabrilliantessayonasimpletopicsimplebutvexingtonewbies.IamaDB2DBA,andexplainingouterjoinstothenewbiedevelopersIencounterconstantlywillbemucheasierwithmaterialslikethis.Thanks,keepitcoming.

    JereyBenneronOctober12,20079:25AM

    IhaveneverseensuchagoodillustraonofSQLjoins.Goodwork.

    Coding Horror: A Visual Explanation of SQL Joins http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...

    9 de 19 31/08/2012 07:18 a.m.

  • JeonOctober12,20079:28AM

    Imustagreethatwhilethediagramsareafairlygoodillustraonsofwhathappenswithajoin,they'renotVenndiagramsinthestrictsensebecausethat'sjustnotwhat'shappening.WhatthefirstdiagramsaystomeisthatyougetallrecordsthatarebothinsetAandsetB(akaintersecon).That'sjustnottrue.Yougetasetofnewrecords,thatareneitherinsetAnorinsetB,buttheycontainacombinaonoftheaributesofbothsets.

    AaronG:joinsareconceptuallyaspecialcaseofthecartesianproduct.Howthedatabaseserveractuallycomputesthemisanothermaerenrely.

    Conceptually,inrelaonalalgebra,aninnerjoinisacrossproductfollowedbyaselecononthejoincondion.That'saterriblyinecientwaytocomputeit,butconceptually,that'swhatitis.

    SvenGrootonOctober12,200710:09AM

    ThemoronsrunningmydatabasefundamentalsclassatmyuniversitythoughtthatteachingtheCartesianproductasamethodofjoining,thenfilteringtheresults,wasavalidalternavetotheinsanelysimpleinnerjoin.Somanypoorstudentsaregoingtohaveahardmeintheindustryasaresult.

    LachlanMcDonOctober12,200710:21AM

    JonRaynor:Outofcuriosity,butwhatdatabasesotherthanOraclesupport+forjoins?

    Anyway,Ipreferthe"TableAaINNERJOINTableBbONa.something=b.somethingelse"syntaxover"TableAa,TableBbWHEREa.something=b.somethingelse"

    (MostDBsalsosupport"USING(something)"insteadof"ONa.something=b.something"ifthecolumnshavethesamename)

    ManyDBswillthrowanerrorifIaccidentlyomittheONstatementinsteadofgivingmeacrossjointhatIdidn'twant.Iimaginethatthequeryparserwouldalsoparseitfaster,asIspecifyupfrontwhichtypeofjoinI'mdoing;thequeryparserdoesn'thavetofigureitout.

    PowerlordonOctober12,200710:31AM

    Je,

    Ilikehowyoucanregurgitateanotherauthor'scontent,andgetawaywithit.

    PhilihponOctober12,200710:45AM

    Bigdeal,SQLfinallycaughtupwiththe1980's.UsedaveryfineDBMSandlanguage,NOMAD2,onmainframesthatdidthisstubutonlymuchbeerandmorethoroughly.

    SteveonOctober12,200710:58AM

    nicelydone.ThoughIdohavetoadmittofindingithumorousthatwhatstartedoutasafast,dirtywaytotrytoclarifytosomeone(onanIRCchannel)whytheyweregengthewronginformaonforajoinnowhasotherscorrecngandlinkingtome.

    LigayaTurmelleonOctober12,200710:59AM

    Coding Horror: A Visual Explanation of SQL Joins http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...

    10 de 19 31/08/2012 07:18 a.m.

  • Bindun!

    hp://www.khankennels.com/blog/index.php/archives/2007/04/20/gengjoins/

    Nicepostthough;)

    BarryonOctober12,200711:04AM

    "IwasundertheimpressionthatINNERJOINsuseahashmatchinternally(infact,I'mquitecertainofthis).CROSSJOINsobviouslydon't.ThereforeIdon'tseehowit'sreasonabletosaythatanIJisjustaspecialcaseoftheCJ.Isupposeinbreadandbuersettheory,wherethere'snonoonofahashoranindex,thiscouldwork,butthisistheworldofCS,wherethecleanacademicsoluonisalmostneverthemostpraccalone.TheIJyouspeakofisthenaivestpossiblealgorithm,onlyusedwhentherearenoindexes(andifyou'redesigningdatabaseswithoutanyindexes,well...stopdesigningdatabases)."AaronG

    AnIJisdefinedasbeingtheequivalentofafilteredCJ.Thefactthatthiswouldnotbeareasonableimplementaondoesnotmakeadierence.

    IJsareABSOLUTELYNOTimplementedexclusivelywithhashalgorithms.Sortmergealgorithmsandnestedloopalgorithmsareusedfrequently.

    RevMikeonOctober12,200711:10AM

    Je:

    Niceillustraon.IthinkyourexamplewouldbeminutelymorereadableifthelehandtablehadanIDcolumncontainingvalues1,2,3,4(asitdoes)buttherighthandtablehadanIDcolumncontainingvaluesA,B,C,D(insteadofnumbers).Itjustmakesthatnybiteasiertotellwhat'swhatbyavoidingthetwosimilarlookingbutdierentcolumns.

    MichaelChermsideonOctober12,200712:04PM

    Verynicearcle.IuseaSqlitedatabase(viathecommandline)tomanagemydatabaseofcomicsandthiswouldhavebeenaverynicethingtohavewhenIstartedout.Hopefully,thiswillhelppeopleingraspingSQLjoins.

    JeFlowersonOctober12,200712:07PM

    Iloveit.Thegrumpycomments,thatis.Plentyofcomplaintsthatthisistoosimpliscaviewtobeuseful,naryalinktoanythingmeaer.

    AndSQLaddictswonderwhyeveryoneelsewhohastodealwithRDBSjumpsatthefirstlibrarythatletsthemtreatthemasanythingotherthanRDBS...

    (justfinishedreworkingabigfatchunkofcodeoriginallywrientopullalltablesintomemoryanditeravelyquery,join,andsortthemevenanultrasimpliscunderstandingwouldhavedonesomeoneatonofgood)

    Shog9onOctober12,200712:11PM

    TheOracle(+),actuallypredatesOracle'susage,wasbecausewhenimplementedtherewasANSInoouterjoinsyntax.InOracle8,theyaddedtheANSIsyntax.Nooneshouldbeusingtheoldsyntaxsohopfullyyouwillnotbeingseeingitoutinthewide.

    willdieterichonOctober12,200712:17PM

    Coding Horror: A Visual Explanation of SQL Joins http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...

    11 de 19 31/08/2012 07:18 a.m.

  • Veryhelpful,thanks!!!

    SpeedmasteronOctober12,20071:04PM

    Whilethisisaninteresngexampleofthesekindsofjoin,IhavefoundthatinpracceIalmostneverneedanythingotherthanle/innerjoin.10yearsofpracce,andit'snottheworldsmostcomplicatedsqlmostoftheme,butthereitis.ThankGODthatstupidthingdidn'tillustrate"RIGHT"joinstoo!

    Thefirst"leouterjoin"isthesameasjust"lejoin".Thesecondoneisthesameaswell,justput"b.idisnull"inthewhere.Andpleasedon'tanyonetellmethattheopmizerisn'tgoingtofigurethatout(ordothesamethingwiththeouter.)Well,maybeitwon'tifitisMySQL,butthatswhyyoudon'tusethat.

    Die"outer",die!

    AndrewonOctober12,20071:12PM

    Excellentvisualrepresentaon.Thisshouldhelpthenoviceseeaconcretepictureintheirmindofthedierentjoins.WhileLINQisn'tquitesetbased(butclose)thesesamevisualizaonswouldworktheretoo.

    ShawnWildermuthonOctober13,20073:40AM

    Excellentarcle.

    Thanksalot.

    canyouwritesomethingsimilarforindexes.

    mpunaskaratgmaildotcom

    MandaronOctober13,20075:30AM

    Somethingyoumayormaynotknow....

    Duringthelate70'sMathswasrepackagedtoinclude

    VennDiagramsMatrices

    andsoon,withtheideaofpreparingforthecomingofcomputers.AtleastinEnglandthathappened...

    Whattheyteachnowishardformetodetermine,asmostvicmsoftheeducaonalsystemcannotcountoutthecorrectchangeinashop.

    DavidGingeronOctober13,20077:08AM

    Wowman,yourdesignisstellar.Contentisgreattoo...you'vegotanewreader.

    WillHarrisonOctober13,20078:40AM

    Coding Horror: A Visual Explanation of SQL Joins http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...

    12 de 19 31/08/2012 07:18 a.m.

  • HolycrapthisisWAYoverdue!I'vereadTONSofSQLbooksandNONEofthemhadthissimplediagram!

    TerrySmithonOctober13,20079:33AM

    IthinktheCartesianequaonorCrossProductinVennDiagramformwouldbebothcirclescombiningtoformasphere.

    TokesonOctober13,20079:35AM

    Interesng.Ifindjoinstobepreyobviouspersonally.Fundamentally,youhavetwosetsofrows,andyou'rematchingthemupbysomecriteria.Inaninnerjoin,youonlytakerowsthatmatchup.Inaleouterjoin,youtakealltheonesfromthele,plustheonesfromtherightthatmatch.Inarightouterjoin,theopposite.Ifyouhavemulplematches,youtakeallpossiblecombinaonsofthem.

    smackfuonOctober13,200710:00AM

    Thankyou!I'vebeenusingSQLforsolongandhavemanybooksonSQLandIhaveneverseensuchsimpleexamples.Iloveit!

    MitchellHashimotoonOctober13,200710:36AM

    ThereasonmanypeoplewhodoDBdevelopmenthavesuchainadequateunderstandingofthissimpletopicisbecausetheSQLlanguageisaninadequatetooltotrytoabsorbitfrom.So,ifyouneverweretaughtthisinschooloronthejob,it'skindofasurprise.

    SomeDBMS'hassyntaxwithmoredescripveverbs(e.g.,'Merge','Subset','Reject'),andVenndiagramsaswellinthevendordocumentaon.

    SQL2005isanimprovementover2000.ButthesadfactisismanypeoplelearnaboutrelaonalalgebrabywringSQLstatements.

    AlesspreyversionofmuchofwhatJeissayingcanbefoundhere:

    hp://db.grussell.org/secon010.html

    SteveonOctober13,200711:21AM

    WithallrespecttoJeAtwood,bewareifyou'vereadthispostandthink,"wow,that'seasywhydidnooneexplainitlikethatbefore?"Well,there'sareasonwhysomanySQLtutorialsandbooksdon'tusethesediagramsthey'reaninadequateexplanaonofwhatdatabasejoinsareallabout.

    Joinsareindeedanalogoustosetoperaons,butitisonlyananalogy.Understandwhat'sreallygoingon,oryouwillgetburnedwhenyouactuallyhavetousethethings.

    MaonOctober13,200711:48AM

    Verynicefirstpostonthesubject.IthinkmanyofthecommentsarevalidandIthinkitwouldbegoodtoconnuethisasaseriesthatbuildsupthemorecomplexissuesofSQLjoins.

    I,wholearnedthisstuthehardway,reallyapprecieatetheseprimers!

    RobCromaronOctober13,20071:18PM

    Coding Horror: A Visual Explanation of SQL Joins http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...

    13 de 19 31/08/2012 07:18 a.m.

  • IfonlysomeonehadexplainedSQLtomelikethiswhenIstarted...greatblog.

    SteveonOctober13,20071:38PM

    Greatstu,

    thanks

    VladonOctober14,20073:05AM

    verycoolvisualisaon,pleasedomoreofthat

    ravemanonOctober14,20077:44AM

    theproblemwithvenndiagramsisthatardbmstableisnotthesamethingasaset.

    WesleyTanakaonOctober14,20078:37AM

    Greatvisualexplanaon.I'veaddedthattomylistofreferencebookmarksforwhenI(oen)forgetthenatureofeachSQLjointype.

    AndyonOctober15,20072:22AM

    You'rerightJe.

    Thisisausefulexplanaon,asfarasgengpeopletounderstandjoinsintermsofsomethingtheyalreadyunderstand(rudimentarysettheory).However,itshouldbemadeclearthatthisisnotwhatismeantbythestatementthat"therelaonaldatabasemodelisbasedonsettheory".Foralongme,IthoughtIunderstoodthatstatementbecauseIhadthisVenndiagramunderstandingofjoins.

    Joinsdonotmapdirectlytothebasicaddiveoperaonsofsettheory(union,intersect,dierence),whichcreatenewsetsbywayofsimplyincludingorexcludingelementsofothersets.TherearewaystogetthoseinSQL,butitinvolveschainingUNIONandMINUSstatements.

    Joins,rather,aremappingoperaons,whichcreatenewsetsbytakinganelementfromeachset,accordingtoasetofrules,andlumpingthemtogetherinanewelementforthenewsetthatisactuallyitselfasmallsetcontainingtheoriginaltwoelementsfromtheothersets.

    IfAisanaddivesetoperaon(representablebyaVenndiagram),thentheresultofAonsetsXandYisasetofmembersofXandY.

    A(X,Y)={x1,y1,x2,x3,y4,y5,...}

    Indatabaseterms,eachelementoftheresulngsetissimplyarowfromeitherXorY.

    Inrealworldterms,it'slikesorngjellybeans.Throwthemallintoabucket,throughasieve.Thesieveeliminatesallbuttheappropriateshapedones,butwhatgetsthroughissllwhatyoustartedwith:anassortmentofjellybeans.

    IfBisamappingsetoperaon(representablebyalinedrawingmatchingqueson),thentheresultofBonsetsXandYisasetofsetseachcontainingamemberfromXandamemberofY.

    B(X,Y)={{x1,y1},{x2,y2},{x3,y3},...}

    Indatabaseterms,eachelementoftheresulngsetisanewtypeofrowthatisalumpingtogetherofarowfromXandarowfromY.

    Coding Horror: A Visual Explanation of SQL Joins http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...

    14 de 19 31/08/2012 07:18 a.m.

  • Inrealworldterms,anexamplewouldbetakingabucketoforangesandabucketofapples,andpullingoutpairsofoneofeachthatarethesamesize,pungthepairstogetherinlilebags,andthenpungthosebagsintoathirdbucket.Youdon'tgetabucketofapplesandoranges.Yougetabucketofpairsofanappleandanorange.

    Lookingatitthisway,itshouldbereasonablyeasytoseethatthereisafundamentaldierencebetweenjoinsandthesimpleunion/intersect/dierencesetoperaons.

    WaterBreathonOctober15,20075:40AM

    "Exceptthatvenndiagramsexplainsetlogic,andSQLJoinshaveveryliletodowithsetlogic.

    Scaryhowmanypeopleareagreeingwiththis.WyaonOctober12,200707:29AM"

    Mythoughtsexactly!

    cloud9ineonOctober15,20075:58AM

    Je,thisisgreat!HowaboutvisuallyexplainingwhyyouhaveSELECTallthecolumnsyouareGROUPingby?Ialwayshaveahardmeexplainingthatonetopeople!

    JFonOctober15,20078:39AM

    I'mafraidthisconceptismisleadingonthereasonsmenonedbySvenGroot.

    TheresultofajoinisnotthoseitemsintableAandthoseitemsintableB,itisa"joined"combinaonofthetwo.ThediagramsyouhavedrawnaresetdiagramsandarecreatedinSQLusingthesetoperatorsUNIONandINTERSECT.

    JoinsareacompletelydierentconceptwhichIbelievearebestexplainedusingjustthetableoutputsyouhaveabovewithoutaddingtheincorrectvenndiagrams.

    JF,theexplanaonbehindSELECTandGROUPBYcanbedescribedsimply.

    SELECTCOUNT(*)FROMPeopleThiswillreturnacountof100people

    SELECTEyeColour,COUNT(*)FROMPeopleGROUPBYEyeColourThiswillreturnBlue20,Green50,Brown30

    SELECTCOUNT(*)FROMPeopleGROUPBYEyeColourThiswillreturn20,50,30whilstthiscontainsthecountsthatyouarelookingfor,theyareuselessasthereisnorelaontoeachcountandwhattherepresent.

    RobinDayonOctober15,200710:53AM

    AssumingPirateandNinjaareidencalrecordsinbothtables,theveryfirstthingthatcametomindaswhatresultIwouldwantwhenIjoinTablesABwas

    PirateMonkeyNinjaSpagheRutabaga

    Coding Horror: A Visual Explanation of SQL Joins http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...

    15 de 19 31/08/2012 07:18 a.m.

  • DarthVader

    Thisseemstobetheintuivemeaningofjoin.Venn'sdon'twork.

    jamesmaidaonOctober15,200712:09PM

    Thisisaverylikablearcle,Ipersonallyreallylikethewayyou'vedonethis...

    DanielonOctober16,200711:01AM

    Itneverceasestoamazemehowmanyfolksbecome"experts"onatechnicaltopiconcesomebodytakesthemetowriteaboutone.

    Igivepropstotheauthorofthearclepresentedhere.Ineededtounderstandthisinformaon,anditwasputtomevisuallyinawayIcouldparsequiteeasily.

    Asforthefolksdissecngthisarcle,nitpickingeventhepremise,Iaskthatyoupleasewriteabeerone,andpostthelinkinsteadofcomplaining.Iwillthendropbyandpickitapartoutofprofessionaldiscourtesy.

    Thanks.

    DadonOctober18,200711:48AM

    TheCartesianproductof2setsisthesetofallcombinaonsoforderedpairswhichcanbeproducedfromtheelementsofbothsets.SotheVennrepresentaonwouldlookliketwopilesofpokerchipsnexttoeachother,eachpilenumberingthenumberofdatapointsintheotherboomchip.

    BarfoRamaonOctober19,20071:25PM

    ThanksforthisgreatTutorial:)

    LeononOctober22,200710:58AM

    Nicewaytoexplainthingsinjoins.Byseeingtheexamplenobodycannotforgetjoins.

    Keepitup.Hopeyouwillpublishmanymorearclewhichwillbeusefultoall.

    Thanks,Satheesh.

    SatheeshonOctober27,200711:49AM

    Ireallyhateyou.IhavenorecolleconofyourapingmywifebutIsllhateyou.

    CheesecakesLikeMeonOctober28,20079:45AM

    thanksforthis,IaminaclassforcrystalreportsandIshowedmanyandithelpedthem

    BrianonOctober30,20079:28AM

    Coding Horror: A Visual Explanation of SQL Joins http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...

    16 de 19 31/08/2012 07:18 a.m.

  • nicequicklessononjoins.Thisisexactlywhatiwanted.

    JaxonOctober31,200711:25AM

    Greatexplanaonofthebasicsofinnerandouterjoins.I'llbereferringitoenandpassingiton.Alsoverybravetoraiseanythinghereasnot100%perfectequalsrubbish

    Marn

    MarnonNovember2,20075:21AM

    Verysimple,I'amalwaysconfusedupwithsqloperaons,butIunderstandbeerwithsimplediagramslikeyours.Thksagainforthisnicejob.

    GhislainonNovember7,20073:36AM

    ThankgodforVenndiagrams!Goodjobmate.

    LukeonNovember13,20078:19AM

    Wow!Terrifictutorial.I'veneverunderstoodJOINSbeyondtheconceptofthem.Thankyoufordemysfying!

    Clay

    ClayonNovember13,20078:52AM

    Thankyousomuchformakingthisavailable.CheersfromtheUK

    JamesPrinteronNovember14,20072:54AM

    VERYGOODEXAMPLE,[email protected]

    sureshonNovember15,20077:09AM

    Onehelpfulsteptounderstandcomplexqueriestoindentthesubqueries.ThiscanbedoneautomacallywiththisfreeSQLFormaerathp://www.sqlinform.com

    GuidoMarcelonNovember22,200711:45AM

    thisisawesome..

    ArunaonDecember2,20073:00AM

    Coding Horror: A Visual Explanation of SQL Joins http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...

    17 de 19 31/08/2012 07:18 a.m.

  • Thisarcleisgreat!Apictureisworthathousandwords,andyourpictureshavehelpedmetounderstandSQLjoins.Thanks.

    DerekonDecember7,200711:46AM

    HeythatwasaCLEARexplanaon...juststartedupwithsqliteanddidntgetwhyiwasnotgengtheseleconiwanted.

    Nowido!

    HennieonDecember8,20079:05AM

    howdoyoujointwocolumnstogetherandgetonecolumninaquery.ForEX:ihavelastnameandfirstnamecolumnsinatable.iwanttojointhesetwocolumnstogetherandgetlastnameandfirstnameinonecolumn??

    InquisitoronDecember13,200712:15PM

    Goodjob.

    GurmeetonJanuary2,20089:45AM

    AlthoughI'mfamiliarwiththetopic,Islllikeyourniceandeasywayofexplainingthings,nicework.

    A.NETDeveloper'sBlogonJanuary6,20089:35AM

    ThiswasaGREATexplanaon.IamworkingwithajuniorDBAandthishashelpedtremendously.Iwillhavetogobackandreadsomeofyourotherblogs.

    AWESOMEJOB!!!!!

    SHALLonJanuary8,20088:58AM

    Thereisaquerybuildertoolthatcomeswithoracleapex.Checkitout.

    OracleTube.comonJanuary16,200810:44AM

    Assomeonesuggestedtocreatedsomethingthemselvesandthencricize;)I'vetriedtodescriberelaonshipsamongvariousjointypesusingERdiagrammhere:hp://gplivna.blogspot.com/2008/01/sqljointypesimstudyingbitsql.htmlAllcommentswelcome!

    GintsPlivnaonJanuary25,20082:43AM

    It'sagreatwaytoexplainthings....thanks

    PrajeeshonFebruary9,20085:05AM

    Coding Horror: A Visual Explanation of SQL Joins http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...

    18 de 19 31/08/2012 07:18 a.m.

  • ThanksforthisJe,wasstrugglingabitwiththeconceptbutyou'vemadeitclearenoughthatevenIcangetmyheadaroundit:)

    AndyonFebruary18,20085:29AM

    Awesome!

    JulieMcBrienonMarch4,200810:09AM

    IreallyhavetohandittoyouJe,thewayyoubreakthingsdownisjustgreat.Ireadtheblogseverymeyoupostone.Thisoneinparcularcameinhandyjusttheotherday.OurQAteamwashavingtroubleunderstandingwhatwasgoingoninthedatabaseandwedeveloperswouldsendthemqueriestoruntofindthedatatheyneeded.TheQAteamhasarudimentaryunderstandingofSQL,butcouldn'tquitegraspjoins.IsentalinktothisarcletoourleadQA,andnowyourarcleisfirmlypostedonhercubewallforreference.Justwantedtosaythankyoufortheblogs!

    ArcondonMarch11,20088:56AM

    Morecomments

    Thecommentstothisentryareclosed.

    Content2012JeAtwood.Logoimageusedwithpermissionoftheauthor.1993StevenC.McConnell.AllRightsReserved.

    Coding Horror: A Visual Explanation of SQL Joins http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-j...

    19 de 19 31/08/2012 07:18 a.m.