Skip to Content
Learning SQL, 3rd Edition
book

Learning SQL, 3rd Edition

by Alan Beaulieu
March 2020
Beginner
380 pages
9h 44m
English
O'Reilly Media, Inc.
Book available
Content preview from Learning SQL, 3rd Edition

Chapter 9. Subqueries

Subqueries are a powerful tool that you can use in all four SQL data statements. In this chapter, I’ll show you how subqueries can be used to filter data, generate values, and construct temporary data sets. After a little experimentation, I think you’ll agree that subqueries are one of the most powerful features of the SQL language.

What Is a Subquery?

A subquery is a query contained within another SQL statement (which I refer to as the containing statement for the rest of this discussion). A subquery is always enclosed within parentheses, and it is usually executed prior to the containing statement. Like any query, a subquery returns a result set that may consist of:

  • A single row with a single column

  • Multiple rows with a single column

  • Multiple rows having multiple columns

The type of result set returned by the subquery determines how it may be used and which operators the containing statement may use to interact with the data the subquery returns. When the containing statement has finished executing, the data returned by any subqueries is discarded, making a subquery act like a temporary table with statement scope (meaning that the server frees up any memory allocated to the subquery results after the SQL statement has finished execution).

You already saw several examples of subqueries in earlier chapters, but here’s a simple example to get started:

 mysql> SELECT customer_id, first_name, last_name     -> FROM customer     -> WHERE customer_id ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning SQL

Learning SQL

Ben Forta
Practical SQL

Practical SQL

Anthony DeBarros
Head First SQL

Head First SQL

Lynn Beighley

Publisher Resources

ISBN: 9781492057604Errata Page