12/23/2015
SQLSubqueriesw3resource
w3resource
SQLSubqueries
LastupdateonApril1120[Link](UTC/GMT+8hours)
Introduction
AsubqueryisaSQLquerynestedinsidealargerquery.
Asubquerymayoccurin:
ASELECTclause
AFROMclause
AWHEREclause
ThesubquerycanbenestedinsideaSELECT,INSERT,UPDATE,orDELETEstatementorinside
anothersubquery.
AsubqueryisusuallyaddedwithintheWHEREClauseofanotherSQLSELECTstatement.
Youcanusethecomparisonoperators,suchas>,<,or=.Thecomparisonoperatorcanalsobea
multiplerowoperator,suchasIN,ANY,orALL.
Asubquerycanbetreatedasaninnerquery,whichisaSQLqueryplacedasapartofanotherquery
calledasouterquery.
Theinnerqueryexecutesfirstbeforeitsparentquerysothattheresultsofinnerquerycanbepassedto
theouterquery.
Syntax:
Thesubquery(innerquery)executesoncebeforethemainquery(outerquery)executes.
Themainquery(outerquery)usethesubqueryresult.
SQLSubqueriesExample:
Inthissection,[Link]
followingtwotables'student'and'marks'withcommonfield'StudentID'.
[Link]
1/10
12/23/2015
SQLSubqueriesw3resource
studentmarks
Nowwewanttowriteaquerytoidentifyallstudentswhogetbettermarksthanthat
ofthestudentwho'sStudentIDis'V002',butwedonotknowthemarksof'V002'.
Tosolvetheproblem,[Link]
(storedinTotal_marksfield)of'V002'andasecondqueryidentifiesthestudents
whogetbettermarksthantheresultofthefirstquery.
Firstquery:
viewplain
01.
02.
03.
copytoclipboard
print
SELECT*
FROM`marks`
WHEREstudentid='V002';
Queryresult:
Theresultofthequeryis80.
Usingtheresultofthisquery,herewehavewrittenanotherquerytoidentifythe
[Link]:
Secondquery:
viewplain
01.
02.
03.
04.
copytoclipboard
print
[Link],[Link],b.total_marks
FROMstudenta,marksb
[Link]=[Link]
ANDb.total_marks>80;
Queryresult:
Abovetwoqueriesidentifiedstudentswhogetbetternumberthanthestudentwho's
StudentIDis'V002'(Abhay).
[Link]
[Link]
2/10
12/23/2015
SQLSubqueriesw3resource
subquery(alsocalledthe'innerquery')[Link]
followingcodeandqueryresult:
viewplain
01.
02.
03.
04.
05.
06.
copytoclipboard
print
[Link],[Link],b.total_marks
FROMstudenta,marksb
[Link]=[Link].total_marks>
(SELECTtotal_marks
FROMmarks
WHEREstudentid='V002');
Queryresult:
PictorialPresentationofSQLSubquery:
[Link]
3/10
12/23/2015
SQLSubqueriesw3resource
Subqueries:GeneralRules
AsubquerySELECTstatementisalmostsimilartotheSELECTstatementanditis
[Link]:
(SELECT[DISTINCT]subquery_select_argument
FROM{table_name|view_name}
{table_name|view_name}...
[WHEREsearch_conditions]
[GROUPBYaggregate_expression[,aggregate_expression]...]
[HAVINGsearch_conditions])
[Link]
4/10
12/23/2015
SQLSubqueriesw3resource
Subqueries:Guidelines
Therearesomeguidelinestoconsiderwhenusingsubqueries:
Asubquerymustbeenclosedinparentheses.
Asubquerymustbeplacedontherightsideofthecomparisonoperator.
Subqueriescannotmanipulatetheirresultsinternally,thereforeORDERBYclause
[Link]
SELECTstatement(outerquery)whichwillbelastclause.
Usesinglerowoperatorswithsinglerowsubqueries.
Ifasubquery(innerquery)returnsanullvaluetotheouterquery,theouterquery
willnotreturnanyrowswhenusingcertaincomparisonoperatorsinaWHERE
clause.
TypeofSubqueries
Singlerowsubquery:Returnszerooronerow.
Multiplerowsubquery:Returnsoneormorerows.
Multiplecolumnsubquery:Returnsoneormorecolumns.
Correlatedsubqueries:ReferenceoneormorecolumnsintheouterSQL
[Link]
isrelatedtotheouterSQLstatement.
Nestedsubqueries:Subqueriesareplacedwithinanothersubqueries.
[Link]
abovetypeofsubqueriesyoucanusesubqueryinsideINSERT,UPDATEand
[Link]:
SubquerieswithINSERTstatement
[Link]
exampleofsubqueriesusingINSERTstatement.
INSERTINTOtable_name[(column1[,column2])]
SELECT[*|column1[,column2]
FROMtable1[,table2]
[WHEREVALUEOPERATOR]
Ifwewanttoinsertthoseordersfrom'orders'tablewhichhavethe
advance_amount2000or5000into'neworder'tablethefollowingSQLcanbeused:
[Link]
5/10
12/23/2015
SQLSubqueriesw3resource
Sampletable:orders
ORD_NUMORD_AMOUNTADVANCE_AMOUNTORD_DATECUST_CODEAGENT_CODEORD_DESCRIPTION
2001143500200015AUG08C00002A008
200122250040016SEP08C00003A004
20011850010020JUL08C00023A006
200119400070016SEP08C00007A010
200121150060023SEP08C00008A004
200130250040030JUL08C00025A011
2001344200180025SEP08C00004A005
viewplain
01.
02.
03.
copytoclipboard
print
INSERTINTOneworder
SELECT*FROMorders
WHEREadvance_amountin(2000,5000);
Output
ToseemoredetailsofsubqueriesusingINSERTstatementclickhere.
SubquerieswithUPDATEstatement
InanUPDATEstatement,youcansetnewcolumnvalueequaltotheresult
[Link]
subqueriesusingUPDATEstatement.
UPDATEtableSETcolumn_name=new_value
[WHEREOPERATOR[VALUE]
(SELECTCOLUMN_NAME
FROMTABLE_NAME)
[WHERE)]
Ifwewanttoupdatethoseord_datein'neworder'tablewith'15JAN10'whichhave
thedifferenceoford_amountandadvance_amountislessthantheminimum
ord_amountof'orders'tablethefollowingSQLcanbeused:
Sampletable:neworder
[Link]
6/10
12/23/2015
SQLSubqueriesw3resource
ORD_NUMORD_AMOUNTADVANCE_AMOUNTORD_DATECUST_CODEAGENT_CODEORD_DESCRIPTION
2001143500200015AUG08C00002A008
200122250040016SEP08C00003A004
20011850010020JUL08C00023A006
200119400070016SEP08C00007A010
200121150060023SEP08C00008A004
200130250040030JUL08C00025A011
2001344200180025SEP08C00004A005
viewplain
01.
02.
03.
04.
copytoclipboard
print
UPDATEneworder
SETord_date='15JAN10'
WHEREord_amountadvance_amount<
(SELECTMIN(ord_amount)FROMorders);
ToseemoredetailsofsubqueriesusingUPDATEstatementclickhere.
SubquerieswithDELETEstatement
[Link]
exampleofsubqueriesusingDELETEstatement.
DELETEFROMTABLE_NAME
[WHEREOPERATOR[VALUE]
(SELECTCOLUMN_NAME
FROMTABLE_NAME)
[WHERE)]
Ifwewanttodeletethoseordersfrom'neworder'tablewhichadvance_amountare
lessthanthemaximumadvance_amountof'orders'table,thefollowingSQLcanbe
used:
Sampletable:neworder
[Link]
7/10
12/23/2015
SQLSubqueriesw3resource
ORD_NUMORD_AMOUNTADVANCE_AMOUNTORD_DATECUST_CODEAGENT_CODEORD_DESCRIPTION
2001143500200015AUG08C00002A008
200122250040016SEP08C00003A004
20011850010020JUL08C00023A006
200119400070016SEP08C00007A010
200121150060023SEP08C00008A004
200130250040030JUL08C00025A011
2001344200180025SEP08C00004A005
viewplain
01.
02.
03.
copytoclipboard
print
DELETEFROMneworder
WHEREadvance_amount<
(SELECTMAX(advance_amount)FROMorders);
ToseemoredetailsofsubqueriesusingDELETEstatementclickhere.
Keypointstoremember
Slides
Slide1
WhatNext?
SingleRowSubqueries
MultipleRowandColumnSubqueries
Corelatedsubqueriesusingaliases
Nestedsubqueries
Note:OutputsofthesaidSQLstatementshownhereistakenbyusingOracle
Database10gExpressEdition.
<<Previous Next>>
Lookingforsomeothertutorial?
Searchw3resourcetutorials
[Link]
Search
8/10
12/23/2015
SQLSubqueriesw3resource
6Comments
w3resource
Recommend 8
Share
Login
SortbyNewest
Jointhediscussion
Rasmus 5monthsago
Isthereaniceeasywaytoechomysqlresultinphpandgetsuchplaintextoutput?It
wouldbenicetoskipallhtmlcodingforshowingtheresult.
Reply Share
w3resource
Mod >Rasmus
5monthsago
YoumaysaveMySQLresultintextfileusingteecommandandthenincludethat
fileusingPHP.
Reply Share
Kalyan 2yearsago
UPDATEneworder
SETord_date='15JAN10'
WHEREord_amountadvance_amount<
(SELECTMIN(advance_amount)FROMorders)
Asperyourscenario:
INtheabovequeryitsnotMIN(Advance_amount)itshouldbeMin(Ord_amount)
Reply Share
w3resource
Mod >Kalyan
2yearsago
[Link]
Reply Share
Designer_Girl 3yearsago
WhenItrytouseyourexample...itneverworks.
>Subqueryreturnedmorethan1value.
Obviously,[Link]
suggestedIuseMIN()inmysubquery,but
thatchangestheentirethingintosomethingIdon'twant.
[Link],[Link],b.total_marks
FROMstudenta,marksb
[Link]
9/10
12/23/2015
SQLSubqueriesw3resource
FROMstudenta,marksb
[Link]=[Link].total_marks>
(SELECTtotal_marks
FROMmarks
WHEREstudentid='V002')
4
Reply Share
w3resource
Mod >Designer_Girl
3yearsago
Whatisyourquery?
10
Subscribe
Reply Share
AddDisqustoyoursiteAddDisqusAdd
Privacy
w3resource201115
Privacypolicy
About
Contact
Feedback
Advertise
[Link]
10/10