Professional Documents
Culture Documents
MIS710 Module 2a Complex SQL Queries: Arijit Sengupta
MIS710 Module 2a Complex SQL Queries: Arijit Sengupta
MIS710 Module 2a
Complex SQL Queries
Arijit Sengupta
Monotonic and Non-Monotonic
Queries
ISOM
A. Selection
B. Projection
C. Cross Product
D. Union
E. Set Difference
SELECT s.*
FROM Student s, Reg r, Course c
WHERE s.sid = r.sid
AND c.cno = r.cno
AND c.dept = 'CS'
The other monotonic query
ISOM
SELECT s.*
FROM Student s, Reg r, Course c
WHERE s.sid = r.sid
AND c.cno = r.cno
AND c.dept != 'CS'
Solving non-monotonic queries
ISOM
SELECT s1.*
FROM Student s1
MINUS
SELECT s.*
FROM Student s, Reg r, Course c
WHERE s.sid = r.sid
AND c.cno = r.cno
AND c.dept = 'CS'
Nesting Queries - Syntax
ISOM
SELECT attribute(s)
FROM relation(S)
WHERE attr [not] {in | comparison operator |
exists }
( query statement(s) );
List
Listall
allstudents
studentsenrolled
enrolledininMIS
MIScourses
courses
select
select name
name
from
from STUDENT
STUDENT
where
where SIdSIdinin
(select
(select SId
SId
from
from REG
REG
where
where cno
cnolike
like‘MIS%’);
‘MIS%’);
List all courses taken by Student (Id 1011)
select cname
from COURSE
where cnum = any
(select cno
from REG
where SId = 1011);
So, IN and ANY essentially are like joins, not that interesting
Sub Queries - continued
ISOM
Who
Whoreceived
receivedthe
thehighest
highestscore
scoreininMIS
MIS415
415
select
select SId SId
from
from REG
REG ALL is quite powerful
where
where cno cno==‘MIS415’
‘MIS415’andand Since it works on the whole
score >=all
score >=all Set returned by the subquery
(select
(select score
score
from
from REG
REG
where
where cno cno==‘MIS415’);
‘MIS415’);
List all students enrolled in MIS courses.
select name
from STUDENT S
Exists is again like where exists
A join! (select *
from REG
where SId = S.SId
and cno like ‘MIS%’);
Non-monotonic queries using
NOT IN and NOT Exists
ISOM
SELECT s.*
FROM Student s, Reg R1
WHERE s.sid = R1.sid
AND not Exists ( SELECT r.*
FROM Reg r, Course c
WHERE r.sid = s.sid
AND r.cno = c.cno
AND c.cno != ‘CS’)
Base Base
Relation 1 Relation 2
update Qualified-Student
set GPA = GPA-0.1
where StudentID = ‘s3’;
insert into Qualified-Student
values ( ‘s9’, ‘Lisa’, 4.0 )
insert into Qualified-Student
values ( ‘s10’, ‘Peter’, 1.7 )