Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Nested Queries

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

4.

12 - - - - - - - - - - - - SQL : Queries, Constraints ancJ Trig9ers [lJ


l\lt
'4
The nbon· l1ucry linds the tupks ,,htch :ire 111 l epch1.tnr but n . I l
111 111
borrower nnd :iutlllnan·c:illy clim111:H
· · es dup 11c:11c
· tup IL'S. ·1·1w-;, 1.f :i cu 51( lf11tt ti1t
biz has an accnunr :1 1 the hank, but h:1 s no lo :111 :it il1e h:111k, th<:n I•, '-~:·,
,11, \I. I
'lj
appear only once 111 the resu\1.

4.4 Introduction to Nested Queries


One of the mosr !)owcrful feature of SQ I,· is nested (JUcrics. 1\ nested u
1lltt1• .
a c1uc1T th:H hns another query unbc<ldc<l (cnclnsl:<l) \\'ithin it. The cinb <l. 11
. I
query 1s en lcu.I a subqucry. \\'/I ..
v 1cn w111111g :1 t1uery, we someum . C dtd
es express~
cnnditions in rhe where cbusc th:it mu,1 i1sclf be c~mpu reJ . The qucrr lt
. .. .
10 compute thts cond1uo 11 1:- :i :-ul)(lll('l'\' :ind :ippl':irs as pan of the main , u~cd
· ' yucrv
.\ ::-ubquery actually appc:irs within the where cbu~c of a query. Subgucrics ca~
somcllmcs :ippc:u in the from cl:Jusc or the h,n·ing clause. .
Herc :ire the sa mple d:w1basc s,

f ¢Mftff j An Instance S3 of sailors I ,


sid SIIUlllC rating age
22 Du ~ltn 7 45.(J
29 Brutm I 33.0
31 Lubber 8 55.5
32 ,\ndr 8 25.0
58 Ru~tY 10 35.0
64 ..,
I lorauo 35.0
71 Zo rba 10 16.0
74 Horn tjo 9 -1 0.0
85 .-\n 3 ')- r
- :>.)
95 Bob 3 63.5

ij'.@ttlffl An Instance R2 of reserves I


sid bid day
,.,,.,
101 10/ 10/ 98
22 102 10/10/ 98
~2 103 10/ 8/ 98
I
22 lfJ-1 11)/7 / 98
31 102 11 / 10/ 98
31 103 11 / 6/ 98
31 10-1 11 / 12/ 98
6-1 101 9/5 / ')8
(,-1 102 9/ 8/98
-➔ 103 9/8 / t.JS

l-•~vM, {j·,_t~l~•li2·
,___ •· · ~1tffl~
-~,~·\,~f1\iM
- · ,,_, ___ l~~~m~ai~4t~Ji~tl~.-- ---- ---- -
.,____ Database Management Sy~
steJ11S
SQL: Queries, Constraints and Triggers [Unit _ 4] _ _ _ _ _ _ _ _ _ _ __
4.13

lfflij@ffl An Instance B1 or boats I


hid bnam c color
101 ln1crl.1h· l>luc
102 lntnhkc rrd
11)3 Cl1ppn grcl'I!
I 0-1 t-.larmc red
Example Queries

I) Find tht namts of sailors who have rcscr\'(:d boat 103.


sql> select S.sname

from sollors S

where S.sld ln(select R.sid

from reserves A

where A.bid = 10 3) ;

· , The nested subg uery computes many siJs for sailors who han: rcscn-cd
boat 103 (sids are 22, 31 and 74) and main query (top-b·cl query) retrie,·es
the names of sailors whose sids arc 22, 31 and 74. The "in" operator allows
us to test whether a value is present in subquery or not. We get result as,
Dustin. Lubber and Horatio.

I
It is easy t_o modify this query ro find all sailors who ha,·e not rest•ryed
bo:it 103 by just replacing operation "in" by "not in".

· ~Iorem·cr, the subguet)' might itself contain :rnothcr nested subguery


known as multiple ncsrcd query.

2) Find the names of sailors who ha,·e resen-c<l a red boat.

sql> select S.snome

from . soilors S

where S.sld ln(select R.sld

from reserves R

where A.bid in(select B.bid

from boots B

where B.colcir = 'red')):

Database Man agement Systems ---- --------11fflai1?•)btbr•nf-j@truS,Mt!i1


