Subqueries: Scalar, IN, EXISTS, Inline Views
A subquery is a SELECT written in parentheses. Its use depends on where it is written and how many rows and columns it returns.
| Kind | Position | Returns |
|---|---|---|
| Scalar subquery | A value position in SELECT or WHERE | 1 row, 1 column (NULL if none) |
IN, EXISTS | WHERE | True or false for the condition |
| Inline view (derived table) | FROM | A result used like a table |
A subquery that references columns of the outer query is a correlated subquery. Read it as being recomputed for each outer row.
Scalar subqueries
Order count and last order date per customer
SELECT c.cust_id, c.cust_nm,
(SELECT COUNT(*) FROM orders o WHERE o.cust_id = c.cust_id) AS orders,
(SELECT MAX(o.ord_dt) FROM orders o WHERE o.cust_id = c.cust_id) AS last_dt
FROM customers c
WHERE c.cust_id BETWEEN 101 AND 110
ORDER BY c.cust_id
A scalar subquery that returns 2 or more rows is an error. To guarantee a single value, use an aggregate function or filter by the primary key.
IN: comparing with a list
VIP customers with canceled orders
SELECT c.cust_id, c.cust_nm
FROM customers c
WHERE c.grade = 'VIP'
AND c.cust_id <= 3000
AND c.cust_id IN (SELECT o.cust_id FROM orders o WHERE o.status = 'CANCELED' AND o.cust_id <= 3000)
ORDER BY c.cust_id
IN keeps an outer row once even if the same value appears several times in the subquery result. Written as a join, the same query repeats the customer row once per canceled order.
EXISTS: asking only whether a row exists
EXISTS (subquery) is true if the subquery returns at least one row. What it SELECTs does not matter, so it is usually written as SELECT 1. The DB can stop once it finds the first row.
VIP customers with canceled orders (EXISTS)
SELECT c.cust_id, c.cust_nm
FROM customers c
WHERE c.grade = 'VIP'
AND c.cust_id <= 3000
AND EXISTS (SELECT 1 FROM orders o WHERE o.cust_id = c.cust_id AND o.status = 'CANCELED')
ORDER BY c.cust_id
NOT EXISTS instead of NOT IN
If the NOT IN subquery result contains even one NULL, the result is 0 rows (NULL and three-valued logic). NOT EXISTS finds "rows without a match" regardless of NULLs.
NOT IN: subquery containing a NULL
SELECT c.cust_id
FROM customers c
WHERE c.cust_id BETWEEN 1 AND 5
AND c.cust_id NOT IN (SELECT NULLIF(x.cust_id, 4) FROM customers x WHERE x.cust_id BETWEEN 2 AND 4)
NOT EXISTS: same meaning regardless of NULLs
SELECT c.cust_id
FROM customers c
WHERE c.cust_id BETWEEN 1 AND 5
AND NOT EXISTS (SELECT 1 FROM customers x
WHERE x.cust_id BETWEEN 2 AND 4
AND NULLIF(x.cust_id, 4) = c.cust_id)
The subquery returns 2, 3, NULL. NOT IN returns 0 rows; NOT EXISTS returns 1, 4, 5.
Inline views
A subquery written in FROM is used like a table. Use it to join or filter a result that was aggregated first. The alias (s below) is required in SQL Server and optional in Oracle and PostgreSQL 16+. To work in all three DBs, always add it.
Aggregate per customer first, then attach customer info
SELECT c.cust_id, c.grade, s.orders, s.total_amt
FROM (SELECT cust_id, COUNT(*) AS orders, SUM(amt) AS total_amt
FROM orders
WHERE cust_id BETWEEN 101 AND 200
GROUP BY cust_id) s
JOIN customers c ON c.cust_id = s.cust_id
WHERE s.orders >= 20
ORDER BY s.total_amt DESC
Writing the same thing with a WITH clause gives it a name and lets you read from top to bottom.
TIP Scalar subqueries,
IN,EXISTS, and joins can express the same result in different shapes, and the optimizer sometimes converts one into another. Check how it runs in the execution plan (tuning scenario 4, 7).
ANY, ALL, and row value comparison are covered in Subquery comparisons; several ways to find the row with the maximum value per group are covered in Rows with the group-wise maximum.