an empty result set. The expression is unknown (that is, NULL) if the subquery produces no rows. An
error occurs if the subquery produces multiple rows because a row subquery can return at most one
row.
The expressions
equivalent. The row constructor and the row returned by the subquery must contain the same number
of values.
A row constructor is used for comparisons with subqueries that return two or more columns. When
a subquery returns a single column, this is regarded as a scalar value and not as a row, so a row
constructor cannot be used with a subquery that does not return at least two columns. Thus, the
following query fails with a syntax error:
SELECT * FROM t1 WHERE ROW(1) = (SELECT column1 FROM t2)
Row constructors are legal in other contexts. For example, the following two statements are
semantically equivalent:
SELECT * FROM t1 WHERE (column1,column2) = (1,1);
SELECT * FROM t1 WHERE column1 = 1 AND column2 = 1;
Prior to MySQL 5.0.26, only the second of the preceding two expressions could be optimized. (Bug
#16081)
The following query answers the request, "find all rows in table
SELECT column1,column2,column3
FROM t1
WHERE (column1,column2,column3) IN
(SELECT column1,column2,column3 FROM t2);
13.2.9.6. Subqueries with
If a subquery returns any rows at all,
FALSE. For example:
SELECT column1 FROM t1 WHERE EXISTS (SELECT * FROM t2);
Traditionally, an
or anything at all. MySQL ignores the
column1
difference.
For the preceding example, if
condition is TRUE. This is actually an unlikely example because a
EXISTS
almost always contains correlations. Here are some more realistic examples:
• What kind of store is present in one or more cities?
SELECT DISTINCT store_type FROM stores
WHERE EXISTS (SELECT * FROM cities_stores
• What kind of store is present in no cities?
SELECT DISTINCT store_type FROM stores
WHERE NOT EXISTS (SELECT * FROM cities_stores
• What kind of store is present in all cities?
SELECT DISTINCT store_type FROM stores s1
WHERE NOT EXISTS (
SELECT * FROM cities WHERE NOT EXISTS (
SELECT * FROM cities_stores
WHERE cities_stores.city = cities.city
Subquery Syntax
and
(1,2)
ROW(1,2)
or
EXISTS
NOT EXISTS
EXISTS subquery
subquery starts with
EXISTS
contains any rows, even rows with nothing but
t2
WHERE cities_stores.store_type = stores.store_type);
WHERE cities_stores.store_type = stores.store_type);
are sometimes called row constructors. The two are
is TRUE, and
*, but it could begin with
SELECT
list in such a subquery, so it makes no
SELECT
1102
that also exist in table t2":
t1
NOT EXISTS subquery
SELECT 5
NULL
[NOT] EXISTS
is
or
SELECT
values, the
subquery
Need help?
Do you have a question about the 5.0 and is the answer not in the manual?
Questions and answers