SQL Subqueries: Scalar, IN, EXISTS, ANY and ALL
How to use a query inside another query: scalar subqueries that return one value, IN and EXISTS subqueries that test membership, comparisons with ANY and ALL, subqueries in SELECT, FROM and HAVING, and the edge cases with empty results and NULLs that catch people out.
kvi5hnuCode Sprout team member16 min readOn this page
Some questions need the answer to another question first. "Which products cost more than the average?" needs the average before it can compare. "Which products have been ordered?" needs the list of ordered product IDs. You could run two queries and copy the result of the first into the second by hand, but SQL lets you write the inner question directly inside the outer one. A query nested inside another statement is a subquery.
You've already met a few subqueries: article 16 used EXISTS and IN to find matching and missing rows, and article 18 used (SELECT MAX(price) FROM products) to find the most expensive product. This article covers subqueries systematically: the kinds of result a subquery can return, where each kind can go, the comparison operators ANY and ALL, and the edge cases that turn a reasonable-looking query into a wrong one.
Vocabulary
SELECT name -- outer query
FROM products
WHERE price > (SELECT AVG(price) -- subquery (inner query)
FROM products);
- The outer query is the main statement. The subquery, or inner query, is the
SELECTin parentheses. - A subquery is uncorrelated when it doesn't refer to the outer query. It has one answer, which the database can compute once. Every example in this article is uncorrelated.
- A subquery is correlated when it refers to a column of the outer query, as in
WHERE o.customer_id = c.customer_id. Its answer can differ for each outer row. Correlated subqueries are the topic of the next article.
Subqueries are classified by the shape of their result, and the shape decides where they can be used:
| Kind | Returns | Typical use |
|---|---|---|
| Scalar subquery | one row, one column | anywhere a single value fits: SELECT, WHERE, HAVING, SET |
| Column subquery | many rows, one column | IN, NOT IN, ANY, ALL |
| Row subquery | one row, several columns | row comparisons, such as (a, b) = (SELECT x, y ...) |
| Table subquery | many rows and columns | FROM (a derived table), EXISTS, multi-column IN |
Scalar subqueries
A scalar subquery returns a single value, so it can go anywhere an expression can:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
-- Products priced above the average price, and by how much
SELECT name,
price,
ROUND(price - (SELECT AVG(price) FROM products), 2) AS above_avg_by
FROM products
WHERE price > (SELECT AVG(price) FROM products)
ORDER BY price;
-- A scalar subquery in the SELECT list: each product's share of total stock
SELECT name,
stock,
ROUND(100.0 * stock / (SELECT SUM(stock) FROM products), 1) AS pct_of_stock
FROM products
ORDER BY stock DESC
LIMIT 3;
name | price | above_avg_by
---------------+--------+--------------
Ridge 2 tent | 249.99 | 112.78
Summit 4 tent | 489.00 | 351.79
(2 rows)
name | stock | pct_of_stock
-------------------+-------+--------------
Merino socks | 75 | 44.9
Glow head torch | 40 | 24.0
Trail 30 backpack | 22 | 13.2
(3 rows)
The first query compares each price with the average, 137.21, which the subquery computes. The same subquery appears in the SELECT list, to show the difference. The second query divides each product's stock by the total stock, computed by a subquery in the SELECT list, to get a share.
Notice that you can't write WHERE price > AVG(price): aggregates aren't allowed in WHERE (article 18). The subquery is a separate query with its own FROM, so its aggregate runs over the whole table, independently of the outer query's rows. That's exactly what's needed here.
The two rules of scalar subqueries
A scalar subquery must return at most one row with exactly one column. What happens otherwise is worth knowing exactly:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
\pset null '(null)'
-- No row: the scalar subquery's value is NULL
SELECT (SELECT name FROM products WHERE price > 1000) AS dearest_over_1000;
-- More than one row: an error at run time
SELECT (SELECT name FROM products WHERE category = 'tents') AS a_tent;
-- So a comparison against "zero rows" is unknown, and the row is not returned
SELECT name FROM products
WHERE price > (SELECT price FROM products WHERE category = 'boats');
dearest_over_1000
-------------------
(null)
(1 row)
psql:/workspace/solution.sql:25: ERROR: more than one row returned by a subquery used as an expression
name
------
(0 rows)
- No rows: the value is NULL. This is not an error. In the first query, no product costs more than 1000, so the result is NULL.
- More than one row: a run-time error, "more than one row returned by a subquery used as an expression". There are two tents, so the second query fails. The error depends on the data, not on the query text: the query worked while there was one tent and fails when a second tent is added. A query that "has always worked" can start failing in production.
- Because "no rows" means NULL, a comparison against an empty scalar subquery is unknown, and
WHEREdrops the row. The third query returns nothing, because there are no boats to compare with.
To make a scalar subquery safe, make sure it can't return more than one row: use an aggregate (MAX, COUNT, SUM) or filter on a primary key or a unique column. Adding LIMIT 1 makes the error go away, but it also hides the question of which row you get. If several rows match, LIMIT 1 without ORDER BY picks one arbitrarily. Use it only when you really mean "any one of them", or with an ORDER BY that picks the right one.
A scalar subquery must also return exactly one column. (SELECT name, price FROM ...) in a place that needs one value is a syntax-level error, whatever the data.
IN with a subquery
IN (subquery) tests whether a value is in the column that the subquery returns:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Products that appear on at least one order line
SELECT name
FROM products
WHERE product_id IN (SELECT product_id FROM order_items)
ORDER BY name;
-- The same question as a join repeats a product once per order line
SELECT p.name
FROM products p
JOIN order_items oi ON oi.product_id = p.product_id
ORDER BY p.name;
-- The subquery must return exactly one column
SELECT name FROM products
WHERE product_id IN (SELECT product_id, qty FROM order_items);
name
-------------------
Day 18 backpack
Glow head torch
Merino socks
Ridge 2 tent
Summit 4 tent
Trail 30 backpack
(6 rows)
name
-------------------
Day 18 backpack
Glow head torch
Glow head torch
Merino socks
Merino socks
Merino socks
Ridge 2 tent
Summit 4 tent
Trail 30 backpack
(9 rows)
psql:/workspace/solution.sql:76: ERROR: subquery has too many columns
LINE 2: WHERE product_id IN (SELECT product_id, qty FROM order_items...
^
The first query lists the six products that appear on at least one order line. The second asks the same question with a join, and returns nine rows: the head torch appears twice and the socks three times, once per matching order line. That's the essential difference:
A join multiplies a row by the number of matches.
INandEXISTSonly test whether a match exists, so each outer row appears at most once.
When you only want rows from one table that have a match in another, IN or EXISTS says that directly, and you don't need DISTINCT to undo the duplication. Article 16 called this a semi-join, and also covered NOT IN and its trap: if the subquery returns a NULL, NOT IN returns no rows at all. Use NOT EXISTS for "has no match".
The third query shows that the subquery in IN must return exactly as many columns as there are values on the left. One value on the left, so one column in the subquery.
Multi-column IN
To compare several columns at once, put them in parentheses on both sides:
WHERE (customer_id, placed_on) IN (SELECT customer_id, MIN(placed_on)
FROM orders
GROUP BY customer_id)
This is a row-value comparison: a row matches when both columns equal the corresponding columns of some subquery row. It's supported by PostgreSQL, MySQL, Oracle and SQLite, but not SQL Server, where you write the same test with EXISTS and a correlated subquery (next article). You'll see it run later in this article.
ANY, SOME and ALL
IN only tests equality. To compare with other operators against a set of values, SQL has ANY and ALL:
x > ANY (subquery)is true ifxis greater than at least one value the subquery returns.x > ALL (subquery)is true ifxis greater than every value the subquery returns.SOMEis a synonym forANY.
Any comparison operator can be used: =, <>, <, <=, >, >=.
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Pack prices are 54.00 and 89.95
-- Dearer than at least one pack
SELECT name, price FROM products
WHERE price > ANY (SELECT price FROM products WHERE category = 'packs')
ORDER BY price;
-- Dearer than every pack
SELECT name, price FROM products
WHERE price > ALL (SELECT price FROM products WHERE category = 'packs')
ORDER BY price;
-- = ANY is the same as IN
SELECT name FROM products
WHERE product_id = ANY (SELECT product_id FROM order_items WHERE qty > 1)
ORDER BY name;
name | price
-------------------+--------
Trail 30 backpack | 89.95
Ridge 2 tent | 249.99
Summit 4 tent | 489.00
(3 rows)
name | price
---------------+--------
Ridge 2 tent | 249.99
Summit 4 tent | 489.00
(2 rows)
name
-----------------
Glow head torch
Merino socks
(2 rows)
The pack prices are 54.00 and 89.95. "Dearer than at least one pack" means dearer than the cheaper one, so > ANY is the same as > 54.00. "Dearer than every pack" means dearer than the dearer one, so > ALL is the same as > 89.95.

The third query shows that = ANY is the same as IN. These equivalences are worth memorizing:
| Expression | Means the same as |
|---|---|
x = ANY (sub) | x IN (sub) |
x <> ALL (sub) | x NOT IN (sub), including its NULL trap |
x > ANY (sub) | x > (SELECT MIN(...) ...), except for empty sets and NULLs |
x > ALL (sub) | x > (SELECT MAX(...) ...), except for empty sets and NULLs |
x < ANY (sub) | x < (SELECT MAX(...) ...), with the same exceptions |
x < ALL (sub) | x < (SELECT MIN(...) ...), with the same exceptions |
One that trips people up: x <> ANY (sub) is not "not in". It's true when x differs from at least one value, which is true for almost every x as soon as the subquery returns two different values. "Not in the list" is <> ALL, or better, NOT EXISTS.
Where ANY and ALL differ from MIN and MAX
The MIN/MAX versions in the table aren't exact equivalents. They differ in two situations:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
-- 1. An empty subquery: > ALL is true for every row, > MAX(...) for none
SELECT COUNT(*) AS gt_all_of_nothing
FROM products
WHERE price > ALL (SELECT price FROM products WHERE category = 'boats');
SELECT COUNT(*) AS gt_max_of_nothing
FROM products
WHERE price > (SELECT MAX(price) FROM products WHERE category = 'boats');
-- 2. A NULL in the subquery: the lighting weights are 90 and NULL
SELECT COUNT(*) AS lt_all_with_null
FROM products
WHERE weight_g < ALL (SELECT weight_g FROM products WHERE category = 'lighting');
SELECT name AS lt_min_ignores_null
FROM products
WHERE weight_g < (SELECT MIN(weight_g) FROM products WHERE category = 'lighting');
gt_all_of_nothing
-------------------
7
(1 row)
gt_max_of_nothing
-------------------
0
(1 row)
lt_all_with_null
------------------
0
(1 row)
lt_min_ignores_null
---------------------
Merino socks
(1 row)
- An empty subquery.
x > ALL (empty)is true for every row: there's no value thatxfails to beat, the same way "every boat in the shop is red" is true when there are no boats.x > ANY (empty)is false. ButMAXof an empty set is NULL, sox > (SELECT MAX(...))is unknown, and no rows are returned. The first two queries return 7 and 0. - A NULL in the subquery. The lighting weights are 90 and NULL.
x < ALL (90, NULL)meansx < 90 AND x < NULL, andx < NULLis unknown, so the result is never true: no rows.MINskips the NULL, sox < (SELECT MIN(...))compares with 90 and finds the socks.
Neither behaviour is wrong, but they're different, so choose deliberately. If NULLs can appear and should be ignored, either use the aggregate form or add WHERE column IS NOT NULL to the subquery. If an empty subquery should mean "no rows", the MAX form does that, while ALL does the opposite.
Support
ANY, SOME and ALL with a subquery are in the SQL standard and supported by PostgreSQL, MySQL, Oracle and SQL Server. SQLite doesn't support them, so use IN, EXISTS or the MIN/MAX forms there. PostgreSQL also accepts arrays: x = ANY (ARRAY[1, 2, 3]) or x = ANY ($1) with an array parameter, which is a common way to pass a list of values from application code.
EXISTS
EXISTS (subquery) is true if the subquery returns at least one row. What the rows contain doesn't matter, so it's usually written SELECT 1. An uncorrelated EXISTS is rarely useful, because its answer is the same for every row:
SELECT name FROM products
WHERE EXISTS (SELECT 1 FROM orders WHERE status = 'pending');
-- returns every product if any order is pending, and no products otherwise
EXISTS becomes useful when it's correlated: "products for which an order line exists with this product's ID". Article 16 covered that use in detail, and the next article explains how correlation works.
Subqueries in HAVING and FROM
A subquery can appear anywhere a value or a table fits, including HAVING and FROM:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- A subquery in HAVING: categories whose average price beats the overall average
SELECT category, ROUND(AVG(price), 2) AS avg_price
FROM products
GROUP BY category
HAVING AVG(price) > (SELECT AVG(price) FROM products);
-- A subquery in FROM: filter on an aggregate without HAVING
SELECT category, n
FROM (SELECT category, COUNT(*) AS n
FROM products
GROUP BY category) AS per_category
WHERE n > 1
ORDER BY category;
-- A multi-column IN: each customer's first order
SELECT order_id, customer_id, placed_on
FROM orders
WHERE (customer_id, placed_on) IN (SELECT customer_id, MIN(placed_on)
FROM orders
GROUP BY customer_id)
ORDER BY order_id;
category | avg_price
----------+-----------
tents | 369.50
(1 row)
category | n
----------+---
lighting | 2
packs | 2
tents | 2
(3 rows)
order_id | customer_id | placed_on
----------+-------------+------------
101 | 1 | 2026-03-02
102 | 2 | 2026-03-05
104 | 3 | 2026-03-15
105 | 4 | 2026-03-20
(4 rows)
- In
HAVING: categories whose average price is above the overall average. The subquery runs over all products, independently of the grouping. Only tents qualify. - In
FROM: a subquery that produces a table, called a derived table. Here the inner query counts products per category, and the outer query filters on the count with an ordinaryWHERE. The same result asHAVING COUNT(*) > 1, written in two steps. A derived table must have an alias (per_category) in most databases. PostgreSQL 16 and later made the alias optional. Derived tables get a full treatment in the next article. - Multi-column
IN: each customer's first order, found by matching (customer, date) pairs against the minimum date per customer. The guest order has a NULL customer, so its pair can't match anything.
Nesting
A subquery can contain its own subqueries, to any reasonable depth:
SELECT name FROM customers
WHERE customer_id IN (SELECT customer_id FROM orders
WHERE order_id IN (SELECT order_id FROM order_items
WHERE product_id = 1));
-- customers who ordered the Ridge 2 tent
Two or three levels are readable. Beyond that, a join or a common table expression (article 24) usually expresses the steps more clearly.
Are subqueries slow?
There's an old belief that subqueries are slow and joins are fast. It dates from optimizers that ran an IN subquery once per outer row. Modern optimizers rewrite subqueries before running them, and the plan often doesn't depend on which form you wrote:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- An uncorrelated scalar subquery runs once (an InitPlan)...
EXPLAIN (COSTS OFF)
SELECT name FROM products
WHERE price > (SELECT AVG(price) FROM products);
-- ...and IN (subquery) is turned into a join
EXPLAIN (COSTS OFF)
SELECT name FROM products
WHERE product_id IN (SELECT product_id FROM order_items);
QUERY PLAN
-----------------------------------------------
Seq Scan on products
Filter: (price > (InitPlan 1).col1)
InitPlan 1
-> Aggregate
-> Seq Scan on products products_1
(5 rows)
QUERY PLAN
-------------------------------------------------------------
Hash Join
Hash Cond: (products.product_id = order_items.product_id)
-> Seq Scan on products
-> Hash
-> HashAggregate
Group Key: order_items.product_id
-> Seq Scan on order_items
(7 rows)
- The scalar subquery appears as an InitPlan: it runs once, and its result is used as a constant for every row of the outer scan.
- The
INsubquery has disappeared. PostgreSQL turned it into a join against the distinct product IDs fromorder_items(theHashAggregateremoves duplicates, so no product is repeated).
MySQL 5.6 and later, SQL Server and Oracle do similar rewrites. So choose the form that expresses the question most clearly: IN or EXISTS for "has a match", a join when you need columns from both tables, and a scalar subquery for "compare with one computed value". Look at the plan (article 67) when performance matters, rather than relying on rules of thumb.
ORDER BY inside a subquery
Sorting inside a subquery used with IN, EXISTS, ANY or ALL is pointless: they test membership, and the order of a set doesn't matter. PostgreSQL and MySQL accept the ORDER BY and ignore it. SQL Server rejects ORDER BY in a subquery unless it also has TOP or OFFSET, because without one of those the order has no effect. The one place where ORDER BY in a subquery matters is together with a row limit, as in (SELECT price FROM products ORDER BY price DESC LIMIT 1), where it decides which row is kept.
What's current
- PostgreSQL 16 made the alias on a derived table optional, so
SELECT * FROM (SELECT ...)works withoutAS t. Oracle has never required one. MySQL, SQL Server and older PostgreSQL versions still do, so add one for portability. - PostgreSQL 17 changed how
EXPLAINshows a subquery's result, as(InitPlan 1).col1instead of$0, which makes plans with subqueries easier to read. - SQLite still doesn't support
ANY,SOMEorALL, and SQL Server still doesn't support multi-columnIN.
Common questions
What happens if a scalar subquery returns no rows?
Its value is NULL. Comparisons with it are unknown, so a WHERE that uses it keeps no rows. Wrap it in COALESCE if a default makes sense.
What happens if a scalar subquery returns two rows?
A run-time error. Make it impossible: aggregate, or filter on a unique key. LIMIT 1 hides the error but returns an arbitrary row unless you also sort.
Should I use IN or a join?
Use IN or EXISTS when you only need columns from the outer table and want each row once. Use a join when you need columns from both tables. Performance is usually the same.
Is x <> ANY (...) the same as NOT IN?
No. NOT IN is <> ALL. <> ANY is true when x differs from at least one value.
Why does > ALL return every row?
The subquery returned no rows. "Greater than all of nothing" is true. Use > (SELECT MAX(...)) if an empty set should return no rows.
Can a subquery use a table that's also in the outer query?
Yes. The examples here use products in both. Without correlation, the two are completely independent. Use different aliases when you need to refer to both, which is what the next article is about.
Can a subquery return more than one column?
In FROM, EXISTS and multi-column IN, yes. Where one value is expected, as in x = (subquery) or x IN (subquery), no.
Can I use a subquery in INSERT, UPDATE and DELETE?
Yes, in their WHERE clauses, in SET, and as the source of an INSERT ... SELECT. Part 7 covers them.
Summary
- A subquery is a query in parentheses inside another statement. It's uncorrelated if it doesn't refer to the outer query, and then it has a single answer.
- A scalar subquery returns one value and can go anywhere a value can. No rows gives NULL. More than one row is a run-time error.
IN (subquery)tests membership without multiplying rows, unlike a join. The subquery must return one column per value tested.ANYmeans "for at least one value",ALLmeans "for every value".= ANYisINand<> ALLisNOT IN.> ALL (empty)is true, while comparing withMAXof an empty set is unknown. A NULL in the subquery makesALLcomparisons unknown, whileMINandMAXskip it.- Subqueries can go in
SELECT,FROM,WHEREandHAVING, and can be nested. - Modern optimizers run uncorrelated scalar subqueries once and turn
INsubqueries into joins, so write the clearest form.
Practice questions
Write a query that returns the name and price of every product that costs less than the average price of the tents.
Answer
SELECT name, price
FROM products
WHERE price < (SELECT AVG(price) FROM products WHERE category = 'tents')
ORDER BY price;
The tents average 369.50, so every product except the Summit 4 tent qualifies. AVG guarantees one row, so the subquery can't fail with a "more than one row" error.
A query uses WHERE customer_id = (SELECT customer_id FROM customers WHERE city = 'Pune'). It worked last month but fails today. What happened, and how do you fix it?
Answer
A second customer in Pune was added, so the scalar subquery now returns two rows, which is an error. If the intent is "customers in Pune", use IN instead of =: WHERE customer_id IN (SELECT customer_id FROM customers WHERE city = 'Pune'). In the course data, both Asha and Chen live in Pune, so the = version fails.
What does SELECT name FROM products WHERE price > ALL (SELECT price FROM products WHERE category = 'tents') return, and why?
Answer
No rows. > ALL requires the price to be greater than every tent price, including 489.00, the highest price in the table. Even the Summit 4 tent isn't greater than its own price. Changing it to >= ALL would return the Summit 4 tent.
Rewrite x NOT IN (SELECT y FROM t) using ALL. Does the rewrite fix the NULL problem?
Answer
x <> ALL (SELECT y FROM t). It doesn't fix anything: it's exactly the same condition. If t.y contains a NULL, x <> NULL is unknown, so the whole ALL is never true and no rows are returned. Use NOT EXISTS (SELECT 1 FROM t WHERE t.y = x) instead, or add WHERE y IS NOT NULL to the subquery.
Write a query that lists the customers who have placed at least one order, without using a join, and without returning anyone twice.
Answer
SELECT name
FROM customers
WHERE customer_id IN (SELECT customer_id FROM orders)
ORDER BY name;
It returns Asha, Ben, Chen and Dana. Asha has two orders but appears once, because IN only tests membership. The guest order's NULL customer_id doesn't matter here, since NULLs never equal anything. It would matter with NOT IN.
Why might WHERE weight_g < ALL (SELECT weight_g FROM products WHERE category = 'lighting') return no rows, although the socks (80 g) are lighter than the head torch (90 g)?
Answer
The lantern's weight is NULL, so the subquery returns 90 and NULL. 80 < ALL (90, NULL) means 80 < 90 AND 80 < NULL, which is true AND unknown, which is unknown. No row can make an ALL comparison true when the set contains a NULL. Add WHERE weight_g IS NOT NULL to the subquery, or compare with (SELECT MIN(weight_g) ...), which ignores NULLs.
Previous: Conditional Aggregation in SQL: CASE Inside Aggregates and FILTER
Next: Correlated Subqueries, Derived Tables and LATERAL Joins

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.