SQLite Subqueries
What is a Subquery?
A subquery is a SELECT statement inside another statement. It is written in parentheses, and SQLite runs it first.
This example selects the products that cost more than the average price:
Example
SELECT ProductName, Price
FROM Products
WHERE Price > (SELECT AVG(Price) FROM Products);
Try it Yourself »
Subquery With IN
A subquery can return a list of values for IN. This example selects the products from suppliers in Germany:
Example
SELECT ProductName
FROM Products
WHERE SupplierID IN (
SELECT SupplierID FROM Suppliers
WHERE Country = 'Germany'
);
Try it Yourself »
Subquery in FROM
A subquery in FROM works like a temporary table. It needs an alias. This example finds the average number of products in a category:
Example
SELECT AVG(ProductCount)
FROM (
SELECT CategoryID, COUNT(*) AS ProductCount
FROM Products
GROUP BY CategoryID
) AS t;
Try it Yourself »
Subquery in SELECT
A subquery in the column list must return one value. This example shows each customer with the number of orders the customer has placed:
Example
SELECT CustomerName, (
SELECT COUNT(*) FROM Orders
WHERE Orders.CustomerID = Customers.CustomerID
) AS NumberOfOrders
FROM Customers;
Try it Yourself »
This subquery uses a value from the outer query (Customers.CustomerID), so it runs once for each customer. This is called a correlated subquery.
No ANY and ALL in SQLite
Some databases have the operators ANY and ALL for subqueries. SQLite does not have them, but you can get the same result in other ways:
| Instead of | Write |
|---|---|
x = ANY (subquery) | x IN (subquery) |
x > ALL (subquery) | x > (SELECT MAX(...) ...) |
x > ANY (subquery) | x > (SELECT MIN(...) ...) |
Example
Select the products that cost more than every product in category 2:
SELECT ProductName, Price
FROM Products
WHERE Price > (
SELECT MAX(Price) FROM Products
WHERE CategoryID = 2
);
Try it Yourself »