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
    -> ); +--------------+---------------+--------+--------+ ...

Get Sams Teach Yourself MySQL now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.