4.14 - - - - - - - - - - - - SQL: Queries, Constr.1lnts and Trigger~ (
Unit ..
41
'1lll' 11111trml,st ~uhlJUl:r\' find:-. hius of rcJ bonts ~02 nnJ 104. lh
,ulll\Ul't ~ lllh' Ind nbm l ' finds ~td ot" s:ulon, who hnvc r('sCr\'c<l bo:lts :
10
.rnd I tl-l :1s ~ids 22 • .31 :inJ (,4. ..

The 1u11-h:H-I uucn· find s 11.1 mt·s of sni.lors whose sids nrc -n- , 3t
7 •/ , , :IOd
6-l ;\s n rc~ult "c ~ct ,umcs, Durnn. l.ul>l>cr :\ll<l I lor:u10.

Tu tind the n:uncs of -;.ulors who h:1\'c nut rcscn·cd n reJ bo•t
" I \\'t
rtp I.\ct· tlw outer most occurrence o f "in" b)' " not 111.
. ..

'\) 1-tnd tht• n:11111:, t)f s:ul<irs who h:n-c not rt.'Sl' r\'cd n rcJ bont.

sql> select S..snome

From sallors S

where S.sld not ln(selcct A sld

from reserves

where A.bid ln(sclect 0.bld

from boats 0

where a.color = 'red'));

111i:- <-1uecT comput<.:s the n:unes of snilors whose sid is not in the set
~2, .3 1 :lllll 6-l .•\ s a result \\'C get n:uncs,

Brutus, .\nJy. Rusty, Zorba, Hor:itio, Art nnd l3ob.

4.4.1 Correlated Nested Queries

In nested queries Lh:1t we hn,·e seen so for, the inner subquery has been complc'1clj·
independent of outer query.

In gc.:ncnl the inner subqm:ry could depend on cnch row that is currently
being examined in the outer query.

Example Query : Find the names of :rnilors who have rcscn·cd boat 103.

sql> select S.sname

from sailors S

where exlsts(select •
from reserves A

where A.bid= 103


·,
and A.sld = S.sld);

•ft:1@·U•l$ H\iilt---------- Database Management S ~


sQL: Queries, Constraints and Triggers [Uni t_
__ __ __ __ __ __
~ 41 4.15
'111c c:iasts opera tor is "n0 I .
• " 1 1cr
set comp ariso n upcr: itor, sue I1 as ...111 " • It ''"llow s-
u,· to test for each row of
ourl't. query whet her the mncr
.
su1)l)uer y ,~ ·. uue for
that row or false for that row. So, for each row of outer
qucrr , the inner subq ucry
is again and again evalu ated. ·nms, for exam ple, for
sailor row Dust in, we rest
whet her rescn·es rows R.bid =
103 an<l R.sid =
S.sid. 1f so, s:1ilor s row Dust in
has rcscr n~d boat I 03 and we rctric ,·c the name. T
he subl1uery clearly depcl ld s
on curre nt row Du st in anJ must be re-ev aluate d for
each row in sailors. The
occu rrenc e of S in the sul?query is called a correlation
anJ such queri es MC called
corre lated 9ucri es.

This query also show s the use of special symb ol ,,..,


wher e we are ch_ecking
that a quali fying row cxiste~ of main query and c,·cn
after selecting all colum ns
of subl1uery using ·'"'' symb ol we are not retrieving them
. This is one of the two
uses of ,,p in selec t claus e and that is good progr amm
ing style .

..\s f~~lhl'~, by using not exists instead of exists, we can


comp ute the name s
of :.au," ·~ who have not reser ved a red boat.

4.4.2 Set Com paris on Operators in Nested Queries

SQL also supp orts op any and op all, wher e op


is one of the arith meti c
comp ariso n opera tors {<, <=, = , <>, >=, > }.

Example Query : Find the sailors with the highe


st rating.

sql> select S.snome

from sailors S

where s.rotl ng >= oll(select S2.rotlng

from sailors S2);

Th e su b query c O mput es all taring values in sailors, The outer wher e claus e
cood .iuon
. 1s. saus· fi e <l o nly when S.rating is great er than or equal to each
of these
. · h
ratmg value s 1.e., w en 1· t is the largest rating value. ·Here. the cond
.
ition is only
.
. • 10
sausf ied for rating an d the resul t includes name of sailors with rattng 10 as
.
name s Rusty and Zorb a.

· l
"in" and "not in" are equ1v a ent to " = any" and "<>a ll" respecti,rely. , ·
~as e Mana geme nt Systems ------------111\liil41i!·1Di!·1?HEilit!·ID,tl· a,1m;,mmm,1,~GII
1
Gtti!·

You might also like