Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Home
SQLForTesters~SoftwareTesting
SeleniumTraining
QTPTraining
Projects
SeleniumTool
VBScriptforUFT
SoftwareTesting
ManualTesting,HPUFT,VBScriptforUFT,QualityCenter,
LoadRunner,CandSQLbyGCReddy(919247837478)
ManualTesting
QTP
SeleniumOnlineTraining
SQL
CLanguage
Java
OracleFAQ
Resumes
UFTGuide
UFTVideos
SoftwareTestingFAQ
Atlassian HipChat
Real-Time Team Collaboration. Safe, Secure, Sign Up in 60 sec.
SeleniumOnlineTraining
QTPOnlineTraining
YouTubeChannel
Search
SQLForTesters
9:26PM
G.C.REDDY
2COMMENTS
Follow
SQLKnowledgeForSoftwareTesters
1.1k
G.C.Reddy
YouTube
TestingQuestionBank
ManualTestingVideos
BasicsoftheSELECTStatement
UFTVideos
Inarelationaldatabase,dataisstoredintables.Anexampletablewould
2K
relateSocialSecurityNumber,Name,andAddress:
EmployeeAddressTable
SSN
City
State
512687458 Joe
Smith
83FirstStreet Howard
758420012 Mary
Scott
Ohio
102254896 Sam
Jones
33ElmSt.
876512563 Sarah
Ackerman 440U.S.110
Paris
NewYork
Upton
Michigan
Now,let'ssayyouwanttoseetheaddressofeachemployee.UsetheSELECT
statement,likeso:
SELECTFirstName,LastName,Address,City,State
FROMEmployeeAddressTable
Thefollowingistheresultsofyourqueryofthedatabase:
FirstName LastName Address
City
State
Joe
Smith
83FirstStreet Howard
Ohio
Mary
Scott
Sam
Jones
33ElmSt.
Paris
NewYork
Sarah
Ackerman
440U.S.110
Upton
Michigan
Togetallcolumnsofatablewithouttypingallcolumnnames,use:
SELECT*FROMTableName
Note:Eachdatabasemanagementsystem(DBMS)hasdifferentmethodsfor
loggingintothedatabaseandenteringSQLcommands.
SQLQueries
ConditionalSelection
SQLDatabaseTutorial TofurtherdiscusstheSELECTstatement,let'slookatanewexampletable:
SQLTraining
JointoGCReddyGroup
Email:
Subscribe
Visitthisgroup
POPULARPOSTS
VBScriptforQTP
EmployeeStatisticsTable
WindowsSQLServer
SQLSoftware
ToolforSQL
BLOGARCHIVE
2015(44)
2014(292)
EmployeeIDNo
Salary
Benefits
Position
010
75000
15000
Manager
105
65000
15000
Manager
November(5)
152
60000
15000
Manager
October(4)
215
60000
12500
Manager
244
50000
12000
Staff
http://www.gcreddy.com/2014/07/sqlfortesters.html
December(69)
September(41)
1/11
1/22/2015
SQLForTesters~SoftwareTesting
QTPGuide
SQLandPl/SQLInterview
Questions
QTPScripting
300
45000
10000
Staff
335
40000
10000
Staff
400
32000
7500
EntryLevel
441
28000
7500
EntryLevel
manualtestinginterview
questions
SQLInterviewQuestions
QTPBasicFeatures
ManualTestingInterview
Questions2
a)RelationalOperators
TherearesixRelationalOperatorsinSQL,andafterintroducingthem,we'll
seehowthey'reused:
OracleInterviewQuestions
andAnswers
AnoverviewonTest
Automation
..
ANALYTICS
Equal
<or!=
NotEqual
<
LessThan
>
GreaterThan
<=
LessThanorEqualTo
>=
GreaterThanorEqual
To
TheWHEREclauseisusedtospecifythatonlycertainrowsofthetableare
displayed,basedonthecriteriadescribedinthatWHEREclause.
IfyouwantedtoseetheEMPLOYEEIDNO'softhosemakingatorover
August(9)
July(35)
Aadharcardcenters
inChattisgarh
AadharCardCenters
inBihar
AadharCardCenters
inUttarPradesh
AadharCardCenters
inNelloreDistrict
AadharCardCenters
inNalgonda
AadharCardCenters
inKrishnaDistrict
AadharCardCenters
inKhammam
AadharCardCenters
inKarimnagar
AadharCardCenters
inGuntur
$50,000,usethefollowing:
AadharCardCenters
inEastGodavari
SELECTEMPLOYEEIDNOFROMEMPLOYEESTATISTICSTABLEWHERESALARY
AadharCardCenters
inCuddapah
>=50000
Noticethatthe>=(greaterthanorequalto)signisused,aswewantedto
seethosewhomadegreaterthan$50,000,orequalto$50,000,listed
together.Thisdisplays:
EMPLOYEEIDNO
010
AadharCardCenters
inChittoor
AadharCardCenters
inAnantapur
UseCaseTemplate
StaticTesting
105
152
215
244
Softwaretesting
Guide
SeleniumTraining
TheWHEREdescription,SALARY>=50000,isknownasacondition(an
operationwhichevaluatestoTrueorFalse).Thesamecanbedonefortext
SoftwareTestPlan
Template
columns:
BRSDocument
SELECTEMPLOYEEIDNO
SeleniumWebDriver
FROMEMPLOYEESTATISTICSTABLE
WHEREPOSITION='Manager'
ThisdisplaystheIDNumbersofallManagers.
MoreComplexConditions:CompoundConditions/Logical
Operators
SeleniumTutorial
SoftwareTesting
Interview
Questions
InsuranceDomain
Knowledge
thatrow'sdatasatisfiesALLconditionslisted(i.e.allconditionsholdtrue).
SQLInterview
Questionsand
Answers
Forexample,todisplayallstaffmakingover$40,000,use:
SQLForTesters
TheANDoperatorjoinstwoormoreconditions,anddisplaysarowonlyif
SELECTEMPLOYEEIDNO
FROMEMPLOYEESTATISTICSTABLE
TestingCertification
Questions
WHERESALARY>40000ANDPOSITION='Staff'
TheORoperatorjoinstwoormoreconditions,butreturnsarowifANYofthe
conditionslistedholdtrue.
Configuration
Management
WebTestingTutorial
Toseeallthosewhomakelessthan$40,000orhavelessthan$10,000in
benefits,listedtogether,usethefollowingquery:
SELECTEMPLOYEEIDNO
http://www.gcreddy.com/2014/07/sqlfortesters.html
PrototypeModel
AgileDevelopment
2/11
1/22/2015
SQLForTesters~SoftwareTesting
Model
FROMEMPLOYEESTATISTICSTABLE
WHERESALARY<40000ORBENEFITS<10000
TestDesign
Techniques
ANDandORcanbecombined,forexample:
DatabaseTesting
SELECTEMPLOYEEIDNO
FROMEMPLOYEESTATISTICSTABLE
Software
DevelopmentLife
Cycle
WHEREPOSITION='Manager'ANDSALARY>60000ORBENEFITS>12000
First,SQLfindstherowswherethesalaryisgreaterthan$60,000andthe
SoftwareTesting
Standards
positioncolumnisequaltoManager,thentakingthisnewlistofrows,SQL
thenseesifanyoftheserowssatisfiesthepreviousANDconditionorthe
AnOverviewon
ComputerSoftware
conditionthattheBenefitscolumnisgreaterthan$12,000.Subsequently,SQL
onlydisplaysthissecondnewlistofrows,keepinginmindthatanyonewith
Benefitsover$12,000willbeincludedastheORoperatorincludesarowif
June(14)
eitherresultingconditionisTrue.AlsonotethattheANDoperationisdone
first.
May(7)
IN&BETWEEN
April(24)
AneasiermethodofusingcompoundconditionsusesINorBETWEEN.
March(18)
Forexample,ifyouwantedtolistallmanagersandstaff:
February(15)
January(51)
SELECTEMPLOYEEIDNO
FROMEMPLOYEESTATISTICSTABLE
WHEREPOSITIONIN('Manager','Staff')
2013(730)
2012(143)
ortolistthosemakinggreaterthanorequalto$30,000,butlessthanor
equalto$50,000,use:
2011(54)
2010(138)
SELECTEMPLOYEEIDNO
FROMEMPLOYEESTATISTICSTABLE
WHERESALARYBETWEEN30000AND50000
...
Tolisteveryonenotinthisrange,try:
SELECTEMPLOYEEIDNO
FROMEMPLOYEESTATISTICSTABLE
WHERESALARYNOTBETWEEN30000AND50000
Similarly,NOTINlistsallrowsexcludedfromtheINlist.
Additionally,NOT'scanbethrowninwithAND's&OR's,exceptthatNOTisa
unaryoperator(evaluatesonecondition,reversingitsvalue,whereas,AND's
&OR'sevaluatetwoconditions),andthatallNOT'sareperformedbeforeany
AND'sorOR's.
SQLOrderofLogicalOperations(eachoperatesfromlefttoright)
1. NOT
2. AND
3. OR
UsingLike
LookattheEmployeeStatisticsTable,andsayyouwantedtoseeallpeople
whoselastnamesstartedwith"S"try:
SELECTEMPLOYEEIDNO
FROMEMPLOYEEADDRESSTABLE
WHERELASTNAMELIKE'S%'
http://www.gcreddy.com/2014/07/sqlfortesters.html
3/11
1/22/2015
SQLForTesters~SoftwareTesting
Thepercentsign(%)isusedtorepresentanypossiblecharacter(number,
letter,orpunctuation)orsetofcharactersthatmightappearafterthe"S".
TofindthosepeoplewithLastName'sendingin"S",use'%S',orifyou
wantedthe"S"inthemiddleoftheword,try'%S%'.
The'%'canbeusedforanycharactersinthesamepositionrelativetothe
givencharacters.
Joins
Gooddatabasedesignsuggeststhateachtablelistsdataonlyaboutasingle
entity,anddetailedinformationcanbeobtainedinarelationaldatabase,by
usingadditionaltables,andbyusingajoin.
First,takealookattheseexampletables:
AntiqueOwners
Jones
Bill
02
Smith
Bob
15
Lawson
Patricia
21
Akins
Jane
50
Fowler
Sam
Orders
OwnerID ItemDesired
02
Table
02
Desk
21
Chair
15
Mirror
Antiques
50
Bed
02
15
Table
15
02
Chair
21
50
Mirror
50
01
Desk
01
21
Cabinet
02
21
CoffeeTable
15
50
Chair
01
15
JewelryBox
02
21
Pottery
21
02
Bookcase
50
01
PlantStand
Keys
First,let'sdiscusstheconceptofkeys.
Aprimarykeyisacolumnorsetofcolumnsthatuniquelyidentifiestherest
ofthedatainanygivenrow.Forexample,intheAntiqueOwnerstable,the
OwnerIDcolumnuniquelyidentifiesthatrow.Thismeanstwothings:notwo
rowscanhavethesameOwnerID,and,eveniftwoownershavethesame
http://www.gcreddy.com/2014/07/sqlfortesters.html
4/11
1/22/2015
SQLForTesters~SoftwareTesting
firstandlastnames,theOwnerIDcolumnensuresthatthetwoownerswill
notbeconfusedwitheachother,becausetheuniqueOwnerIDcolumnwillbe
usedthroughoutthedatabasetotracktheowners,ratherthanthenames.
Aforeignkeyisacolumninatablewherethatcolumnisaprimarykeyof
anothertable,whichmeansthatanydatainaforeignkeycolumnmusthave
correspondingdataintheothertablewherethatcolumnistheprimarykey.
InDBMSspeak,thiscorrespondenceisknownasreferentialintegrity.For
example,intheAntiquestable,boththeBuyerIDandSellerIDareforeign
keystotheprimarykeyoftheAntiqueOwnerstable(OwnerIDforpurposes
ofargument,onehastobeanAntiqueOwnerbeforeonecanbuyorsellany
items),as,inbothtables,theIDrowsareusedtoidentifytheownersor
buyersandsellers,andthattheOwnerIDistheprimarykeyofthe
AntiqueOwnerstable.Inotherwords,allofthis"ID"dataisusedtoreferto
theowners,buyers,orsellersofantiques,themselves,withouthavingtouse
theactualnames.
PerformingaJoin
Thepurposeofthesekeysissothatdatacanberelatedacrosstables,
withouthavingtorepeatdataineverytablethisisthepowerofrelational
databases.
Forexample,youcanfindthenamesofthosewhoboughtachairwithout
havingtolistthefullnameofthebuyerintheAntiquestable...youcangetthe
namebyrelatingthosewhoboughtachairwiththenamesinthe
AntiqueOwnerstablethroughtheuseoftheOwnerID,whichrelatesthedata
inthetwotables.
Tofindthenamesofthosewhoboughtachair,usethefollowingquery:
SELECTOWNERLASTNAME,OWNERFIRSTNAME
FROMANTIQUEOWNERS,ANTIQUES
WHEREBUYERID=OWNERIDANDITEM='Chair'
Notethefollowingaboutthisquery...noticethatbothtablesinvolvedinthe
relationarelistedintheFROMclauseofthestatement.
IntheWHEREclause,firstnoticethattheITEM='Chair'partrestrictsthe
listingtothosewhohavebought(andinthisexample,therebyown)achair.
Secondly,noticehowtheIDcolumnsarerelatedfromonetabletothenext
byuseoftheBUYERID=OWNERIDclause.OnlywhereID'smatchacross
tablesandtheitempurchasedisachair(becauseoftheAND),willthenames
fromtheAntiqueOwnerstablebelisted.Becausethejoiningconditionusedan
equalsign,thisjoiniscalledanequijoin.Theresultofthisqueryistwo
names:Smith,Bob&Fowler,Sam.
Dotnotationreferstoprefixingthetablenamestocolumnnames,toavoid
ambiguity,asfollows:
SELECTANTIQUEOWNERS.OWNERLASTNAME,
ANTIQUEOWNERS.OWNERFIRSTNAME
FROMANTIQUEOWNERS,ANTIQUES
WHEREANTIQUES.BUYERID=ANTIQUEOWNERS.OWNERIDAND
ANTIQUES.ITEM='Chair'
Asthecolumnnamesaredifferentineachtable,however,thiswasn't
necessary.
DISTINCTandEliminatingDuplicates
Let'ssaythatyouwanttolisttheIDandnamesofonlythosepeoplewho
havesoldanantique.
Obviously,youwantalistwhereeachsellerisonlylistedonceyoudon't
wanttoknowhowmanyantiquesapersonsold,justthefactthatthisperson
soldone(forcounts,seetheAggregateFunctionsectionbelow).
http://www.gcreddy.com/2014/07/sqlfortesters.html
5/11
1/22/2015
SQLForTesters~SoftwareTesting
ThismeansthatyouwillneedtotellSQLtoeliminateduplicatesalesrows,
andjustlisteachpersononlyonce.
Todothis,usetheDISTINCTkeyword.
First,wewillneedanequijointotheAntiqueOwnerstabletogetthedetail
dataoftheperson'sLastNameandFirstName.However,keepinmindthat
sincetheSellerIDcolumnintheAntiquestableisaforeignkeytothe
AntiqueOwnerstable,asellerwillonlybelistedifthereisarowinthe
AntiqueOwnerstablelistingtheIDandnames.Wealsowanttoeliminate
multipleoccurrencesoftheSellerIDinourlisting,soweuseDISTINCTonthe
columnwheretherepeatsmayoccur(however,itisgenerallynotnecessary
tostrictlyputtheDistinctinfrontofthecolumnname).
Tothrowinonemoretwist,wewillalsowantthelistalphabetizedby
LastName,thenby
FirstName(onaLastNametie).Thus,wewillusetheORDERBYclause:
SELECTDISTINCTSELLERID,OWNERLASTNAME,OWNERFIRSTNAME
FROMANTIQUES,ANTIQUEOWNERS
WHERESELLERID=OWNERID
ORDERBYOWNERLASTNAME,OWNERFIRSTNAME
Inthisexample,sinceeveryonehassoldanitem,wewillgetalistingofallof
theowners,inalphabeticalorderbylastname.
Forfuturereference(andincaseanyoneasks),thistypeofjoinisconsidered
tobeinthecategoryofinnerjoins.
Aliases&In/Subqueries
Inthissection,wewilltalkaboutAliases,Inandtheuseofsubqueries,and
howthesecanbeusedina3tableexample.
First,lookatthisquerywhichprintsthelastnameofthoseownerswhohave
placedanorderandwhattheorderis,onlylistingthoseorderswhichcanbe
filled(thatis,thereisabuyerwhoownsthatordereditem):
SELECTOWN.OWNERLASTNAMELastName,ORD.ITEMDESIREDItemOrdered
FROMORDERSORD,ANTIQUEOWNERSOWN
WHEREORD.OWNERID=OWN.OWNERID
ANDORD.ITEMDESIREDIN
(SELECTITEM
FROMANTIQUES)
Thisgives:
LastNameItemOrdered
SmithTable
SmithDesk
AkinsChair
LawsonMirror
MiscellaneousSQLStatements
AggregateFunctions
Fiveimportantaggregatefunctions:SUM,AVG,MAX,MIN,andCOUNT.
Aggregatefunctionssummarizetheresultsofaquery,ratherthanlistingall
oftherows.
SUM()givesthetotalofalltherows,satisfyinganyconditions,ofthe
givencolumn,wherethegivencolumnisnumeric.
AVG()givestheaverageofthegivencolumn.
MAX()givesthelargestfigureinthegivencolumn.
MIN()givesthesmallestfigureinthegivencolumn.
COUNT(*)givesthenumberofrowssatisfyingtheconditions.
Lookingatthetablesatthetopofthedocument,let'slookatthree
examples:
SELECTSUM(SALARY),AVG(SALARY)
http://www.gcreddy.com/2014/07/sqlfortesters.html
6/11
1/22/2015
SQLForTesters~SoftwareTesting
FROMEMPLOYEESTATISTICSTABLE
Thisqueryshowsthetotalofallsalariesinthetable,andtheaveragesalary
ofalloftheentriesinthetable.
SELECTMIN(BENEFITS)
FROMEMPLOYEESTATISTICSTABLE
WHEREPOSITION='Manager'
ThisquerygivesthesmallestfigureoftheBenefitscolumn,oftheemployees
whoareManagers,whichis12500.
SELECTCOUNT(*)
FROMEMPLOYEESTATISTICSTABLE
WHEREPOSITION='Staff'
ThisquerytellsyouhowmanyemployeeshaveStaffstatus(3).
Views
InSQL,youmight(checkyourDBA)haveaccesstocreateviewsforyourself.
Whataviewdoesistoallowyoutoassigntheresultsofaquerytoanew,
personaltable,thatyoucanuseinotherqueries,wherethisnewtableis
giventheviewnameinyourFROMclause.
Whenyouaccessaview,thequerythatisdefinedinyourviewcreation
statementisperformed(generally),andtheresultsofthatquerylookjust
likeanothertableinthequerythatyouwroteinvokingtheview.
Forexample,tocreateaview:
CREATEVIEWANTVIEWASSELECTITEMDESIREDFROMORDERS
Now,writeaqueryusingthisviewasatable,wherethetableisjustalisting
ofallItemsDesiredfromtheOrderstable:
SELECTSELLERID
FROMANTIQUES,ANTVIEW
WHEREITEMDESIRED=ITEM
ThisqueryshowsallSellerID'sfromtheAntiquestablewheretheIteminthat
tablehappenstoappearintheAntviewview,whichisjustalloftheItems
DesiredintheOrderstable.
ThelistingisgeneratedbygoingthroughtheAntiqueItemsonebyoneuntil
there'samatchwiththeAntviewview.Viewscanbeusedtorestrictdatabase
access,aswellas,inthiscase,simplifyacomplexquery.
CreatingNewTables
Alltableswithinadatabasemustbecreatedatsomepointintime...let'ssee
howwewouldcreatetheOrderstable:
CREATETABLEORDERS
(OWNERIDINTEGERNOTNULL,
ITEMDESIREDCHAR(40)NOTNULL)
ThisstatementgivesthetablenameandtellstheDBMSabouteachcolumnin
thetable.
Pleasenotethatthisstatementusesgenericdatatypes,andthatthedata
typesmightbedifferent,dependingonwhatDBMSyouareusing.Asusual,
checklocallistings.Somecommongenericdatatypesare:
Char(x)Acolumnofcharacters,wherexisanumberdesignatingthe
maximumnumberofcharactersallowed(maximumlength)inthe
column.
IntegerAcolumnofwholenumbers,positiveornegative.
Decimal(x,y)Acolumnofdecimalnumbers,wherexisthemaximum
lengthindigitsofthedecimalnumbersinthiscolumn,andyisthe
http://www.gcreddy.com/2014/07/sqlfortesters.html
7/11
1/22/2015
SQLForTesters~SoftwareTesting
maximumnumberofdigitsallowedafterthedecimalpoint.The
maximum(4,2)numberwouldbe99.99.
DateAdatecolumninaDBMSspecificformat.
LogicalAcolumnthatcanholdonlytwovalues:TRUEorFALSE.
Oneothernote,theNOTNULLmeansthatthecolumnmusthaveavaluein
eachrow.IfNULLwasused,thatcolumnmaybeleftemptyinagivenrow.
AlteringTables
Let'saddacolumntotheAntiquestabletoallowtheentryofthepriceofa
givenItem(Parenthesesoptional):
ALTERTABLEANTIQUESADD(PRICEDECIMAL(8,2)NULL)
Thedataforthisnewcolumncanbeupdatedorinsertedasshownlater.
AddingData
Toinsertrowsintoatable,dothefollowing:
INSERTINTOANTIQUESVALUES(21,01,'Ottoman',200.00)
Thisinsertsthedataintothetable,asanewrow,columnbycolumn,inthe
predefinedorder.
Instead,let'schangetheorderandleavePriceblank:
INSERTINTOANTIQUES(BUYERID,SELLERID,ITEM)
VALUES(01,21,'Ottoman')
UpdatingData
Let'supdateaPriceintoarowthatdoesn'thaveapricelistedyet:
UPDATEANTIQUESSETPRICE=500.00WHEREITEM='Chair'
ThissetsallChair'sPricesto500.00.Asshownabove,moreWHERE
conditionals,usingAND,mustbeusedtolimittheupdatingtomorespecific
rows.Also,additionalcolumnsmaybesetbyseparatingequalstatements
withcommas.
DeletingData
Let'sdeletethisnewrowbackoutofthedatabase:
DELETEFROMANTIQUES
WHEREITEM='Ottoman'
Butifthereisanotherrowthatcontains'Ottoman',thatrowwillbedeleted
also.Let'sdeleteallrows(one,inthiscase)thatcontainthespecificdatawe
addedbefore:
DELETEFROMANTIQUES
WHEREITEM='Ottoman'ANDBUYERID=01ANDSELLERID=21
MiscellaneousTopics
Indexes
IndexesallowaDBMStoaccessdataquicker(pleasenote:thisfeatureis
nonstandard/notavailableonallsystems).Thesystemcreatesthisinternal
datastructure(theindex)whichcausesselectionofrows,whentheselection
isbasedonindexedcolumns,tooccurfaster.
ThisindextellstheDBMSwhereacertainrowisinthetablegivenan
indexedcolumnvalue,muchlikeabookindextellsyouwhatpageagiven
wordappears.
Let'screateanindexfortheOwnerIDintheAntiqueOwnerstable:
CREATEINDEXOID_IDXONANTIQUEOWNERS(OWNERID)
http://www.gcreddy.com/2014/07/sqlfortesters.html
8/11
1/22/2015
SQLForTesters~SoftwareTesting
Nowonthenames:
CREATEINDEXNAME_IDXONANTIQUEOWNERS(OWNERLASTNAME,
OWNERFIRSTNAME)
Togetridofanindex,dropit:
DROPINDEXOID_IDX
Bytheway,youcanalso"drop"atable,aswell(careful!thatmeansthat
yourtableisdeleted).Inthesecondexample,theindexiskeptonthetwo
columns,aggregatedtogetherstrangebehaviormightoccurinthis
situation...checkthemanualbeforeperformingsuchanoperation.
SomeDBMS'sdonotenforceprimarykeysinotherwords,theuniquenessof
acolumnisnotenforcedautomatically.Whatthatmeansis,if,forexample,I
triedtoinsertanotherrowintotheAntiqueOwnerstablewithanOwnerIDof
02,somesystemswillallowmetodothat,eventhoughwedonot,asthat
columnissupposedtobeuniquetothattable(everyrowvalueissupposedto
bedifferent).Onewaytogetaroundthatistocreateauniqueindexonthe
columnthatwewanttobeaprimarykey,toforcethesystemtoenforce
prohibitionofduplicates:
CREATEUNIQUEINDEXOID_IDXONANTIQUEOWNERS(OWNERID)
GROUPBY&HAVING
OnespecialuseofGROUPBYistoassociateanaggregatefunction(especially
COUNTcountingthenumberofrowsineachgroup)withgroupsofrows.
First,assumethattheAntiquestablehasthePricecolumn,andeachrowhas
avalueforthatcolumn.Wewanttoseethepriceofthemostexpensiveitem
boughtbyeachowner.WehavetotellSQLtogroupeachowner'spurchases,
andtellusthemaximumpurchaseprice:
SELECTBUYERID,MAX(PRICE)
FROMANTIQUES
GROUPBYBUYERID
Now,sayweonlywanttoseethemaximumpurchasepriceifthepurchaseis
over$1000,soweusetheHAVINGclause:
SELECTBUYERID,MAX(PRICE)
FROMANTIQUES
GROUPBYBUYERID
HAVINGPRICE>1000
MoreSubqueries
Anothercommonusageofsubqueriesinvolvestheuseofoperatorstoallowa
WhereconditiontoincludetheSelectoutputofasubquery.
First,listthebuyerswhopurchasedanexpensiveitem(thePriceoftheitem
is$100greaterthantheaveragepriceofallitemspurchased):
SELECTBUYERID
FROMANTIQUES
WHEREPRICE>
(SELECTAVG(PRICE)+100
FROMANTIQUES)
ThesubquerycalculatestheaveragePrice,plus$100,andusingthatfigure,
anOwnerIDisprintedforeveryitemcostingoverthatfigure.Onecoulduse
DISTINCTBUYERID,toeliminateduplicates.
ListtheLastNamesofthoseintheAntiqueOwnerstable,ONLYiftheyhave
boughtanitem:
SELECTOWNERLASTNAME
FROMANTIQUEOWNERS
WHEREOWNERIDIN
(SELECTDISTINCTBUYERID
FROMANTIQUES)
http://www.gcreddy.com/2014/07/sqlfortesters.html
9/11
1/22/2015
SQLForTesters~SoftwareTesting
Thesubqueryreturnsalistofbuyers,andtheLastNameisprintedforan
AntiqueOwnerifandonlyiftheOwner'sIDappearsinthesubquerylist
(sometimescalledacandidatelist).Note:onsomeDBMS's,equalscanbe
usedinsteadofIN,butforclarity'ssake,sinceasetisreturnedfromthe
subquery,INisthebetterchoice.
ForanUpdateexample,weknowthatthegentlemanwhoboughtthe
bookcasehasthewrongFirstNameinthedatabase...itshouldbeJohn:
UPDATEANTIQUEOWNERS
SETOWNERFIRSTNAME='John'
WHEREOWNERID=
(SELECTBUYERID
FROMANTIQUES
WHEREITEM='Bookcase')
First,thesubqueryfindstheBuyerIDfortheperson(s)whoboughtthe
Bookcase,thentheouterqueryupdateshisFirstName.
Rememberthisruleaboutsubqueries:
whenyouhaveasubqueryaspartofaWHEREcondition,theSelectclausein
thesubquerymusthavecolumnsthatmatchinnumberandtypetothosein
theWhereclauseoftheouterquery.Inotherwords,ifyouhave"WHERE
ColumnName=(SELECT...)",theSelectmusthaveonlyonecolumninit,to
matchtheColumnNameintheouterWhereclause,andtheymustmatchin
type(bothbeingintegers,bothbeingcharacterstrings,etc.).
EXISTS&ALL
EXISTSusesasubqueryasacondition,wheretheconditionisTrueifthesub
queryreturnsanyrows,andFalseifthesubquerydoesnotreturnanyrows
thisisanonintuitivefeaturewithfewuniqueuses.However,ifaprospective
customerwantedtoseethelistofOwnersonlyiftheshopdealtinChairs,
try:
SELECTOWNERFIRSTNAME,OWNERLASTNAME
FROMANTIQUEOWNERS
WHEREEXISTS
(SELECT*
FROMANTIQUES
WHEREITEM='Chair')
IfthereareanyChairsintheAntiquescolumn,thesubquerywouldreturna
roworrows,makingtheEXISTSclausetrue,causingSQLtolisttheAntique
Owners.IftherehadbeennoChairs,norowswouldhavebeenreturnedby
theoutsidequery.
ALLisanotherunusualfeature,asALLqueriescanusuallybedonewith
different,andpossiblysimplermethodslet'stakealookatanexample
query:
SELECTBUYERID,ITEM
FROMANTIQUES
WHEREPRICE>=ALL
(SELECTPRICE
FROMANTIQUES)
Thiswillreturnthelargestpriceditem(ormorethanoneitemifthereisa
tie),anditsbuyer.ThesubqueryreturnsalistofallPricesintheAntiques
table,andtheouterquerygoesthrougheachrowoftheAntiquestable,andif
itsPriceisgreaterthanorequaltoevery(orALL)Pricesinthelist,itis
listed,givingthehighestpricedItem.Thereason"="mustbeusedisthatthe
highestpriceditemwillbeequaltothehighestpriceonthelist,becausethis
ItemisinthePricelist.
RelatePosts:
SQLQueriesExamples
http://www.gcreddy.com/2014/07/sqlfortesters.html
10/11
1/22/2015
SQLForTesters~SoftwareTesting
SQLInterviewQuestions
SQLGuide
DatabaseTestingInterviewQuestions
Postedin:SQLBasics,sqlcommands,SQLInterviewQuestions,SQLQueries,SQLQueriesandSub
Queries,SQLSelectstatement
NewerPost
Home
OlderPost
2comments:
Anonymous says:
July10,2014at2:39AM
Verynicefortesters
Reply
Anonymous says:
July11,2014at4:52AM
GoodexplanationonSQL,youprovidesomeDatabaseTestingExamples.
Reply
PostaComment
Enteryourcomment...
Commentas:
Publish
GoogleAccount
Preview
Linkstothispost
CreateaLink
Copyright2011SoftwareTesting|PoweredbyBlogger
http://www.gcreddy.com/2014/07/sqlfortesters.html
11/11