A subquery is a select statement that is nested inside another select, insert, update, or delete statement, inside a conditional statement, or inside another subquery.
You can also express subqueries as join operations.
Subqueries, also called inner queries, appear within a where or having clause of another SQL statement, or in the select list of a statement.
You can use subqueries to handle query requests that are expressed as the results of other queries. A statement that includes a subquery operates on rows from one table, based on its evaluation of the subquery’s select list, which can refer either to the same table as the outer query, or to a different table. In Transact-SQL, you can use a subquery almost anywhere an expression is allowed, if the subquery returns a single value. A case expression can also include a subquery.
For example, this subquery lists the names of all authors whose royalty split is more than $75:
select au_fname, au_lname from authors where au_id in (select au_id from titleauthor where royaltyper > 75)
select statements that contain one or more subqueries are sometimes called nested queries or nested select statements.
The result of a subquery that returns no values is NULL. If a subquery returns NULL, the query failed.
This is an example of how to find the books that have the same price as Straight Talk About Computers.
First find the price of Straight Talk:
select price from titles where title = "Straight Talk About Computers"
price ------------- $19.99 (1 row affected)
Use the results of the first query in a second query to find all the books that cost the same as Straight Talk:
select title, price from titles where price = $19.99
title price ------------------------------------------ ----- The Busy Executive’s Database Guide 19.99 Straight Talk About Computers 19.99 Silicon Valley Gastronomic Treats 19.99 Prolonged Data Deprivation: Four Case Studies 19.99
You can use a subquery to receive the same results in only one step:
select title, price from titles where price = (select price from titles where title = "Straight Talk About Computers")
title price --------------------------------------- ----- The Busy Executive’s Database Guide 19.99 Straight Talk About Computers 19.99 Silicon Valley Gastronomic Treats 19.99 Prolonged Data Deprivation: Four Case Studies 19.99