0% found this document useful (0 votes)
209 views

SQL Subqueries - W3resource

This document discusses SQL subqueries, including: - A subquery is a SQL query nested inside a larger query that can be used in the SELECT, FROM, and WHERE clauses. - Subqueries execute first before the outer query and the outer query uses the subquery results. - Examples demonstrate identifying students with better marks than a student with ID "V002" using a subquery in the WHERE clause. - General rules and guidelines for subqueries are provided.

Uploaded by

Anonymous 293DQY
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
209 views

SQL Subqueries - W3resource

This document discusses SQL subqueries, including: - A subquery is a SQL query nested inside a larger query that can be used in the SELECT, FROM, and WHERE clauses. - Subqueries execute first before the outer query and the outer query uses the subquery results. - Examples demonstrate identifying students with better marks than a student with ID "V002" using a subquery in the WHERE clause. - General rules and guidelines for subqueries are provided.

Uploaded by

Anonymous 293DQY
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

12/23/2015

SQLSubqueriesw3resource

w3resource

SQLSubqueries
LastupdateonApril11201513:05:25(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,youwilllearntherequirementsofusingsubqueries.Wehavethe
followingtwotables'student'and'marks'withcommonfield'StudentID'.

http://www.w3resource.com/sql/subqueries/understandingsqlsubqueries.php

1/10

12/23/2015

SQLSubqueriesw3resource

studentmarks
Nowwewanttowriteaquerytoidentifyallstudentswhogetbettermarksthanthat
ofthestudentwho'sStudentIDis'V002',butwedonotknowthemarksof'V002'.
Tosolvetheproblem,werequiretwoqueries.Onequeryreturnsthemarks
(storedinTotal_marksfield)of'V002'andasecondqueryidentifiesthestudents
whogetbettermarksthantheresultofthefirstquery.
Firstquery:
viewplain

01.
02.
03.

copytoclipboard

print

SELECT*
FROM`marks`
WHEREstudentid='V002';

Queryresult:

Theresultofthequeryis80.
Usingtheresultofthisquery,herewehavewrittenanotherquerytoidentifythe
studentswhogetbetternarksthan80.Hereisthequery:
Secondquery:
viewplain

01.
02.
03.
04.

copytoclipboard

print

SELECTa.studentid,a.name,b.total_marks
FROMstudenta,marksb
WHEREa.studentid=b.studentid
ANDb.total_marks>80;

Queryresult:

Abovetwoqueriesidentifiedstudentswhogetbetternumberthanthestudentwho's
StudentIDis'V002'(Abhay).
Youcancombinetheabovetwoqueriesbyplacingonequeryinsidetheother.The
http://www.w3resource.com/sql/subqueries/understandingsqlsubqueries.php

2/10

12/23/2015

SQLSubqueriesw3resource

subquery(alsocalledthe'innerquery')isthequeryinsidetheparentheses.Seethe
followingcodeandqueryresult:
viewplain

01.
02.
03.
04.
05.
06.

copytoclipboard

print

SELECTa.studentid,a.name,b.total_marks
FROMstudenta,marksb
WHEREa.studentid=b.studentidANDb.total_marks>
(SELECTtotal_marks
FROMmarks
WHEREstudentid='V002');

Queryresult:

PictorialPresentationofSQLSubquery:

http://www.w3resource.com/sql/subqueries/understandingsqlsubqueries.php

3/10

12/23/2015

SQLSubqueriesw3resource

Subqueries:GeneralRules
AsubquerySELECTstatementisalmostsimilartotheSELECTstatementanditis
usedtobeginaregularorouterquery.Hereisthesyntaxofasubquery:
(SELECT[DISTINCT]subquery_select_argument
FROM{table_name|view_name}
{table_name|view_name}...
[WHEREsearch_conditions]
[GROUPBYaggregate_expression[,aggregate_expression]...]
[HAVINGsearch_conditions])

http://www.w3resource.com/sql/subqueries/understandingsqlsubqueries.php

4/10

12/23/2015

SQLSubqueriesw3resource

Subqueries:Guidelines
Therearesomeguidelinestoconsiderwhenusingsubqueries:
Asubquerymustbeenclosedinparentheses.
Asubquerymustbeplacedontherightsideofthecomparisonoperator.
Subqueriescannotmanipulatetheirresultsinternally,thereforeORDERBYclause
cannotbeaddedintoasubquery.YoucanuseaORDERBYclauseinthemain
SELECTstatement(outerquery)whichwillbelastclause.
Usesinglerowoperatorswithsinglerowsubqueries.
Ifasubquery(innerquery)returnsanullvaluetotheouterquery,theouterquery
willnotreturnanyrowswhenusingcertaincomparisonoperatorsinaWHERE
clause.

TypeofSubqueries
Singlerowsubquery:Returnszerooronerow.
Multiplerowsubquery:Returnsoneormorerows.
Multiplecolumnsubquery:Returnsoneormorecolumns.
Correlatedsubqueries:ReferenceoneormorecolumnsintheouterSQL
statement.Thesubqueryisknownasacorrelatedsubquerybecausethesubquery
isrelatedtotheouterSQLstatement.
Nestedsubqueries:Subqueriesareplacedwithinanothersubqueries.
Inthenextsessionwehavethoroughlydiscussedtheabovetopics.Apartfromthe
abovetypeofsubqueriesyoucanusesubqueryinsideINSERT,UPDATEand
DELETEstatement.Hereisabriefdiscussion:

SubquerieswithINSERTstatement
INSERTstatementcanbeusedwithsubqueries.Hereisthesyntaxandan
exampleofsubqueriesusingINSERTstatement.
INSERTINTOtable_name[(column1[,column2])]
SELECT[*|column1[,column2]
FROMtable1[,table2]
[WHEREVALUEOPERATOR]

Ifwewanttoinsertthoseordersfrom'orders'tablewhichhavethe
advance_amount2000or5000into'neworder'tablethefollowingSQLcanbeused:
http://www.w3resource.com/sql/subqueries/understandingsqlsubqueries.php

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
returnedbyasinglerowsubquery.Hereisthesyntaxandanexampleof
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

http://www.w3resource.com/sql/subqueries/understandingsqlsubqueries.php

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
DELETEstatementcanbeusedwithsubqueries.Hereisthesyntaxandan
exampleofsubqueriesusingDELETEstatement.
DELETEFROMTABLE_NAME
[WHEREOPERATOR[VALUE]
(SELECTCOLUMN_NAME
FROMTABLE_NAME)
[WHERE)]

Ifwewanttodeletethoseordersfrom'neworder'tablewhichadvance_amountare
lessthanthemaximumadvance_amountof'orders'table,thefollowingSQLcanbe
used:
Sampletable:neworder

http://www.w3resource.com/sql/subqueries/understandingsqlsubqueries.php

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

http://www.w3resource.com/sql/subqueries/understandingsqlsubqueries.php

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

Fixednow.Thanks

Reply Share

Designer_Girl 3yearsago

WhenItrytouseyourexample...itneverworks.
>Subqueryreturnedmorethan1value.
Obviously,mysubqueryisgoingtocontainMANYvalues.Itshould.Someoneelse
suggestedIuseMIN()inmysubquery,but
thatchangestheentirethingintosomethingIdon'twant.
SELECTa.studentid,a.name,b.total_marks
FROMstudenta,marksb

http://www.w3resource.com/sql/subqueries/understandingsqlsubqueries.php

9/10

12/23/2015

SQLSubqueriesw3resource

FROMstudenta,marksb
WHEREa.studentid=b.studentidANDb.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

http://www.w3resource.com/sql/subqueries/understandingsqlsubqueries.php

10/10

You might also like