Sub topic 3
SQL set operations
This chapter assumes you know SELECT, FROM, WHERE, joins, and the set operations union, intersection, and difference. It uses the schema Student(sid, sname, age), Course(cid, cname), and Enrolled(sid, cid).
Set operations
Set operations combine the results of two queries. Both queries must return the same number of columns with compatible types.
SELECT sid FROM Enrolled WHERE cid = 10
UNION
SELECT sid FROM Enrolled WHERE cid = 20;UNION removes duplicate rows. INTERSECT keeps rows found in both results. EXCEPT keeps rows from the first result that are missing from the second. UNION ALL keeps duplicates.
Nested and correlated subqueries
A nested subquery runs once. A correlated subquery refers to the current outer row, so it runs once for each outer row.
SELECT s.sid
FROM Student s
WHERE NOT EXISTS (SELECT 1 FROM Enrolled e WHERE e.sid = s.sid);Aggregation, GROUP BY and HAVING
WHERE filters rows before grouping. HAVING filters groups after aggregation.
SELECT cid, COUNT(*) AS n
FROM Enrolled
GROUP BY cid
HAVING COUNT(*) >= 10;NULLs and three-valued logic
A comparison with NULL evaluates to UNKNOWN. WHERE keeps only rows whose condition is TRUE. COUNT(*) counts all rows, while COUNT(age) skips NULL values.
'For all' queries in SQL
SQL has no division operator. Write "for all" as "there is no course the student is not enrolled in":
SELECT s.sid
FROM Student s
WHERE NOT EXISTS (
SELECT *
FROM Course c
WHERE NOT EXISTS (
SELECT *
FROM Enrolled e
WHERE e.sid = s.sid AND e.cid = c.cid
)
);CREATE TABLE and constraints
CREATE TABLE Enrolled (
sid INT,
cid INT,
PRIMARY KEY (sid, cid),
FOREIGN KEY (sid) REFERENCES Student(sid) ON DELETE CASCADE,
FOREIGN KEY (cid) REFERENCES Course(cid) ON DELETE CASCADE
);The primary key forbids duplicate and NULL key values. The foreign keys require each sid and cid to exist in its parent table. ON DELETE CASCADE deletes the matching Enrolled rows when a student or course is deleted.
GATE strategies: counting tuples and checking equivalence
To bound the result size, reason about each operand. For UNION, the maximum is the sum of the two row counts. For INTERSECT, the maximum is the smaller count. For EXCEPT, the maximum is the row count of the first query. To show two queries are not equivalent, find one database state where their results differ.
Exercise
Relation R has 4 distinct rows and S has 3 distinct rows, with the same columns. What is the maximum number of rows in R EXCEPT S?
Show answer
4. EXCEPT removes at most the rows of S from R, and S can remove none of them.