• Learning MySQL By Example
  • Introduction
  • 1. How to Retrieve Data From a Single Table
  • 2. How to Retrieve Data from Multiple Tables
  • 3. Using Functions
  • 4. How to Insert, Update, Delete Data in Tables
  • 5. Summary Queries and Aggregate Functions
  • 6. Working With Subqueries
  • 7. SQL Views
  • 8. SQL Indexes
  • Glossary
  • Index
  • Download
  • Translations
  • 6.1

    The Subquery In a SELECT Statement

    The Subquery in a SELECT Statement

    • A subquery is a SELECT statement coded within another SELECT statement.
    • A subquery can return a single value or a list of values.
    • A subquery can return multiple columns.
    • A subquery cannot make use of the ORDER BY clause
    • A subquery can be nested within another subquery
    • You can use a subquery in a WHERE, HAVING, FROM and SELECT clause.

    Code Sample:

    1    USE world;
    2    SELECT name, population 
    3    FROM city 
    4    WHERE CountryCode IN 
    5        (SELECT code 
    6        FROM country 
    7        WHERE region = 'Caribbean') 
    8    ORDER BY population 
    9    LIMIT 5;

    Results:

    sub_01.png

    SELECT name, population

    FROM city

    WHERE CountryCode IN

    (SELECT code

     FROM country

     WHERE region = 'Caribbean')

    This content is provided to you freely by EdTech Books.

    Access it online or download it at https://edtechbooks.org/learning_mysql/the_subquery_in_a_se.