Nested Queries
Nested Queries
Nested Queries
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
from sollors S
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".
from . soilors S
from reserves R
from boots B
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.
From sallors S
from reserves
from boats 0
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,
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.
from sailors S
where exlsts(select •
from reserves A
from sailors S
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!·