0% found this document useful (0 votes)
29 views42 pages

6 SQL Post 4

The document outlines important deadlines and reminders for upcoming tutorials, midterms, and milestones related to a course. It also provides SQL practice exercises, including queries using various SQL concepts such as NOT EXISTS, INTERSECT, and Division. Additionally, it emphasizes the significance of SQL in relational databases and its expressive power compared to earlier query languages.

Uploaded by

Roy Chen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views42 pages

6 SQL Post 4

The document outlines important deadlines and reminders for upcoming tutorials, midterms, and milestones related to a course. It also provides SQL practice exercises, including queries using various SQL concepts such as NOT EXISTS, INTERSECT, and Division. Additionally, it emphasizes the significance of SQL in relational databases and its expressive power compared to earlier query languages.

Uploaded by

Roy Chen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Reminders and Important Dates

Mar 12, 2020


Upcoming deadlines
• March 9 to 13: Tutorial 6 is due
• March 16 to 20: Tutorial 7 is due
• March 17 @ 7PM: Midterm 2
• March 30 to April 3: Tutorial 9 is due
• April 5 @ 11:59PM: Milestone 4- Implementation (no late submissions allowed)
• April 7-8: Milestone 5- Demos
• April 8 @ 11:59PM: Tutorial 10 is due April 14 @ 12PM: Final exam

Reminders
• Java/Oracle, PHP/Oracle and PHP/MYSQL resources are available
• Mason and Aditya have office hours dedicated for project
• If your project group would like to meet with your project TA within the next week, then
please email them to set up an appointment

• RA and Datalog practice exercises are available on canvas – Please


check them out!
Please check piazza post @7 for Important Dates and Deadlines
Outline

1. Recap
2. SQL
• Not Exists
• Division
3. Practice Exercise

2
Previously…
• Set Operators (Union, Intersection, Except)

• ALL and ANY

• IS NULL

• Self referencing joins

• Outer joins

• Exists

• Not 3
NOT
Apartment

Query 33a: Display the BuildingID, AptNo, and ANoOfBedrooms for all apartments that are not
leased.
SELECT buildingid, aptno, anoofbedrooms, ccid
FROM apartment
WHERE ccid IS NULL

Query 33b : Display the BuildingID, AptNo, and ANoOfBedrooms for all
apartments that are leased.
SELECT buildingid, aptno,
anoofbedrooms, ccid
FROM apartment
WHERE ccid IS NOT NULL

SQL 4
Practice Exercise 1
Ques. Consider the following relations:
•Student(snum: integer, sname: string, major: string, standing: string, age: integer)
•Class(name: string, meets_at: string, room: string, fid: integer)
•Enrolled(snum: integer, cname: string)
•Faculty(fid: integer, fname: string, deptid: integer)

1. Find the names of all students who are enrolled in two classes that
meet at the same time.

2. Find the names of students not enrolled in any class.

SQL 5
Practice Exercise SOL
Ques. Consider the following relations:
•Student(snum: integer, sname: string, major: string, standing: string, age: integer)
•Class(name: string, meets_at: string, room: string, fid: integer)
•Enrolled(snum: integer, cname: string)
•Faculty(fid: integer, fname: string, deptid: integer)
1. Find the names of all students who are enrolled in two classes that
meet at the same time.
SELECT DISTINCT S.sname Select DISTINCT s.sname
FROM Student S From class c, student s,
WHERE S.snum IN (SELECT E1.snum enrolled e
FROM Enrolled E1, Enrolled E2, Class C1, Class C2 where c.name = e.cname
WHERE E1.snum = E2.snum AND AND s.snum = e.snum
E1.cname <> E2.cname group by c.meets_at,
AND E1.cname = C1.name s.sname
AND E2.cname = C2.name AND having count(meets_at) > 1
C1.meets_at = C2.meets_at)

SQL 6
2. Find the names of students not enrolled in any class.
SELECT DISTINCT S.sname
FROM Student S
WHERE S.snum NOT IN (SELECT E.snum
FROM Enrolled E )

