You are on page 1of 33

ISOM

MIS710 Module 2a
Complex SQL Queries

Arijit Sengupta
Monotonic and Non-Monotonic
Queries
ISOM

• Monotonic queries: queries for which the size of


the results either increase or stay the same as the
size of the inputs increase. The result size never
decreases
• Non-monotonic queries: queries for which it is
possible that the size of the result will DECREASE
when the size of the input increases
• Examples of each?
Examples of monotonic queries
ISOM
Examples of non-monotonic queries
ISOM
Which of the operations is non-
monotonic?
ISOM

A. Selection
B. Projection
C. Cross Product
D. Union
E. Set Difference

What does this signify?


Identify – monotonic/non-
monotonic?
ISOM
• Find students who have taken
algebra but not calculus
A. Monotonic
B. Non-monotonic

• Find students who have taken


calculus but are not math majors
A. Monotonic
B. Non-monotonic
Answers to prev. slide
ISOM
• Find students who have taken algebra but not
calculus
 Non-monotonic – you take a student who has taken
algebra but not calculus, add a new registration for
calculus, and he is gone from the result
• Find students who have taken calculus but are
not math majors
 Monotonic! Assume Joe has taken calculus and is not
a math major – can you remove him from the result by
adding more rows?
• Moral: If something is monotonic, you can solve
it with basic SELECT-FROM-WHERE
• If something is non-monotonic – you HAVE to
use something else
• Options are: MINUS, NOT IN, NOT EXISTS,
Special grouping
Identify – monotonic/non-
monotonic
ISOM

1. Find the students who have taken some


CS courses
2. Find the students who have only taken
CS courses
3. Find the students who have taken all
the CS courses
4. Find the students who have not taken
any CS course
5. Find the students who have taken a
non-CS course
Answers to previous slide
ISOM

1. Monotonic – if someone has taken some CS


course, he stays in the results regardless of
what you add/remove
2. Non-monotonic – someone who has only
taken CS course will disappear from the result
if you add a registration for them for a non-cs
course
3. Non-monotonic – if you add a new CS course,
then …
4. Non-monotonic – if you add a registration for a
CS course…
5. Monotonic! Someone who has taken a non-
CS course will continue to stay in the result!
Thumb rules
ISOM

• Some clues to identify non-monotonic


queries
 Every, All
 No, None, Never
 Only
• Remember – these are just thumb rules
and not absolute laws – you need to think
about how the queries will behave to
determine non-monotonicity
Lets do the monotonic first!
ISOM

• Find students who have taken some


CS course

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

• Find Students who have taken a


Non-CS Course

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

• We know that MINUS can solve


non-monotonic
• Unfortunately representing all
queries using MINUS is not easy
• Some are easy:
Students who have not taken any CS
course
All students MINUS students who have
taken some CS course
Non-monotonic queries using
MINUS
ISOM
• All students MINUS students who have taken
some CS course

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 names of students who are taking “MIS415”


select Name
from Student
where SID in
( select SID
from REG
where Cno = ‘MIS415’);
Sub Queries
ISOM

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

• Students who have not taken CS courses

Using NOT IN Using NOT EXISTS

SELECT s.* SELECT s.*


FROM Student s FROM Student s
WHERE s.sid not IN ( WHERE NOT EXISTS (
SELECT r.sid SELECT *
FROM Reg r, Course c FROM Reg r, Course c
WHERE r.cno = c.cno WHERE r.cno = c.cno
AND c.dept = ‘CS’) AND c.dept = ‘CS’
AND r.sid = s.sid)

Notice how the alias ‘s’ from outside the


subquery is used in the subquery!
These are called “correlated” subqueries.
The “default” results
ISOM

• Notice that sometimes queries using


not exists will give you results that
appear “by default”

• For example, students who have not


taken ANY course will show up in
the result of the last query

• Okay for this query?


Writing non-monotonic queries
ISOM
• See if you can rewrite the statement below in English with
double negatives.
• Remember – the new sentence MUST mean the same!
• Find students who have taken ALL CS courses
Try another one
ISOM

• Find students who have got A’s in


All courses they took
Tackling non-monotonic queries
ISOM

• Try 1: See if you can write it as a


difference between two sets
 Solve using MINUS or NOT IN
• Try 2: Rewrite the query to use the tables
and finding ways to use not exists
 Find students who have taken all CS courses
 Find students such that there is no CS course
that they have not taken
 Find students such that there doesn’t exist
any CS course for which there doesn’t exist a
registration for that student in that course!
 Yes, a lot of double negatives!
Step by Step
ISOM

• Find students who have taken all CS courses

Find students SELECT s.*


FROM Student s
such that there doesn’t exist WHERE not exists (
SELECT c.*
any CS course FROM Course c
WHERE c.dept = ‘CS’
for which there doesn’t exist AND NOT EXISTS (

a registration SELECT r.*


FROM Reg r
WHERE
for that student r.sid = s.sid

AND r.cno = c.cno))


in that course!
Should we do one more?
ISOM

• Find students who have ONLY taken CS


courses
• Find students such that every course
they have taken is a CS course
• Find students such that every registration
they have corresponds to a CS course
• Find students such that there doesn’t
exist any registration record for that
student corresponding to a non-CS
course
Translating this query
ISOM

Find students SELECT s.*


such that FROM Student s
there doesn’t exist WHERE not Exists
any registration record ( SELECT r.*
FROM Reg r, Course c
for that student WHERE r.sid = s.sid
corresponding to a AND r.cno = c.cno
non-CS course AND c.cno != ‘CS’)
Default result here
ISOM

• You will notice that students who have


not taken any courses will show up in this
query’s results!
• Why?
• Logically, students who haven’t taken
any courses haven’t taken any non-cs
courses 
• To get rid of this default behavior, you
may want to perform a join on the
outermost query, so that you retrieve
students who have taken some course
Query with the default removed
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’)

Now this query will only retrieve students


who have taken at least one course,
none of which is CS.
Relational Views
ISOM

• Relations derived from other relations.


• Views have no stored tuples.
• Are useful to provide multiple user views.

View 1 View 2 View N

Base Base
Relation 1 Relation 2

•What level in the three layer model do views belong?


•Which kind of independence do they support?
View Creation
ISOM

Create View view-name [ ( attr [ , attr ] ...) ]


AS subquery
[ with check option ] ;

DROP VIEW view-name;

 Create a view containing the student ID, Name,


Age and GPA for those who are qualified to
take 300 level courses, i.e., GPA >=2.0.
View Options
ISOM

• With Check Option enforces the query


condition for insertion or update
To enforce the GPA >=2.0 condition on all
new student tuples inserted into the view

• A view may be derived from multiple base


relations
Create a view that includes student IDs, student names and
their instructors’ names for all CIS 300 students.
View Retrieval
ISOM

Queries on views are the same as that on base


relations.
Queries on views are expanded into queries on
their base relations.

select Name, Instructor-Name


from CIS300-Student
where Name = Instructor-Name;
View: Update
ISOM

Update on a view actually changes its base relation(s)!

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 )

Why are some views not updateable?


What type of views are updateable?
Summary
ISOM

• SQL is a low-complexity, declarative query


language
• The good thing about being declarative is
that internally the query can be changed
automatically for optimization
• Good thing about being low-complexity?
 No SQL query ever goes into an infinite loop
 No SQL query will ever take indefinite amount of
space to get the solution
• Can be used for highly complex problems!

You might also like