A subquery is a SELECT
- FROM
- WHERE
expression that is nested within another query.
SQL provides a mechanism for the nesting of subqueries.
Set membership
SQL allows testing tuples for membership in a relation, using IN
or NOT IN
clause.
Examples
- Name all instructors whose name is neither “Mozart” nor “Einstein”
- Find all the courses taught in the Fall 2009 semester, but not in the Spring 2010 semester
- Find the total number of distinct students who have taken course sections taught by the instructor with ID
10101
- As seen in the example query below, it is possible to test for membership in an arbitrary relation.
Set comparison
SOME
clause
SOME
clause can check if the predicate is satisfied by at least one tuple in the relation.
F <comp> SOME r
such that , where= SOME
IN
, however<> SOME
NOT IN
Example
Find names of instructors with salary greater than that of some (at least one) instructor in the Biology department
ALL
clause
ALL
clause can check if the predicate is satisfied by all of the tuples in the relation.
F <comp> ALL r
such that , where<> ALL
NOT IN
, however= ALL
IN
Example
Find the names of all instructors whose salary is greater the salary of all instructors in the Biology department
Test for empty relations
The EXISTS
construct returns the value TRUE
if the argument subquery is nonempty.
EXISTS r
NOT EXISTS r
Example
- Find all students who have taken all courses offered in the Biology department
- Note that
- This query cannot be written using
= ALL
and its variants
Test for the absence of duplicate tuples
The UNIQUE
construct tests whether a subquery has any duplicate tuples in its result.
It evaluates to TRUE
if a given subquery contains no duplicates.
Example
- Find all courses that were offered at most once in 2017
Subqueries in the FROM
clause
Since any SELECT
- FROM
- WHERE
clause returns a relation as a result, it can be inserted into another SELECT
- FROM
- WHERE
aanywhere that a relation can appear.
Example
Find the average instructors’ salaries of those departments where the average salary is greater than 42000
- Since the subquery in the
FROM
clause computes the average salary,HAVING
query is not required; the predicate is rather inside theWHERE
clause of the outer query. - The above query is equivalent to
WITH
clause
The WITH
clause provides a way of defining a temporary relation whose definition is available only to the query in which the WITH
clause occurs.
Examples
- Find all departments with the maximum budget
- Find all departments where the total salary is greater than the average of the total salary at all departments
Scalar subquery
Scalar subqeury is used where a single value is expected. It incurs a runtime error if the subquery returns more than one result tuple.
Example
- Find all departments, along with the number of instructors, in each department