SQL 7
NOT EXISTS

SELECT [Column Names]


FROM [table]
WHERE NOT EXISTS (Subquery to Check)

Subquery: If the subquery returns true then it will


return the records otherwise, it doesn’t return any
records.

SQL 8
NOT EXISTS
Query 34 text: Retrieve records for all buildings that do not have managers living
in them

SQL 9
NOT EXISTS
Query 34 text: Retrieve records for all buildings that do not have managers living
in them
Building
Query 34:
SELECT *
FROM building b Manager
WHERE NOT EXISTS
(SELECT *
FROM manager m
WHERE b.buildingid = m.mresbuildingid);

Query 334result:

SQL 10
INTERSECT and EXCEPT
SELECT R.A, R.B (SELECT R.A, R.B
FROM R FROM R)
WHERE INTERSECT
EXISTS (SELECT * (SELECT S.A, S.B
FROM S FROM S)
WHERE R.A=S.A and R.B=S.B)

Query : List the Building id and the first name of managers that were living in building
having more than four floors.
select m.mfname, m.mresbuildingid select m.mfname, m.mresbuildingid
from manager m from manager m
where Exists intersect
(select b.buildingid select m.mfname, m.mresbuildingid
from building b from building b , manager m
where b.bnooffloors > 4 and where b.bnooffloors > 4 and
b.buildingid=m.mresbuildingid) b.buildingid=m.mresbuildingid

SQL 11
INTERSECT and EXCEPT

SELECT R.A, R.B (SELECT R.A, R.B


FROM R FROM R)
WHERE INTERSECT
EXISTS (SELECT * (SELECT S.A, S.B
FROM S FROM S)
WHERE R.A=S.A and R.B=S.B)

SELECT R.A, R.B (SELECT R.A, R.B


FROM R FROM R)
WHERE EXCEPT
NOT EXISTS (SELECT * (SELECT S.A, S.B
FROM S FROM S)
WHERE R.A=S.A and R.B=S.B)

SQL 12
Division query example

• Find students who have taken all courses taught by instructor “Hazra”.

• Find the supplier_ids of suppliers who supply every part.

• Find the sids of suppliers who supply every red part.

SQL 13
cust(cid, cname, rating, salary)
ord(cid, iid, day, qty)
item(iid, iname, price)
Division Example
Query: Find items (iid) that are ordered by every customer

cust item ord


𝜋𝑖𝑖𝑑,𝑐𝑖𝑑 𝑜𝑟𝑑 ÷ 𝜋𝑐𝑖𝑑 (𝐶𝑢𝑠𝑡)) I1 …
C1 … C1 I1 … …
C2 … I2 … C2 I1 … …
C3 … C3 I1 … …
C1 I2 … …
𝑤𝑖𝑡𝑛𝑒𝑠𝑠(𝐶,𝐼) 𝑜𝑟𝑑(𝐶,𝐼,_,_)
B𝑎𝑑(𝐼) ← 𝑐𝑢𝑠𝑡 (𝐶,_,_,_ ), 𝑜𝑟𝑑 (_,𝐼,_,_ ), ¬𝑤𝑖𝑡𝑛𝑒𝑠𝑠 (𝐶,𝐼) .
G𝑜𝑜𝑑 (𝐼) ← 𝑜𝑟𝑑(_,𝐼,_,_), ¬B𝑎𝑑(𝐼).

select item I such that ...


there is no item I…
which is not ordered by C

14
Division in SQL
Student Enrolled
Course

Query: Retrieve the name of the students who are enrolled in ALL
the courses

15
Division in SQL
Student Enrolled
Course

Query: Retrieve the name of the students who are enrolled in ALL
the courses
R1  𝜋𝑠𝑖𝑑,𝑐𝑖𝑑 𝑒𝑛𝑟𝑜𝑙𝑙𝑒𝑑 ÷ 𝜋𝑐𝑖𝑑 (𝑐𝑜𝑢𝑟𝑠𝑒))
Answer  𝜋𝑠𝑛𝑎𝑚𝑒 𝑆𝑡𝑢𝑑𝑒𝑛𝑡 ⋈𝑅1

