Beruflich Dokumente
Kultur Dokumente
Translate: SelectLanguage
Search
Home
Java
C/C++
Databases/SQL
SQLInterviewQuestions
Innervs.Outerjoins
SQLKeyDefinition
Whatisaselfjoin?Explainitwithanexampleand
DifferencesbetweenPrimaryand
ForeignKeys tutorial.
NaturalKeyInDatabase
Letsillustratetheneedforaselfjoinwithanexample.Supposewehavethefollowing
SecondaryKey tablethatiscalledemployee.Theemployeetablehas2columnsonefortheemployee
SimplekeyinSQL
name(calledemployee_name),andonefortheemployeelocation(called
SuperkeyExample
employee_location): Purva
WhatisReferentialIntegrity employee Silversand
Havingvs.Whereclause employee_name employee_location in Pune
Howdodatabaseindexeswork? Joe NewYork
AdvancedSQLInterviewQuestionsand
AnswersPart2
SELECTemployee_name
PracticeInterviewQuestion2continued
FROMemployee
DataMiningvs.DataWarehousing WHEREemployee_location="NewYork"
Ternary/ThreevaluedLogicinSQL
FindMaximumValueWithoutUsing So,insteadofaquerylikethatwhatwecoulddoiswriteanestedSQLquery(basicallya
Aggregate
querywithinanotherquerywhichismorecommonlycalledasubquery)likethis:
SQLInjectionExampleandTutorial
SQLInjectionPrevention
BlindSQLInjectionExample SELECTemployee_name
FROMemployee
ParameterizedQueriesvsPrepared
Statements WHEREemployee_locationin
(SELECTemployee_location
PreparedStatementExample
FROMemployee
Differencebetweenafulljoinandan WHEREemployee_name="Joe")
innerjoin?
Differencebetweenaleftouterjoinand
rightouterjoin?
Differencebetweenaleftjoinandaleft
outerjoin? Asubqueryisinefficient
SQL:HavingvsGroupBy Usingasubqueryforsuchasimplequestionisinefficient.Isthereamoreefficientand
SQL:GroupBywithmultiplecolumns elegantsolutiontothisproblem?
SQLSelectDistinctandOrderBy Itturnsoutthatthereisamore
efficientsolutionwecanuse
SQLOrderBydefaultsortorder
somethingcalledaselfjoin.Aself
Derivedtablevssubquery joinisbasicallywhenatableis
CorrelatedvsUncorrelatedSubquery joinedtoitself.Thewayyoushould
visualizeaselfjoinforagiventable
FindnthhighestsalarySQL
isbyimaginingthatajoinis
CardinalityinSQL
http://www.programmerinterview.com/index.php/databasesql/whatisaselfjoin/ 1/9
03/06/2016 SQL/Databases:Whatisaselfjoin?
performedbetweentwoidentical
SelectivityinSQLDatabases
copiesofthattable.Andthatis
CardinalityversusSelectivity exactlywhyitiscalledaselfjoin
becauseofthefactthatitsjustthe
Clusteredvs.NonClusteredIndex
sametablebeingjoinedtoanother
Pageversusblock copyofitselfratherthanbeing
DatabaseLocking joinedwithadifferenttable.
LockEscalation
Howdoesaselfjoin
DatabaseDeadlockExample work
Whatisadatabasetransaction?
Beforewecomeupwithasolution
SQLServerTransaction forthisproblemusingaselfjoin,we
shouldgooversomeconceptsso
OracleTransaction
thatyoucanfullyunderstandhowa
MySQLTransaction selfjoinworks.Thiswillalsomake
DB2Transaction theSQLinourselfjointutorialaloteasiertounderstand,whichyouwillseefurther
below.
ConcurrentUpdateProblem
HowtoTuneDatabasePerformance Aselfjoinmusthavealiases
DatabaseFullTableScan
Inaselfjoinwearejoiningthesametabletoitselfbyessentiallycreatingtwocopiesof
Whatiscostbasedoptimization? thattable.But,howdowedistinguishbetweenthetwodifferentcopiesofthetable
becausethereisonlyonetablenameafterall?Well,whenwedoaselfjoin,thetable
HowtotuneSQLqueries
namesabsolutelymustusealiasesotherwisethecolumnnameswouldbeambiguous.In
SQLIndexPerformance otherwords,wewouldnotknowwhichofthetwocopiesofthetablescolumnsisbeing
Whatisabitmapindex? referencedwithoutusinganaliasforeachcopyofthetable.Ifyoudontalreadyknow
whatanaliasis,itssimplyanothernamegiventoatablethinkofanaliasasa
OracleIndexesExamples
nicknameandthatnicknameisthenusedintheSQLquerytoreferencethetable.
Systemprivilegesvs.objectprivileges Becauseweneedtwocopiesoftheemployeetable,wewilljustusethealiasese1ande2
fortheemployeetablewhenwedoaselfjoin.
SQLGrant
SQLRevoke Selfjoinpredicate
SQLCreateUser
Aswithanyjointheremustbeaconditionuponwhichaselfjoinisperformedwecan
DatabaseRoles notjustarbitrarilysaydoaselfjoin,withoutspecifyingsomecondition.Thatcondition
SQLCASEStatement willbeourjoinpredicate.Ifyouneedarefresheronjoinpredicates(orjustjoinsin
general)thencheckthislinkout:Innervs.Outerjoins.
SQLSearchedCASEStatement
Now,letscomeupwithasolutiontotheoriginalproblemusingaselfjoininsteadofa
SQLInlineView
subquery.Thiswillhelpillustratehowexactlyaselfjoinworks.Thekeyquestionthatwe
RANK()versusDENSE_RANK() mustaskourselvesiswhatshouldourjoinpredicatebeinthisexample?Well,wewantto
findalltheemployeeswhohavethesamelocationasJoe.
Javascript
Becausewewanttomatchbetweenourtwotables(bothofwhicharethesametable
PHP
employeealiasedase1ande2)onlocationourjoinpredicateshouldclearlybeWHERE
Info>
e1.employee_location=e2.employee_location.Butisthatenoughtogiveuswhatwe
DataStructures
want?No,itsnot,becausewealsowanttofiltertherowsreturnedsinceweonlywant
peoplewhoarefromthesamelocationasJoe.
DesignPatternQuestions
So,howcanwefiltertherowsreturnedsothatonlypeoplefromJoeslocationare
ExcelInterviewQuestions
returned?Well,whatwecandoissimplyaddaconditionononeofthetables(e2inour
example)sothatitonlyreturnstherowwherethenameisJoe.Then,theothertable
HTML5
(e1)willmatchupallthenamesthathavethesamelocationine2,becauseofourjoin
predicatewhichisWHEREe1.employee_location=e2.employee_location.Wewill
Networking
thenjustselectthenamesfrome1,andnote2becausee2willonlyhaveJoesname.If
OrganicCotton thatsconfusingthenkeepreadingfurthertounderstandmoreabouthowthequerywill
OperatingSystems
Underwear work.
Recursion
GetQuotes So,theselfjoinquerythatwecomeupwithlookslikethis:
ApacheInterviewQuestions
Info>
SelfJoinSQLExample
General/Miscellaneous
NonTechnicalQuestions
SELECTe1.employee_name
FROMemployeee1,employeee2
InterviewinginIndia
WHEREe1.employee_location=e2.employee_location
ANDe2.employee_name="Joe"
WorkingAsaSoftwareEngineer
FinancialAnalystQuestions
ThisquerywillreturnthenamesJoeandJacksinceJackistheonlyotherpersonwho
JobAdviceForProgrammers
livesinNewYorklikeJoe.
Puzzles Generally,queriesthatrefertothesametablecanbegreatlysimplifiedbyrewritingthe
queriesasselfjoins.And,thereisdefinitelyaperformancebenefitforthisaswell.
AssortmentofKnowledge
Whatdoesaselfjoinlooklike?
http://www.programmerinterview.com/index.php/databasesql/whatisaselfjoin/ 2/9
03/06/2016 SQL/Databases:Whatisaselfjoin?
Whatdoesaselfjoinlooklike?
AmericanVocabulary
Itwillhelptremendouslytoactuallyvisualizetheactualresultsofaselfjoininternally.
TechnicalVocabulary Rememberthataselfjoinisjustlikeanyotherjoin,wherethetwotablesaremergedinto
onetemporarytable.Firstoff,youshouldvisualizethatwehavetwoseparatecopiesof
ScienceQuestions
theemployeetable,whicharegivenaliasesofe1ande2.Thesecopieswouldsimplylook
likethisnotethatweshortenedthecolumnnamesfromemployee_nameand
employee_locationtojustNameandLocationforconvenience:
FindaJob
JuniorProgrammer e1 e2
Paradigm...Columbia,MD
SoftwareDeveloper... Name Location Name Location
EsriPortland,OR Joe NewYork Joe NewYork
SoftwareProgrammer
Sunil India Sunil India
Seattle...Seattle,WA
SoftwareProgrammer Alex Russia Alex Russia
Future...Moorestown,NJ Albert Canada Albert Canada
EntryLevel...
Jack NewYork Jack NewYork
Gongos...AuburnHills,MI
SoftwareDeveloper...
Andthefinalresultsofrunningtheselfjoinqueryabovetheactualjoinedtablewould
Informatio...Calverton,MD
looklikethis:
WebApplication...
Deptof...Richmond,VA
e1.employee_name e1.employee_location e2.employee_name e2.employee_location
JrProgrammer...
LeidosSanDiego,CA Joe NewYork Joe NewYork
Scientific... Jack NewYork Joe NewYork
Columbia...NewYork,NY
SoftwareProgrammer Selfjoinsversusinnerjoins
ROBOVENTSterlingHeights,MI
Areselfjoinsandinnerjoinsthe
What: title,keywords same?Youmightbewonderingifall
Where: city,state,orzip selfjoinsarealsoinnerjoins.After
MicrosoftMechanics
all,inourexampleaboveourself
FindJobs
joinusesaninnerjoinbecauseonly
therowsthatmatchbasedonthe
joinpredicatearereturnednon
matchingrowsarenotreturned.
Well,itturnsoutthataselfjoinand
innerjoinarecompletelydifferent
concepts.Aselfjoincouldjustas
jobsby
wellbeanouterjoinoraninnerjoin
itjustdependsonhowthequery
01 Job Performance Office365SecurityMgmt
Visibility&ControlinyourtenantWatchandlearnto
iswritten.Wecouldeasilychange
thequeryweusedabovetodoa
activate.
LEFTOUTERJOINwhilethequery
02 SQL Query Examples stillremainsaselfjoinbutthat
wouldntgiveustheresultswewant
Selfjoinsmanageremployeeexample
05 SQL Server Optimization
Themostcommonlyusedexampleforselfjoinsistheclassicemployeemanagertable.
ThetableiscalledEmployee,butholdsallemployeesincludingtheirmanagers.Every
employeehasanID,andthereisalsoacolumnforthemanagerID.So,forexample,lets
saywehaveatablethatlookslikethisandwecallitEmployee:
1 Sam 10
Country UnitedStates
2 Harry 4
4 Manager NULL
10 AnotherManager NULL
Noticethatinthetableabovetherearetwomanagers,convenientlynamedManager
I'm not a robot
andAnotherManager.And,thosemanagersdonthavemanagersoftheirownas
notedbytheNULLvalueintheirManagercolumn.
Now,giventhetableabove,howcanwereturnresultsthatwillshoweachemployees
reCAPTCHA
name,andhis/hermanagersnameinnicelyarrangedresultswiththeemployeeinone
Privacy - Terms
columnandhis/hermanagersnameintheothercolumn.Well,itturnsoutwecanusea
http://www.programmerinterview.com/index.php/databasesql/whatisaselfjoin/ 3/9
03/06/2016 SQL/Databases:Whatisaselfjoin?
selfjointodothis.TrytocomeupwiththeSQLonyourownbeforereadingouranswer.
Selfjoinmanageremployeeanswer
Inordertocomeupwithacorrectanswerforthisproblem,ourgoalshouldbetoperform
aselfjointhatwillhaveboththeemployeeinformationandmanagerinformationinone
row.Firstoff,sincewearedoingaselfjoin,ithelpstovisualizetheonetableastwotables
letsgivethemaliasesofe1ande2.Now,withthatinmind,wewanttheemployees
informationononesideofthejoinedtableandthemanagersinformationontheother
sideofthejoinedtable.So,letsjustsaythatwewante1toholdtheemployee
informationande2toholdthecorrespondingmanagersinformation.Whatshouldour
joinpredicatebeinthatcase?
Well,thejoinpredicateshouldlooklikeONe1.ManagerID=e2.EmployeeIDthis
basicallysaysthatweshouldjointhetwotables(aselfjoin)basedontheconditionthat
themanagerIDine1isequaltotheemployeeIDine2.Inotherwords,anemployees
managerine1shouldhavethemanagersinformationine2.Anillustrationwillhelp
clarifythis.Supposeweusethatpredicateandjustselecteverythingafterwejointhe
tables.So,ourSQLwouldlooklikethis:
SELECT*
FROMEmployeee1
INNERJOINEmployeee2
ONe1.ManagerID=e2.EmployeeID
Theresultsofrunningthequeryabovewouldlooklikethis:
Notethatthereareonly2rowsreturnedthisisbecauseaninnerjoinisperformed,
whichmeansthatonlywhenthereisamatchbetweenemployeeIDsandmanagerIDs
willtherebearesultreturned.Andsincethereare2peoplewithoutmanagers(whohave
amanagerIDofNULL),theywillnotbereturnedaspartoftablee1,becauseno
employeeshaveamatchingIDofNULL.
Now,rememberthatweonlywanttoreturnthenamesoftheemployeeand
correspondingmanagerasapair.So,wecanfinetunetheSQLasfollows:
SELECTe1.Name,e2.Name
FROMEmployeee1
INNERJOINEmployeee2
ONe1.ManagerID=e2.EmployeeID
RunningtheSQLabovewouldreturn:
SamAnotherManager
HarryManager
Andthatistheanswertotheemployeemanagerproblemusingaselfjoin!Feelfreeto
postanycomments.
http://www.programmerinterview.com/index.php/databasesql/whatisaselfjoin/ 4/9
03/06/2016 SQL/Databases:Whatisaselfjoin?
Hiring?JobHunng?PostaJOBoryourRESUMEonourJOBBOARD>>
Subscribetoournewsletterformorefreeinterviewquestions.
Follow@programmerintvw
FOLLOWVaroonSahgal,AuthorofProgrammerInterview on
Previous... Next...
Sponsored
TVSApacheRTR2004VTestRideReview
auto.ndtv.com
HughGrantsexoticBengalinightswithSupriyaPathak
TheReelbyScroll.in
HairRegrowthWithoutaPrescriptionorSideEffects
HairforSure
FreeTaxPlanningAdviceAndCalculatorsFor201617
BigDecisions
BeattheHeatwithDeliciousHomemadeColdCoffee
TheFlyingSquirrel
48YearOldChildrenLoveThisActivityBox
41Comments ProgrammerInterview
1 Login
Jointhediscussion
Shwetha 3yearsago
Excellentexplanation.OneofthebesttutorialwebsitesIhavevisitedso
far.Everythingisexplainedinsuchasimpleway.greatwork!!
19 Reply Share
nitinchauhan 3yearsago
Iwouldliketoassertthatthisistutorialisamongstthetopofjavaand
databasetutorialsavailableonotherwebsitesandIsincerelythanksfor
providingsuchanexcellentqualityoftechnicalmaterialonsubjectslike
databaseandJava.ThemainthingthatIhaveobservedistheelaborate,
efficientandindepthexplanationofthekeyconceptswithexamplesthat
havehelpedmealotinfurthersharpeningmyskillsandknowledge.
Ihopethatyouwillcontinuethelegacyofprovidingthesameonotherhot
subjectsrelatedtojavaanddatabaseinthefuture.
Thanks,
NitinChauhan
4 Reply Share
http://www.programmerinterview.com/index.php/databasesql/whatisaselfjoin/ 5/9
03/06/2016 SQL/Databases:Whatisaselfjoin?
4 Reply Share
juhi 2yearsago
Bestexplanationavailableoninternet..:)
2 Reply Share
anonymous 3yearsago
oneofthebestexplanations...greatwork!
2 Reply Share
SmijiJohn ayearago
Goodone.Simpleandclear.
ifanemployeeismanagerformorethanoneemployees,thatmanager
nameappearinmultiplerows.
IfIwanttogetthelistofonlymanagersfromthetableandIdon'twant
employeename,wemayhavetouseeitherdistinctorasubquery.
Isthereanybetterapproachtoavoidduplicatesinsuchcases.
eg:
selectNamefromEmployeewhereEmployeeIDin(selectManagerID
fromEmployee)
or
selectdistinct(e2.Name)"ManagerName"fromEmployeee1innerjoin
Employeee2one1.ManagerID=e2.EmployeeID
1 Reply Share
Shubham 2yearsago
Awesomeexplanation..!!Thanks..!!
1 Reply Share
Ranju 2yearsago
Greatexplanation.Thankyou!
1 Reply Share
Amit 2yearsago
reallysuperbusefullexplaination...Thankyouverymuch
1 Reply Share
Steve0 2yearsago
ThefirstexplanationIgrokked.You'reawesome!
1 Reply Share
alia 2yearsago
THanx..forexplanation,
1 Reply Share
Sampath 2yearsago
ThanksfortheexcellentpostVaroon..Itisreallyreallyhelpfulforpeople
whowanttounderstandthebasics.MayGodBlessyou.
1 Reply Share
DharmenderKumar 2yearsago
inverysimplewords,theveryusefulexplanation.Thanks
1 Reply Share
Fai 3yearsago
SupertututhankyouyouAceIt:)
1 Reply Share
EswaranThirumalairaj 3yearsago
veryusefull
1 Reply Share
http://www.programmerinterview.com/index.php/databasesql/whatisaselfjoin/ 6/9
03/06/2016 SQL/Databases:Whatisaselfjoin?
1 Reply Share
abhynay 3yearsago
Veryinsightfulexplanation.Reallylovedthewayyouhandledthetopic.
1 Reply Share
JoeMann 3yearsago
GreatExample!Keepitup!
1 Reply Share
MarcoPeters amonthago
Excellentexplanation.
Reply Share
EmmaAbbas 7monthsago
thebestexplanationforselfjoins!
Thankyou.
Reply Share
Sandeep 8monthsago
Iwasfortunatetofindthiswebsite!!Thanksforthisgreatstuff.
Reply Share
titasbhattacharya 9monthsago
mostniceanddetailedexplanationthatIhaveevercomeacross..OSM
OSMWEBSITE,PLEASEKEEPUPTHEGOODWORK..andcontinue
tofeeduswithyourinvaluablecontent.BIGTHANKS
Reply Share
kumarik ayearago
veryniceexplanation
Reply Share
Bala ayearago
goodexplanationbutstillneedmoreclearansweraboutselfjoin
Reply Share
Anjali ayearago
soconfusedbeforeregardingselfjoin,nowigetit.Thanksalot...
Reply Share
MdFarooq ayearago
whatanexplantion,hatsofftoyouguys.
Reply Share
kanu ayearago
oneofthebestexplanation
Reply Share
BhavinRathod ayearago
Veryhandytoolforlastminutepreparation.Explainseverytopicperfectly
anddeeply.
Reply Share
suniltewatia ayearago
propert_detailstablenameorproperty_id,property_nametwocolumns
thenhowtogetalldata
Reply Share
G ayearago
Veryclearexplanation!Thanks
Reply Share
Ashi ayearago
http://www.programmerinterview.com/index.php/databasesql/whatisaselfjoin/ 7/9
03/06/2016 SQL/Databases:Whatisaselfjoin?
Ashi ayearago
explainedineasyway...thumbsup
Reply Share
Nishtha ayearago
Excellentexplanation.ThankYou
Reply Share
Cici 2yearsago
awesome!
Reply Share
raj 2yearsago
greatexplanation.Thankyou
Reply Share
FromIndia 2yearsago
thankusoomuch!!!!:)
Reply Share
NehaSood 2yearsago
howcanwesolveemployeemanagerproblemusingaliasing?
Reply Share
baidpunit1017>NehaSood ayearago
itisalreadysolvedusingaliasing.
Reply Share
cromateu 2yearsago
seemstobeasyyetcomplicated
Reply Share
allwynmascarenhas 2yearsago
itriedthesameexample..thisiswhatiget.someassistanceplease!
http://postimg.org/image/ntukt...
Reply Share
allwynmascarenhas 2yearsago
Igotlilconfusedinthelastexample.Isitthatonly1tableholdsboth
employeesandmanagersthenwhatisthemeaningofmanagerand
anothermanager.Alsothenamecolumniscommonforbothmanagers
andemployees?I'malsothinkingmaybesomethingwasleftout
somewhere..pleasecommentsomeone.Andgreatanswers,youare
addingsomuchvaluetoourlives!THANKS!
Reply Share
harami 3yearsago
brilliantdon
Reply Share
RAMAA ayearago
SELECTe1.employee_name
FROMemployeee1,employeee2
WHEREe1.employee_location=e2.employee_location
ANDe2.employee_name="Joe"
InthisSQLselfjoinexample,thequerydon'thaveanyformofJOIN
keyword,
isthis'sstillaJOIN??
whetheraquerymeantforjoinmusthaveJOINkeywordinitorit's
optional??
Reply Share
venkateshkannan>RAMAA 2monthsago
http://www.programmerinterview.com/index.php/databasesql/whatisaselfjoin/ 8/9
03/06/2016 SQL/Databases:Whatisaselfjoin?
venkateshkannan>RAMAA 2monthsago
IhavethesamedoubtasRAMAA.
Alsofortheemployeemanagerexample,isthebelowSQlsame
astheonementionedinthetutorial.
SELECTe1.Name,e2.Name
FROMEmployeee1
WHEREEmployeee1=Employeee2
ONe1.ManagerID=e2.EmployeeID
Pleasecomment.Thankyouforyourtime.
Reply Share
Subscribe d AddDisqustoyoursiteAddDisqusAdd
Privacy
WouldyouliketothankProgrammerInterview.comforbeingahelpfulfreeresource?Thenwhynottellafriendaboutus,orsimplyaddalink
tothispagefromyourwebpageusingtheHTMLbelow.
Linktothispage:
<ahref="http://www.programmerinterview.com/index.php/databasesql/whatisaselfjoin/">ProgrammerandSoftwareInterviewQuestionsandAnswersWhatisaselfjoin?</a>
Copyright2015|ProgrammerJobBoard|IndiaJobBoardforProgrammers|About WebsiteDesignedbyNayaPixel.com
http://www.programmerinterview.com/index.php/databasesql/whatisaselfjoin/ 9/9