Subquery Basics

What is a Subquery?

A subquery (inner query, nested query) is a SELECT written inside another statement, in parentheses. The inner query runs and its result is used by the outer query.

Example

Products that cost more than the average price:

SELECT ProductName, Price
FROM Products
WHERE Price > (SELECT AVG(Price) FROM Products);

Result: 3 rows

ProductNamePrice
Basmati Rice 5kg12.5
Olive Oil 1L9.99
Espresso Beans 1kg18

Kinds of Subqueries

KindReturnsUsed with
Scalarone value (1 row, 1 column)= > <, in SELECT list
Row / columnone column, many rowsIN, ANY, ALL
Tablemany rows and columnsFROM (derived table)
Correlateddepends on the outer rowEXISTS, comparisons

Note: A subquery used with = must return at most one row, otherwise the query fails (or, in SQLite, silently uses the first row).