Find student S such that


There is no course C
Which is not enrolled by S

16
Division

Query: Retrieve the name of the students who are enrolled in ALL the courses

R1  𝜋𝑠𝑖𝑑,𝑐𝑖𝑑 𝑒𝑛𝑟𝑜𝑙𝑙𝑒𝑑1 ÷ 𝜋𝑐𝑖𝑑 (𝑐𝑜𝑢𝑟𝑠𝑒1)) SELECT s.SName


Answer  𝜋𝑠𝑛𝑎𝑚𝑒 𝑆𝑡𝑢𝑑𝑒𝑛𝑡1 ⋈𝑅1
FROM student s
WHERE NOT EXISTS
(SELECT * from course c
Find student S such that WHERE NOT EXISTS
There is no course C (SELECT E.SID
Which is not enrolled by S
FROM enrolled E
WHERE S.SID=E.SID AND
C.CID=E.CID));

17
Find student S such that
There is no course C

Division Which is not enrolled by S

Query: Retrieve the name of the students who are enrolled in ALL the courses
SELECT s.SName
FROM student s
WHERE NOT EXISTS
(SELECT * from course c
WHERE NOT EXISTS
(SELECT E.SID
FROM enrolled E
WHERE S.SID=E.SID AND
C.CID=E.CID));

18
Find student S such that
There is no course C

Division Which is not enrolled by S

Query : Retrieve the name of the students who are enrolled in ALL
the courses
SELECT s.SName S1, Mary

FROM student s CPSC 304


