O'Reilly logo

Sams Teach Yourself MySQL by Chris Newman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Understanding Subqueries

A subquery is a query that is embedded within another query. Subqueries are sometimes also referred to as subselects because one SELECT statement appears within another. Let’s look at how subqueries can be useful.

Filtering by Subquery

You can use the result of a query like you use a list of values with the IN operator to filter a query based on the result of another query. The subquery appears in parentheses after the IN keyword.

The following query fetches all columns from the products table, but only for those product codes that were part of order number 1:

mysql> SELECT *
    -> FROM products
    -> WHERE product_code IN (
    ->   SELECT product_code
    ->   FROM order_lines
    ->   WHERE order_id = 1
    -> ); +--------------+---------------+--------+--------+ ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required