MySQL Reference Manual for version 4.0.18.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

13.1.8 Subquery Syntax

A subquery is a SELECT statement inside another statement. For example:

 
SELECT * FROM t1 WHERE column1 = (SELECT column1 FROM t2);

In the above example, SELECT * FROM t1 ... is the outer query (or outer statement), and (SELECT column1 FROM t2) is the subquery. We say that the subquery is nested in the outer query, and in fact it's possible to nest subqueries within other subqueries, to a great depth. A subquery must always be inside parentheses.

Starting with version 4.1, MySQL supports all subquery forms and operations which the SQL standard requires, as well as a few features which are MySQL-specific. The main advantages of subqueries are:

With earlier MySQL versions it was necessary to work around or avoid subqueries, but people starting to write code now will find that subqueries are a very useful part of the toolkit.

Here is an example statement which shows the major points about subquery syntax as specified by the SQL standard and supported in MySQL.

 
DELETE FROM t1
WHERE s11 > ANY
 (SELECT COUNT(*) /* no hint */ FROM t2
 WHERE NOT EXISTS
  (SELECT * FROM t3
   WHERE ROW(5*t2.s1,77)=
    (SELECT 50,11*s1 FROM t4 UNION SELECT 50,77 FROM
     (SELECT * FROM t5) AS t5)));

For MySQL versions prior to 4.1, most subqueries can be successfully rewritten using joins and and other methods. See section 13.1.8.11 Rewriting Subqueries for Earlier MySQL Versions.

13.1.8.1 The Subquery as Scalar Operand  
13.1.8.2 Comparisons Using Subqueries  
13.1.8.3 Subqueries with ANY, IN, and SOME  
13.1.8.4 Subqueries with ALL  
13.1.8.5 Correlated Subqueries  
13.1.8.6 EXISTS and NOT EXISTS  
13.1.8.7 Row Subqueries  
13.1.8.8 Subqueries in the FROM clause  
13.1.8.9 Subquery Errors  
13.1.8.10 Optimizing Subqueries  
13.1.8.11 Rewriting Subqueries for Earlier MySQL Versions  


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

This document was generated by rdg (Feb 25 2004) using texi2html