Rechercher dans le manuel MySQL
13.2.11.1 The Subquery as Scalar Operand
In its simplest form, a subquery is a scalar subquery that
returns a single value. A scalar subquery is a simple operand,
and you can use it almost anywhere a single 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 that it can be NULL
, and so on.
For example:
The subquery in this SELECT
returns a single value ('abcde'
) that 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
. Nullability of the value selected by a
scalar subquery is not copied because if the subquery result is
empty, the result is NULL
. For the subquery
just shown, if t1
were empty, the result
would be NULL
even though
s2
is NOT NULL
.
There are a few contexts in which a scalar subquery cannot be
used. If a statement permits only a literal value, you cannot
use a subquery. For example, LIMIT
requires
literal integer arguments, and LOAD
DATA
requires a literal string file name. You cannot
use subqueries to supply these values.
When you see examples in the following sections that contain the
rather spartan construct (SELECT column1 FROM
t1)
, imagine that your own code contains much more
diverse and complex constructions.
Suppose that we make two tables:
Then perform a SELECT
:
The result is 2
because there is a row in
t2
containing a column s1
that has a value of 2
.
A scalar subquery can be part of an expression, but remember the parentheses, even if the subquery is an operand that provides an argument for a function. For example:
Document created the 26/06/2006, last modified the 26/10/2018
Source of the printed document:https://www.gaudry.be/en/mysql-rf-scalar-subqueries.html
The infobrol is a personal site whose content is my sole responsibility. The text is available under CreativeCommons license (BY-NC-SA). More info on the terms of use and the author.
References
These references and links indicate documents consulted during the writing of this page, or which may provide additional information, but the authors of these sources can not be held responsible for the content of this page.
The author This site is solely responsible for the way in which the various concepts, and the freedoms that are taken with the reference works, are presented here. Remember that you must cross multiple source information to reduce the risk of errors.