Sub topic 14
Nested and Correlated Subqueries
This chapter assumes you know tables, primary and foreign keys, basic SELECT-FROM-WHERE, and the logic of “there exists” and “for all.” A subquery is a query written inside another SQL query. It lets one query use the result of another query.
Uncorrelated subqueries
An uncorrelated subquery can run independently of the outer query. Its result is computed once conceptually, then used by the outer query.
Suppose the database has these tables:
Student(sid, sname, age)Enrolled(sid, cid)Course(cid, cname)
To find students enrolled in course 10, use IN:
SELECT sname
FROM Student
WHERE sid IN (
SELECT sid
FROM Enrolled
WHERE cid = 10
);The inner query returns student IDs. The outer query finds names whose IDs occur in that result.
EXISTS tests whether a subquery returns at least one row:
SELECT sname
FROM Student s
WHERE EXISTS (
SELECT 1
FROM Enrolled e
WHERE e.sid = s.sid
);Although this query contains s.sid, the subquery is correlated because it refers to a row of the outer query. The database evaluates the condition for each student. A student is selected when at least one matching enrollment exists.
Correlated subqueries
A correlated subquery depends on the current outer row. It is useful when the inner condition must be checked separately for each candidate.
The following query finds students enrolled in every course:
SELECT s.sid, s.sname
FROM Student s
WHERE NOT EXISTS (
SELECT 1
FROM Course c
WHERE NOT EXISTS (
SELECT 1
FROM Enrolled e
WHERE e.sid = s.sid
AND e.cid = c.cid
)
);Read the query from the inside out. The innermost query checks whether the current student is enrolled in the current course. The middle query searches for a course without such an enrollment. The outer NOT EXISTS keeps the student only when no missing course exists.
This is SQL’s common form for a “for all” condition:
- “For every course, the student is enrolled.”
- Equivalent logic: “There does not exist a course in which the student is not enrolled.”
Common errors
IN compares values with a set. EXISTS checks rows, so SELECT 1, SELECT *, and SELECT cid have the same truth result inside EXISTS.
Do not confuse WHERE and HAVING. A subquery in WHERE filters individual rows. A subquery using aggregation may instead compare groups.
Be careful with NOT IN. If its subquery returns NULL, three-valued logic can make the condition unknown for every row. NOT EXISTS is usually safer for “no matching row” tests.
Exercise
What does the outer query require in the double-NOT-EXISTS example?
Show answer
It requires that no course exists for which the current student lacks an enrollment.