Sub topic 17
“For All” Queries in SQL and Table Constraints
Assume you know basic SELECT, joins, primary keys, and first-order logic. In particular, ∀ means “for every,” and ∃ means “there exists.” SQL has no direct FOR ALL operator, so express a universal condition by checking that no counterexample exists.
Expressing “for every” with double `NOT EXISTS`
Suppose Student(sid, sname) and Course(cid, cname) describe students and courses. To find students enrolled in every course, use this pattern:
SELECT s.sid, s.sname
FROM Student AS s
WHERE NOT EXISTS (
SELECT 1
FROM Course AS c
WHERE NOT EXISTS (
SELECT 1
FROM Enrolled AS e
WHERE e.sid = s.sid
AND e.cid = c.cid
)
);Read the query from the inside outward:
- The innermost query tests whether student
sis enrolled in coursec. - The middle query finds courses for which that enrollment does not exist.
- The outer query keeps a student only when no such course exists.
Therefore, the query means:
> There does not exist a course for which the student is not enrolled.
This is equivalent to “the student is enrolled in every course.” It also matches relational division:
π_sid,cid(Enrolled) ÷ π_cid(Course)If Course is empty, the condition is true for every student. This is called vacuous truth: no course exists that could violate the requirement.
CREATE TABLE and integrity constraints
A database schema can prevent invalid data instead of relying only on queries. A constraint is a rule that inserted or updated data must satisfy.
CREATE TABLE Student (
sid INT PRIMARY KEY,
sname VARCHAR(80) NOT NULL,
age INT CHECK (age >= 0)
);
CREATE TABLE Course (
cid INT PRIMARY KEY,
cname VARCHAR(100) NOT NULL
);
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
);| Constraint | Purpose |
|---|---|
| `PRIMARY KEY` | Uniquely identifies each row and disallows `NULL` |
| `FOREIGN KEY` | Requires a matching row in the referenced table |
| `NOT NULL` | Requires a value |
| `CHECK` | Requires a condition to be true |
The composite primary key (sid, cid) prevents duplicate enrollment pairs. The foreign keys enforce referential integrity. With ON DELETE CASCADE, deleting a student or course also deletes its related enrollment rows.
Exercise
Why does the universal query keep every student when the Course table has no rows?
Show answer
There is no course that can serve as a counterexample, so “no course is missing” is true for every student.