| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
In its simplest form (the scalar subquery as opposed to the
row or table subqueries which will be discussed later),
a subquery is a simple operand. Thus you can use it wherever a column value
or literal is legal, and you can expect it to have those characteristics
that all operands have: a data type, a length, an indication whether it can
be NULL, and so on.
For example:
CREATE TABLE t1 (s1 INT, s2 CHAR(5) NOT NULL); SELECT (SELECT s2 FROM t1); |
The subquery in the above SELECT has a data type of CHAR,
a length of 5, a character set and collation equal to the defaults in
effect at CREATE TABLE time, and an indication that the value in
the column can be NULL. In fact almost all subqueries can be
NULL, because if the table is empty -- as in the example -- then
the value of the subquery will be NULL.
There are few restrictions.
SELECT, INSERT, UPDATE, DELETE,
SET, or DO.
SELECT can contain:
DISTINCT, GROUP BY, ORDER BY, LIMIT,
joins, hints, UNION constructs, comments, functions, and so on.
So, when you see examples in the following sections that contain the rather
Spartan construct (SELECT column1 FROM t1), imagine that your own
code will contain much more diverse and complex constructions.
For example, suppose we make two tables:
CREATE TABLE t1 (s1 INT); INSERT INTO t1 VALUES (1); CREATE TABLE t2 (s1 INT); INSERT INTO t2 VALUES (2); |
Then perform a SELECT:
SELECT (SELECT s1 FROM t2) FROM t1; |
The result will be 2 because there is a row in t2, with a
column s1, with a value of 2.
The subquery may be part of an expression. If it is an operand for a function, don't forget the parentheses. For example:
SELECT UPPER((SELECT s1 FROM t1)) FROM t2; |
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |