A subquery is a parenthesized query enclosed within some outer SQL statement.
Most queries are SELECTs, so this means that a subquery usually takes the
form "(SELECT ...)", nested somewhere inside an expression. Queries return
result sets, or Tables, and the values in such Tables can be used when the
syntax of the outer expression calls for a value of the appropriate <data
type>.
Subqueries make an SQL statement look structured, and indeed it was the
presence of subqueries that gave the original SQL its distinctive look (the
letters SQL used to stand for "Structured Query Language"). Nowadays subqueries
are less essential because there other ways (particularly joins and
UNION/EXCEPT/INTERSECT operators) to reach the same ends.
Nevertheless, they are important because they provide these benefits:
- SQL statements with subqueries are readable. Most people, especially if they are familiar with the role of subordinate clauses in English, can figure that a subquery-containing SQL statement can be read "from the inside out" — that is, they can focus on the subquery's workings first, and then on the separate analysis of the outer statement. Statements with joins, by contrast, must be read all at once.
- Certain types of problems can be stated more concisely, and more efficiently, with subqueries.
-
Subquery Syntax
A subquery is used to specify either a value (the scalar subquery, which re... -
Scalar Subqueries
In general terms, a scalar subquery resembles a scalar function. Remember t... -
Row Subqueries
Row subqueries are similar to scalar subqueries in the one fundamental resp... -
Table Subqueries
We now switch from talking about "one-row" subqueries, to talking about "mu... -
Quantified Comparisons
In our chapters on the various <data type>s, we showed you which of them co... -
Predicates
In addition to quantified comparisons, SQL provides four other predicates t... -
Joins versus Subqueries
Often, SQL statements containing subqueries can be re-formulated as stateme... -
Subquery Examples
The following examples are derived, with much editing, from an SQL applicat... -
Subquery Tips
Make sure your scalar subqueries return a maximum of one row. You can help ... -
Dialects
SQL-89 was very restrictive about subqueries. SQL-92 removed most of the re...