- Enrolled – S1, 304 (found a tuple) False (304 will not returned)
1 WHERE NOT EXISTS CPSC 416
- Enrolled – S1, 416 (found a tuple) False (416 will not returned)
(SELECT * from course c → The innermost loop is empty (TRUE). So (S1) will go in result set

2 WHERE NOT EXISTS


S2, John
(SELECT E.SID CPSC 304

FROM enrolled E -Enrolled- S2, 304 (found a tuple). False ((304 will not returned)
CPSC 416
WHERE S.SID=E.SID AND -no tuple TRUE. Return CPSC 416 to

→ (S2, John) inner query is not empty so this will not go in result set
C.CID=E.CID));

19
Division – Easy way
SELECT s.SName
SELECT s.SName
FROM student s FROM student s
WHERE NOT EXISTS WHERE NOT EXISTS
(SELECT * from course c ((SELECT c.cid from course c)
WHERE NOT EXISTS EXCEPT
(select E.cid
(SELECT E.SID
from Enrolled E
FROM enrolled E where E.sid = S.sid));
WHERE S.SID=E.SID AND
C.CID=E.CID));

20
ST – SalesTransaction
S – Soldvia
P- Product
Division in SQL – TRY! C- Customer

• Query: Find customers name who have bought all products


Select customer C such that ...
there is no product P…
which is not purchased by C

SQL 21
ST – SalesTransaction
S – Soldvia
P- Product
Division in SQL – TRY! C- Customer

• Query : Find customers name who have bought all products


Select customer C such that ...
there is no product P…
which is not purchased by C

SELECT C.CustomerName SELECT C.CustomerName


FROM customer C FROM customer C
WHERE NOT EXISTS WHERE NOT EXISTS
((SELECT P.ProductID from product P) (SELECT P.ProductID from product P
EXCEPT where not exists
(Select S.ProductID FROM (Select S.ProductID FROM
soldvia S, salestransaction T soldvia S, salestransaction T
WHERE T.TID=S.TID AND WHERE T.TID=S.TID AND
T.CustomerID=C.CustomerID )); T.CustomerID=C.CustomerID
and P.productid = S.productid));

SQL 22
Relational schema: ZAGI Retail Company Sales Department Database
Join Without Using A Primary Key/ Foreign Key
Combination

• Join without using a primary key/foreign key combination


• It is possible to join two tables without joining a foreign key column in one
table with a primary key column in another table.
• A JOIN condition can connect a column from one table with a column
from the other table as long as those columns contain the same values.

SQL 24
Join Without Using A Primary Key/Foreign Key
Combination
Query 35 text: For each manager who has a staff member with the
same name as the manager’s first name, show the manager’s ID, first
name, and last name, ID of the staff members, name of staff member

Query 35: SELECT m.managerid, m.mfname, m.mlname,


s.smemberid
FROM manager m, staffmember s
WHERE m.mfname = s.smembername;

Query 35 result:

SQL 25
Assertions

SQL 26
Constraints over Multiple Relations:
Remember this one?

name dname
since
sin lot did budget

Employees WorksIn Departments

(many) (many)

• We couldn’t express
“every employee works in a department and every department has some
employee in it”?
• Neither foreign-key nor not-null constraints in Works_In can do that.
• Assertions to the rescue!

SQL 27
Constraints Over Multiple Relations

• Cannot be defined in one table.


• Are defined as ASSERTIONs which are not associated with any
table
• Example: Every MovieStar needs to star in at least one Movie

CREATE ASSERTION totalEmployment


CHECK
( NOT EXISTS ((SELECT StarID FROM MovieStar)
EXCEPT
(Select StarID FROM StarsIn)));
Not In Exam

SQL 28
Summary

• SQL was an important factor in the early acceptance of the relational


model; more natural than earlier, procedural query languages.

• Relationally complete; in fact, significantly more expressive power


than relational algebra.

• Consists of a data definition, data manipulation and query language.

• Many alternative ways to write a query; optimizer should look for


most efficient evaluation plan.

• NULL for unknown field values brings many complications

• SQL allows specification of rich integrity constraints (assertions)

SQL 29
Learning Goals Revisited
Given the schemas of a relation you will be able to:

1. Create SQL queries using: SELECT, FROM, WHERE, DISTINCT,


GROUP BY, HAVING, ANY, ALL, JOINS, EXISTS AND NOT EXISTS

2. Show that there are alternative ways of coding SQL queries to yield the
same result. Determine whether or not two SQL queries are equivalent.

3. Comment on the relative expressive power of SQL.

4. Explain the purpose of NULL values and justify their use. Also describe
the difficulties added by having nulls.

5. Create and modify table schemas and views in SQL.

6. Translate a query between SQL and RA/Datalog

SQL 30
Midterm 2
• WHEN: Tuesday March 17, 2020 @ 7PM
• HOW LONG: 90 minutes
• WHERE:
• HEBB 100: A to PAN
• PHRM 1101: PARANGUE to Z
• COVERAGE: From 3NF to the end of SQL

• Hazra’s office hour on Tuesday (Mar 17)


• Open office hour (5 – 6:30 in DMP 310)
• No office hour from 3 – 4:30 on Mar 17

SQL 31
Class Activity - Translate into RA and SQL
Professor(ssn, profname, status, salary) • status can take values from “Full”,
Course(crscode, crsname, credits) “Associate”, and “Assistant”.
Taught(crscode, semester, ssn) • csc6710 is crscode

1. List the names of those courses that Professor Smith have never taught.
2. Return the course code of those courses that have been taught by all professors.
3. Return those courses that have been taught in all semesters.
4. Return those courses that have been taught ONLY by assistant professors

SQL 32
1. List the names of those courses that
Professor Smith have never taught

Professor(ssn, profname, status, salary)


Course(crscode, crsname, credits)
Taught(crscode, semester, ssn)

crsname(Course)-crsname(profname=‘Smith’(Professor) (Taught) Course)

SELECT crsname
FROM Course C
WHERE NOT EXISTS
SELECT *
FROM Professor P, Taught T
WHERE P.profname=‘Smith’ AND P.ssn = T.ssn AND
T.crscode = C.crscode
)

SQL 33
2. Return the coursecode of those courses that
have been taught by all professors.

Professor(ssn, profname, status, salary)


Course(crscode, crsname, credits)
Taught(crscode, semester, ssn)

crscode, ssn(Taught)/ ssn(Professor)


