Sub topic 17
Nested and correlated subqueries
This chapter assumes you can read a basic SELECT ... FROM ... WHERE statement, know joins, and have seen the three-valued logic rule that a comparison with NULL gives UNKNOWN. The examples use Student(sid, sname, age), Course(cid, cname) and Enrolled(sid, cid).
What a subquery is
A subquery is a SELECT written inside another query, in parentheses. It can appear in WHERE, FROM or SELECT. What the outer query does with it depends on the shape of its result:
- A table with one column is a set of values, used with
IN,ANY,ALL. - A table with any shape is tested for emptiness with
EXISTS. - A single value (one row, one column) is a scalar and can be used with
=,<and so on.
A subquery is uncorrelated if it never mentions the outer query's tables. It can be evaluated once and its result reused. It is correlated if it refers to a variable from the outer query. Then it conceptually runs once for each outer row.
IN and NOT IN
IN tests membership in the subquery's result.
SELECT sname
FROM Student
WHERE sid IN (SELECT sid FROM Enrolled WHERE cid = 10);The inner query returns the sid values enrolled in course 10. The outer query keeps students whose sid is in that set. This is equivalent to a join, with one difference: the join returns a student once per matching Enrolled row, while IN returns each student at most once per Student row.
EXISTS and correlation
EXISTS (subquery) is true when the subquery returns at least one row. The columns selected do not matter, so SELECT 1 or SELECT * are both common.
SELECT s.sname
FROM Student s
WHERE EXISTS (
SELECT 1
FROM Enrolled e
WHERE e.sid = s.sid AND e.cid = 10
);The inner query uses s.sid, which belongs to the outer query. That reference makes it correlated. The conceptual evaluation is a nested loop.
Real systems often rewrite this into a join, but the loop model is the one to use when predicting results.
Scope rules
A name in a subquery refers to the nearest enclosing table that has it. Inner tables hide outer ones. An outer query can never see columns of a subquery's tables. If you reuse a table in both queries, give them different aliases (Student s and Student s2). Otherwise an unqualified sid inside the subquery binds to the inner table, and you may silently get an uncorrelated query.
ANY and ALL
op ANY (subquery) is true if the comparison holds for at least one value. op ALL (subquery) is true if it holds for every value.
-- Students older than at least one student named Ravi
SELECT sname FROM Student
WHERE age > ANY (SELECT age FROM Student WHERE sname = 'Ravi');
-- Students at least as old as everyone with a known age
SELECT sname FROM Student
WHERE age >= ALL (SELECT age FROM Student WHERE age IS NOT NULL);| Construct | Equivalent to | Result on an empty subquery |
|---|---|---|
| `x = ANY (S)` | `x IN (S)` | false |
| `x <> ALL (S)` | `x NOT IN (S)` | true |
| `x > ANY (S)` | `x > MIN(S)` | false |
| `x > ALL (S)` | `x > MAX(S)` | true |
| `EXISTS (S)` | S has a row | false |
| `NOT EXISTS (S)` | S has no row | true |
<> ANY is not the same as NOT IN. It is true whenever some value differs from x. The usual mistake is reading <> ANY as "differs from all".
Scalar subqueries
A subquery that returns exactly one value can be used like a constant. If it returns more than one row, the query fails with a runtime error. If it returns zero rows, the value is NULL.
SELECT s.sname
FROM Student s
WHERE (SELECT COUNT(*)
FROM Enrolled e
WHERE e.sid = s.sid) >= 2;This lists students with at least two enrollments. COUNT(*) always returns exactly one row, even when no rows match, so the subquery is safe.
The NOT IN trap
x NOT IN (S) means x <> v1 AND x <> v2 AND .... If any vi is NULL, that term is UNKNOWN, so the whole condition can never be true. The result is an empty table.
-- Enrolled contains (sid=1, cid=10) and (sid=2, cid=NULL)
SELECT cid FROM Course
WHERE cid NOT IN (SELECT cid FROM Enrolled); -- returns no rows
SELECT c.cid FROM Course c
WHERE NOT EXISTS (SELECT 1 FROM Enrolled e WHERE e.cid = c.cid); -- correctNOT EXISTS only asks whether a matching row exists. A NULL cid never equals anything, so it never matches and does no harm.
Subqueries in FROM
A subquery in FROM is a derived table and must have an alias.
SELECT t.cid, t.n
FROM (SELECT cid, COUNT(*) AS n FROM Enrolled GROUP BY cid) AS t
WHERE t.n > 5;It is never correlated with the other tables of the same FROM clause in standard SQL.
Counting results
Several GATE questions ask for the minimum or maximum number of rows returned. A routine that works:
- Decide whether the subquery is correlated.
- For
INorEXISTS, the result is a subset of the outer table, so the maximum is the outer row count and the minimum is often 0. - For
NOT IN, ask whether the inner column can be NULL. If it can, the minimum and maximum may both be 0. - If a join replaces
IN, duplicates in the inner table can raise the count above the outer row count.
Exercise
Student has 5 rows. Enrolled has 3 rows with sid values 1, 1, 2, all non-NULL and all existing in Student. How many rows does SELECT sid FROM Student WHERE sid IN (SELECT sid FROM Enrolled) return, and how many does SELECT s.sid FROM Student s, Enrolled e WHERE s.sid = e.sid return?
Show answer
The IN query returns 2 rows (students 1 and 2, each once). The join returns 3 rows, because student 1 matches two Enrolled rows.
Exercise
Table T(a) holds the values 1 and 2. Table U(b) holds the values 2 and NULL. What does SELECT a FROM T WHERE a NOT IN (SELECT b FROM U) return? What does the same query with NOT EXISTS (SELECT 1 FROM U WHERE U.b = T.a) return?
Show answer
The NOT IN query returns no rows. For a = 1 the test 1 <> 2 AND 1 <> NULL is UNKNOWN, and for a = 2 it is false. The NOT EXISTS query returns the row with a = 1, because only a = 2 has a matching U row.