Tom Kelliher, CS 318
Feb. 13, 15, 2002
We've seen insert already --- no need to review.
Just touching on the basics, refer to the text and PostgreSQL docs for more advanced material.
Collect homework.
Read 10.1--4.
Relational algebra.
PostgreSQL and PHP.
SELECT S.Name FROM Student S WHERE S.Status = 'Senior';
FROM
clause.
WHERE
clause individually to resulting tuples.
SELECT
clause.
SELECT S.Name FROM Student S, Transcript T WHERE S.Id = T.StuId AND T.CrsCode = 'CS318';Use of tuple variables.
SELECT E1.Id, E1.Salary - E2.Salary FROM Employee E1, Employee E2 WHERE E1.Supervisor = E2.Id AND E1.Sal >= 2 * E2.Sal;
SELECT DISTINCT S.Name FROM Student S, Transcript T WHERE S.Id = T.StuID AND T.CrsCode LIKE 'CS%';Alternative for retrieving students who have taken topics courses:
WHERE S.Id = T.StuID AND T.CrsCode IN ('CS318', 'CS319');
(SELECT S.Id FROM Student S) EXCEPT (SELECT T.StuId FROM Transcript T WHERE T.Semester = 'F2001');Version 2 using
NOT IN
:
SELECT S.Id FROM Student S WHERE S.Id NOT IN (SELECT T.StuId FROM Transcript T WHERE T.Semester = 'F2001');Sub-query.
Version 3 using NOT EXISTS
:
SELECT S.Id FROM Student S WHERE NOT EXISTS (SELECT * FROM Transcript T WHERE S.Id = T.StuId AND T.Semester = 'F2001');Correlated sub-query.
SELECT P.Id, TR.CrsCode, TR.StuId FROM Transcript TR, Professor P WHERE TR.Semester <> 'S2002' AND TR.CrsCode IN (SELECT TE.CrsCode FROM Teaching TE WHERE P.Id = TE.ProfId AND TE.Semester = 'S2002');
SELECT S1.Name FROM Student S1 WHERE S1.Id >ALL (SELECT S2.Id FROM Student S2);Alternative using aggregate function
MAX
:
SELECT S1.Name FROM Student S1 WHERE S1.Id > (SELECT MAX(S2.Id) FROM Student S2);These will both return empty relations. Why?
SELECT COUNT(S.Id) FROM Student S;
SELECT AVG(E.Sal) FROM Employee E WHERE E.Dept = 'Accounting';How would you retrieve the ID of the employee with the highest salary?
SELECT F.FoodType, Count(F.Name) as Count, AVG(F.Calories) AS AvgCalories FROM Food F WHERE F.Calories < 100 GROUP BY F.FoodType HAVING COUNT(F.Name) >= 20;Query evaluation strategy II:
FROM
clause.
WHERE
clause individually to resulting tuples.
GROUP BY
clause to partition tuples into groups.
HAVING
clause to winnow out groups.
SELECT
clause.
123456789
.
DELETE FROM Student WHERE Id = '123456789';
DELETE FROM Student WHERE Id IN (SELECT T.StuId FROM Transcript T WHERE T.CrsCode = 'CS318' AND T.Semester = 'S2002');
Give a 10% raise to all faculty who teach the most ornery student, whose
ID is 123456789
.
UPDATE Professor SET Salary = 1.1 * Salary WHERE ID IN (SELECT TE.ProfID FROM Teaching TE, Transcript TR WHERE TE.CrsCode = TR.CrsCode AND TR.StuId = '123456789');