How Do Subselects Work? (Part 3 of 3)
Subselects are located within a WHERE or HAVING clause. This statement is called the outer query.The subselect (also known as a subquery) is enclosed in parentheses and is called the inner query.
For simplicity, we will show it in the WHERE clause in our examples.
Remember, whatever we say about using it in the WHERE clause also applies to the HAVING clause.
> Some subqueries give a list of values that are used as input to the outer query.
> Some subqueries produce a value that the outer query uses with a comparison operator.
> Some subqueries return a value of true or false.
A subselect must:
> Be a single select statement (no JOINS or UNIONS), but may contain another subselect.
> Start and end with left and right parentheses without a semicolon (;) between the parentheses. The entire statement from select to subselect must be terminated with only one semicolon at the end.
> Reference only column names in the subselect FROM table or FROM tables of outer selects.
> Have no ORDER BY in the subselect since a subselect produces only intermediate results.
If a table appears in an inner select, but does not appear in the outer select (such as in the FROM clause), then columns from that table can not be included in the final result.
Sample WHERE formats are:
WHERE test_variable operator (subquery)
WHERE test_variable [NOT] IN (subquery)
WHERE test_variable operator ANY (subquery)
WHERE test_variable operator ALL (subquery)
WHERE [NOT] EXISTS (subquery)