SELECT first_name, email
FROM users
WHERE id IN(SELECT user_id
FROM orders
WHERE total_amount >500);
Output
-- Users who have placed at least one order over 500
Note For large datasets, EXISTS often performs better than IN with a subquery because EXISTS short-circuits on the first match. IN materializes the entire subquery result first.
SELECT
top_customers.first_name,
top_customers.total_spentFROM(SELECT u.first_name,SUM(o.total_amount)AS total_spent
FROM users u
JOIN orders o ON o.user_id= u.idGROUPBY u.id, u.first_nameHAVINGSUM(o.total_amount)>1000)AS top_customers
ORDERBY top_customers.total_spentDESC;
Output
-- first_name | total_spent
-- Alice | 4520.00
-- Bob | 2310.50
Note Derived tables (subqueries in FROM) must have an alias. They are computed once and treated like a temporary table. CTEs (WITH clause) are generally more readable for the same purpose.
SELECT first_name, salary
FROM employees
WHERE salary >ALL(SELECT salary
FROM employees
WHERE department_id =3);
Output
-- Employees earning more than everyone in department 3
Note ANY means 'at least one' - the condition must hold for at least one row from the subquery. ALL means 'every' - it must hold for all rows. An empty subquery makes ALL true and ANY false.
Frequently asked questions
How does SQL handle in subquery?
SQL covers this with 3 copy-ready snippets on this page. The "Subquery in WHERE with IN" snippet in SQL uses `WHERE column IN (SELECT column FROM ...)`.
Which statement does the SQL example use?
The "Subquery in WHERE with IN" snippet uses `WHERE column IN (SELECT column FROM ...)`, from the Subqueries section of the SQL cheat sheet.
What other SQL snippets are shown for "in subquery"?
Besides "Subquery in WHERE with IN", this page also shows "Derived Table (Subquery in FROM)", "Subquery with ANY / ALL".
Is there anything to watch out for?
Yes. For "Subquery in WHERE with IN": For large datasets, EXISTS often performs better than IN with a subquery because EXISTS short-circuits on the first match. IN materializes the entire subquery result first.