It is possible to read data from multiple operations in a given order by nesting queries. Nested queries contain what is called a subquery.
Subquery: Explanation
- A subquery is a query that is used in SQL statements; most commonly, this is another query.
- The query containing the subquery is called the outer query.
- In this context, the subquery is also referred to as the inner query.

A subquery can be used to achieve the following:
Make a SELECT statement more readable.
Improve the performance of a SELECT statement, however, with a perfect optimizer, this should not be necessary.
Formulate a SELECT statement that cannot be formulated (or only with difficulty) without a subquery. For example, it is not possible to put aggregate expressions in the WHERE clause of a SELECT statement, unless they are part of a subquery.
There are different types of subqueries:
Expression subqueries return exactly one row; quantified predicate subqueries may return zero or multiple rows.
Uncorrelated subqueries are complete SELECT statements that may be run on their own. Correlated subqueries are incomplete and must refer to the outer query.
These two determinations (expression versus quantified predicate; uncorrelated versus correlated) are independent. This gives four possible types of subqueries.
Note
Differences Between Existence and Quantified Predicate Subqueries
- Expression Subquery
An expression subquery returns exactly one row (CarID values are unique). Boolean expressions may be used to compare against the subquery.
Code Snippet12345SELECT * FROM Owner WHERE OwnerID = (SELECT Owner FROM Car WHERE CarID = ꞌF08ꞌ);- Quantified Predicate Subquery
A quantified predicate subquery may return zero or many rows (there may be any number of owners in the city of Wiesloch).
Boolean expressions may not be used because one value cannot be equal to (or greater, or less than) multiple values. IN and EXISTS may be used instead.
Code Snippet12345SELECT * FROM Car WHERE Owner IN (SELECT OwnerID FROM Owner WHERE City = ꞌWieslochꞌ);
Uncorrelated Versus Correlated Subquery
- Uncorrelated Subquery
An uncorrelated subquery makes no reference to the outer query.
Code Snippet12345SELECT * FROM Car WHERE Owner IN (SELECT OwnerID FROM Owner WHERE City = 'Wiesloch');- Correlated Subquery
A correlated subquery refers to the outer query.
Code Snippet123456SELECT * FROM Car c WHERE EXISTS (SELECT * FROM Owner o WHERE o.OwnerID = c.Owner AND o.City = 'Wiesloch');