LAB Worksheet #2and #3
LAB Worksheet #2and #3
AIM: sub Queries using ANY, ALL, IN, EXISTS, NOTEXISTS, UNION, INTERSET.
Solution:
SQL Nested queries:
A nested query is a query that has another query embedded within it. The embedded query is
called a sub query. Generally sub query is appeared in WHERE clause.
Examples on nested queries:
Q1) find sailors names who have reserved boat no 103
SQL> SELECT S.sname FROM sailors S
WHERE S.sid IN ( SELECT R.sid FROM reserves R WHERE R.bid=103)
Output:
Q2) find sailor’s names who have reserved boat no 103
SQL> SELECT S.sname FROM sailors S
WHERE S.sid = ANY ( SELECT R.sid FROM reserves R WHERE R.bid=103)
Output:
Q3) find sailor’s names who have not reserved boat no 103
SQL> SELECT S.sname FROM sailors S
WHERE S.sid NOT IN ( SELECT R.sid FROM reserves R WHERE R.bid=103)
Output:
Q4) find sailor’s names who have not reserved boat no 103
SQL> SELECT S.sname FROM sailors S
WHERE S.sid != ALL ( SELECT R.sid FROM reserves R WHERE R.bid=103)
Output:
UNION (R U S)
The union of two relations R and S is a relation that includes all the tuples that are either in R or
in S or in both R and S. The two relations R and S must be union compatible. Duplicate tuples
are eliminated.
Two relations are union compatible if
they have the same number of attributes ie degree(R)=degree(S)
the domain of each attribute in column order is the same in both R and S
Q8) write a RA and SQL query to display all sailors names whose rating < 9 or age <50
RA: π sname (σ rating<9 (sailors)U σ age<50 (sailors))
SQL> SELECT sname FROM sailors WHERE rating < 9
UNION
SELECT sname FROM sailors WHERE age < 50
Output:
Q9) write a RA and SQL query to display Boat id and names whose color is red or green
RA: π bid, bname (σcolor=’RED’ (boats)U σ color=’GREEN’ (boats))
SQL> SELECT bid,bname FROM boats WHERE color=’RED’
UNION
SELECT bid,bname FROM boats WHERE color=’GREEN’
Output:
LAB WORK SHEET # 3
AIM: Queries using Aggregate functions (COUNT, SUM, AVG, MAX and MIN), GROUP BY,
HAVING and Creation and dropping of Views
Solution:
Queries using Aggregate Functions
AVG() Returns the average value of expr. Avg AGE
Q1)The following query returns the average age of all sailors. -------------
SQL> select avg(age) “AVERAGE AGE” from Sailors