Sub topic 1
A Quick Refresher on Subqueries in WHERE
Correlated subqueries and EXISTS build on one idea: a query nested inside the WHERE clause of another query. This chapter reviews that idea so the later chapters can add to it. You will see the shapes of subquery results, the operators that accept them, and the errors people hit most often. Every subquery here is self-contained. The next chapter changes that.
Prerequisites
This chapter assumes you can already do the following:
- Write
SELECTstatements withWHEREandORDER BY. - Use
INNER JOINandLEFT JOIN. - Use aggregate functions such as
COUNT,AVG, andMAX. - Give tables short aliases, as in
FROM orders o. - Treat
NULLas a missing value that is neither equal nor unequal to anything.
The examples use standard SQL and run on PostgreSQL, MySQL 8, SQL Server, and SQLite. Where behavior differs, the text says so.
The sample data
All chapters in this tutorial use a small shop schema. Create it once and reuse it for every example.
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(50) NOT NULL
);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER,
order_date DATE NOT NULL,
total DECIMAL(10,2) NOT NULL
);
INSERT INTO customers (customer_id, name) VALUES
(1, 'Ada'),
(2, 'Ben'),
(3, 'Chen'),
(4, 'Dana');
INSERT INTO orders (order_id, customer_id, order_date, total) VALUES
(101, 1, '2026-01-05', 50.00),
(102, 1, '2026-02-10', 150.00),
(103, 2, '2026-02-11', 80.00),
(104, 2, '2026-03-01', 20.00),
(105, 3, '2026-03-15', 200.00);Ada has two orders, Ben has two, Chen has one, and Dana has none. The average order total is (50 + 150 + 80 + 20 + 200) / 5 = 100.00. Keep these numbers in mind, because the results below depend on them.
What a subquery in WHERE is
A subquery is a SELECT statement written inside parentheses and placed inside another statement. The statement that contains it is the outer query. In this chapter the subquery sits in the WHERE clause, where it supplies a value or a list of values for a condition.
SELECT order_id, total
FROM orders
WHERE total > (SELECT AVG(total) FROM orders);The subquery (SELECT AVG(total) FROM orders) computes one number, 100.00. The outer query then behaves as if you had written WHERE total > 100.00. The result is orders 102 (150.00) and 105 (200.00).
The main reason to use a subquery is that you cannot write the number yourself. Averages and maximums change as data changes, and the subquery recomputes them every time the statement runs.
The shape of the result decides what you can do
Whether a subquery is allowed depends on how many rows and columns it returns. Check the shape first, and the operator follows from it.
| Subquery returns | Name | Operators that accept it |
|---|---|---|
| One row, one column | Scalar subquery | `=`, `<>`, `<`, `<=`, `>`, `>=` |
| Many rows, one column | Column subquery | `IN`, `NOT IN`, `ANY`, `ALL`, `EXISTS` |
| Any number of rows and columns | Table subquery | `EXISTS`, or `FROM` as a derived table |
EXISTS appears in two rows because it ignores what the subquery returns and only asks whether any row came back. A later chapter covers that in detail.
Scalar subqueries with comparison operators
A scalar subquery returns exactly one value. You can place it on either side of a comparison.
SELECT order_id, customer_id, order_date
FROM orders
WHERE order_date = (SELECT MAX(order_date) FROM orders);This returns order 105, the most recent order. An aggregate without GROUP BY always produces exactly one row, so MAX, MIN, AVG, SUM, and COUNT are the usual source of scalar subqueries.
A scalar subquery can also look up a single row by a key.
SELECT order_id, total
FROM orders
WHERE customer_id = (SELECT customer_id FROM customers WHERE name = 'Ada');This works because exactly one customer is named Ada. The database does not know that. If the data later contained two customers named Ada, the statement would start failing. Use a scalar subquery on a lookup like this only when a primary key or unique constraint guarantees one row.
Column subqueries with IN
When the subquery can return several rows, use IN. The condition is true when the outer value equals any value in the list.
SELECT customer_id, name
FROM customers
WHERE customer_id IN (
SELECT customer_id
FROM orders
WHERE total > 100
);The inner query yields the list (1, 3), because orders 102 and 200 belong to customers 1 and 3. The outer query returns Ada and Chen. Ada appears once even though she could have several large orders, because IN only tests membership. It does not multiply rows the way a join does.
NOT IN negates the test. It returns customers whose id is not in the list.
SELECT customer_id, name
FROM customers
WHERE customer_id NOT IN (
SELECT customer_id
FROM orders
);On this data it returns Dana. It works here only because orders.customer_id contains no NULL. A later chapter shows what happens when it does.
ANY and ALL
ANY and ALL combine a comparison operator with a column subquery.
SELECT order_id, total
FROM orders
WHERE total > ALL (
SELECT total
FROM orders
WHERE customer_id = 2
);> ALL means greater than every value in the list. Ben's totals are 80.00 and 20.00, so the query returns orders 102 (150.00) and 105 (200.00). = ANY is equivalent to IN. The same NULL caution applies to ALL, and you will see it again later.
How the database evaluates an uncorrelated subquery
All the subqueries above are uncorrelated. They do not mention any column of the outer query, so each one could be run on its own and give the same answer. Conceptually the database runs the inner query once, keeps the result, and then evaluates the outer query against that result.
The diagram shows the logical model. Real optimizers are free to reorder work, convert the subquery into a join, or cache results, as long as the answer matches. This logical model is enough for now. The next chapter shows what changes when the inner query depends on the current outer row, because then it cannot run just once.
You can tell a subquery is uncorrelated with a simple test: copy the text inside the parentheses, paste it into a separate query window, and run it. If it runs and returns a sensible result, it is uncorrelated. If it fails with an error such as "column not found" for an outer table's alias, it refers to the outer query.
Three-valued logic still applies
A WHERE clause keeps a row only when the condition is TRUE. Conditions can also be FALSE or UNKNOWN, and UNKNOWN rows are dropped just like FALSE ones. Subqueries produce UNKNOWN in two situations that surprise people.
First, a scalar subquery that returns no rows is treated as NULL.
SELECT order_id, total
FROM orders
WHERE total > (SELECT total FROM orders WHERE customer_id = 99);No customer 99 exists, so the subquery returns zero rows and becomes NULL. The comparison total > NULL is UNKNOWN for every row, and the query returns nothing. No error is raised, so a typo in a lookup can silently empty your result.
Second, an aggregate over zero rows returns one row containing NULL for AVG, MAX, MIN, and SUM. COUNT returns 0 instead.
SELECT order_id, total
FROM orders
WHERE total > (SELECT AVG(total) FROM orders WHERE customer_id = 99);This also returns nothing, for the same reason.
Common errors
These mistakes account for most failures with subqueries in WHERE.
- Too many rows for a scalar comparison. Writing
WHERE total > (SELECT total FROM orders WHERE customer_id = 1)makes the subquery return two rows (50.00 and 150.00). PostgreSQL reports "more than one row returned by a subquery used as an expression", and MySQL reports "Subquery returns more than 1 row". SQLite does not raise an error. It silently uses the first row it finds. The fix is to aggregate, as in(SELECT MAX(total) ...), to useANYorALL, or to switch toIN. - Too many columns.
WHERE customer_id IN (SELECT customer_id, total FROM orders)fails becauseINcompares against a single column. Select only the column you compare against. - Mismatched types. Comparing an integer id against a text column inside the subquery either errors or forces a slow implicit conversion, depending on the database. Keep the compared columns the same type.
- Forgetting that duplicates in the list are harmless.
INdoes not needDISTINCTinside the subquery. Adding it rarely helps and can add sort work in some engines. - Using
NOT INagainst a nullable column. This is the subtlest mistake and gets its own chapter. For now, note thatorders.customer_idis nullable in this schema on purpose.
Subquery or join?
Many subqueries in WHERE can be written as joins. The query that finds customers with a large order can be written like this.
SELECT DISTINCT c.customer_id, c.name
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
WHERE o.total > 100;A join returns one output row per matching pair, so a customer with two large orders would appear twice without DISTINCT. A subquery with IN has no such problem. The two forms are equivalent in meaning here, and modern optimizers often plan them identically. Choose based on readability. If you only need columns from the outer table and are testing a condition on another table, a subquery states that intent directly. If you need columns from both tables in the output, you need a join. A later chapter compares the options in detail.
Where subqueries can appear
Subqueries are not limited to WHERE. A scalar subquery can sit in the SELECT list, and a table subquery can sit in FROM as a derived table. This tutorial concentrates on WHERE, with one detour into the SELECT list when comparing a row to an aggregate. The rules you learned above about shape (one value, one column, or a table) apply in every position.
What comes next
Every subquery in this chapter could run alone, and the database could evaluate it once. The next chapter removes that property by letting the inner query refer to a column of the outer row. That one change makes the inner query's result depend on which outer row is being examined, and it is the basis for EXISTS, NOT EXISTS, and per-row aggregates.
Exercise
Using the sample data, write a query that returns the names of customers who have placed at least one order with a total below 30. Use a subquery with IN. What does it return?
Show answer
SELECT name FROM customers WHERE customerid IN (SELECT customerid FROM orders WHERE total < 30); The only order below 30 is order 104 (20.00), which belongs to customer 2, so the query returns Ben.
Exercise
The query SELECT orderid FROM orders WHERE total = (SELECT total FROM orders WHERE customerid = 2) fails or behaves unpredictably. Why, and how would you change it to return orders whose total equals the largest total among Ben's orders?
Show answer
Ben has two orders (80.00 and 20.00), so the subquery returns two rows, but = needs a single value. Use an aggregate to guarantee one row: SELECT orderid FROM orders WHERE total = (SELECT MAX(total) FROM orders WHERE customerid = 2); This returns order 103.
Exercise
What does SELECT orderid FROM orders WHERE total < (SELECT MIN(total) FROM orders WHERE customerid = 99) return, and why is there no error?
Show answer
It returns no rows. No customer 99 exists, so MIN over zero rows returns NULL. The comparison total < NULL is UNKNOWN for every row, and WHERE keeps only rows where the condition is TRUE.