EXPERIMENT NO.
AIM:- Perform Nested and Complex Queries
OBJECTIVES :-To understand Nested and Complex Queries in SQL
THEORY:-
A sub/nested query is a select query that is contained inside another query. The inner select query is usually used
to determine the results of the outer select query\
Let's look into the sub query syntax -
Nested Query: some nested queries are written based on below schema.
1) Find the names of sailors who have reserved boat number 103.
select [Link], [Link] , [Link] from sailors s, reserves r where [Link] = [Link] and [Link]=103;
2) Find the sids of all sailors who have reserved red boats but not green boats.
select [Link] , [Link], [Link] from sailors s, reserves r, boat b where [Link]=[Link] and [Link]
=[Link] and [Link]='red' and [Link] not in (select [Link] from sailors s,reserves r,boat b where
[Link]=[Link] and [Link]=[Link] and [Link]='green');
3) Find sailors whose rating is better than some sailor called Horatio.
select sid,sname,rating from sailors where rating > any (select rating from sailors where
sname='horatio');
4) Find the sailor with the highest rating.
select sid, sname, rating from sailors where rating in(select max(rating) from sailors );
5) Find the names of sailors who have reserved all boats.
select [Link] from sailors s where not exists ( select [Link] from boat b where not exists ( select
r. bid fom reserves r where [Link] = [Link] and [Link] = [Link] ))
6) Find the age of the youngest sailors who is eligible to vote (i.e., is at least 18 years old) for each rating level
with at least two such sailors.
select min(age),count(*) from sailors where age>18 group by rating having count(*)=2 or
count(*)>2;
7) Find the average age of sailors who have of voting age (i.e.~ at least 18 years old) for each rating level that
has at least two sailors.
select rating, avg(age),count(*) from sailors where age>18 group by rating having
count(*)>1;