HomeMySQL Page 2 - Using Subqueries In MySQL (part 1)
Sub-Zero Code - MySQL
One of the most powerful new features in MySQL 4.1 is subqueries, which make it possible to nest multiple SQL queries within each other. This introductory segment of a two-part tutorial demonstrates how to use this new feature to build sophisticated data retrieval queries, illustrating (among other things) how to use subqueries in WHERE and HAVING clauses, with comparison and logical operators, with aggregate functions, and with inner, left, right and self joins.
Subqueries, as the name suggests, are queries nested inside other queries. They make it possible to use the results of one query directly in the conditional tests or FROM clauses of other queries, and can substantially simplify the task of writing SQL-based applications, by reducing the number of application-level query statements to be executed in a given program.
Subqueries come in many shapes, sizes and forms. The most common one is a SELECT within a SELECT, such that the results of the inner SELECT serve as values for the WHERE clause of the outer SELECT. However, while this is certainly one of the most common uses of subqueries, it's not the only one - as you'll see, you can use subqueries in a number of other places, including within grouped result sets, with comparison and logical operators, with membership tests, in UPDATE and DELETE operations, and within a query's FROM clause. They're a very powerful tool - and properly used, they can let you perform some pretty amazing feats with SQL.
Before proceeding further, be warned that subqueries are still in an experimental stage, and are only available in MySQL 4.1 and above. If you're using an older version of MySQL, the examples in this tutorial will not execute correctly. You can get yourself the latest version of the software, for both Windows and Linux platforms, on the very informative MySQL Web site, at http://www.mysql.com/
If you're not already set up, get yourself a copy of MySQL, install and configure it (the installation documents that come with the binary archive for your platform will tell you how) and then flip the page to meet the tables I'll be using in this tutorial.