SELECT crscode
FROM Taught T1
WHERE NOT EXISTS(
(SELECT ssn
FROM Professor)
EXCEPT
(SELECT ssn
FROM Taught T2
WHERE T2.crscode = T1.crscode))

SQL 34
3. Return those courses that have been taught
in all semesters.

Professor(ssn, profname, status, salary)


Course(crscode, crsname, credits)
Taught(crscode, semester, ssn)

crscode, semester(Taught)/ semester(Taught)


SELECT crscode
FROM Taught T1
WHERE NOT EXISTS(
(SELECT semester
FROM Taught)
EXCEPT
(SELECT semester
FROM Taught T2
WHERE T2.crscode = T1.crscode)
)

SQL 35
4. Return those courses that have been taught
ONLY by assistant professors.

Professor(ssn, profname, status, salary)


Course(crscode, crsname, credits)
Taught(crscode, semester, ssn)

crscode(Course) - crscode (status‘Assistant’(Professor) Taught)

SELECT crscode
FROM Course C
WHERE c.crscode NOT IN(
(SELECT crscode
FROM Taught T, Professor P
WHERE T.ssn = P.ssn AND P.status ‘Assistant’
)

SQL 36
More Practice- Translate into RA and SQL
Professor(ssn, profname, status, salary)
Course(crscode, crsname, credits)
Taught(crscode, semester, ssn)
status can take values from “Full”, “Associate”, and “Assistant”.

5. Return the ssn of those professors who have taught ‘csc6710’ but never
‘csc7710’.
6. Return the ssn of those professors who have taught both ‘csc6710’ and
‘csc7710’.
7. Return the ssn of those professors who have never taught ‘csc7710’.
8. Return the professor who earns the highest salary. [Only SQL]
9. Select name of those professors who taught less than 40 credits. [Only
SQL]

SQL 37
5. Return the ssn of those professors who have
taught ‘csc6710’ but never ‘csc7710’.

Professor(ssn, profname, status, salary)


Course(crscode, crsname, credits)
Taught(crscode, semester, ssn)

ssn(crscode=‘csc6710’(Taught))-ssn(crscode=‘csc7710’(Taught))
(SELECT ssn
From Taught
Where crscode = ‘CSC6710’)
EXCEPT
(SELECT ssn
From Taught
Where crscode = ‘CSC7710’))

SQL 38
6. Return the ssn of those professors who have
taught both ‘csc6710’ and ‘csc7710’.

Professor(ssn, profname, status, salary)


Course(crscode, crsname, credits)
Taught(crscode, semester, ssn)

ssn(crscode=‘csc6710’(Taught))  ssn(crscode=‘csc7710’(Taught))

SELECT T1.ssn
From Taught T1, Taught T2,
Where T1.crscode = ‘CSC6710’ AND
T2.crscode=‘CSC7710’ AND T1.ssn=T2.ssn

SQL 39
7. Return the ssn of those professors who have
never taught ‘csc7710’.

Professor(ssn, profname, status, salary)


Course(crscode, crsname, credits)
Taught(crscode, semester, ssn)

ssn(Professor)-ssn(crscode=‘csc7710’(Taught))

(SELECT ssn
From Professor)
EXCEPT
(SELECT ssn
From Taught T
Where T.crscode = ‘CSC7710’)

SQL 40
8. Return the professor who earns the highest
salary. (Only SQL)

Professor(ssn, profname, status, salary)


Course(crscode, crsname, credits)
Taught(crscode, semester, ssn)

SELECT *
FROM Professor
WHERE salary = (
(SELECT MAX(salary)
FROM Professor P
)

SQL 41
9. Select name of those professors who taught
less than 40 credits. (Only SQL)

Professor(ssn, profname, status, salary)


Course(crscode, crsname, credits)
Taught(crscode, semester, ssn)

SELECT profname
FROM Professor
WHERE ssn IN(
SELECT T.ssn
FROM Taught T, Course C
WHERE T.crscode = C.crscode
GROUP BY ssn
HAVING SUM(C.credits) < 40
)

SQL 42

You might also like