Careeroza
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
| ProductName | Price |
|---|---|
| Basmati Rice 5kg | 12.5 |
| Olive Oil 1L | 9.99 |
| Espresso Beans 1kg | 18 |
Kinds of Subqueries
| Kind | Returns | Used with |
|---|---|---|
| Scalar | one value (1 row, 1 column) | = > <, in SELECT list |
| Row / column | one column, many rows | IN, ANY, ALL |
| Table | many rows and columns | FROM (derived table) |
| Correlated | depends on the outer row | EXISTS, comparisons |
Note: A subquery used with = must return at most one row, otherwise the query fails (or, in SQLite, silently uses the first row).