1 Subqueries (Nested & Correlated)
TopA subquery is a query inside another query. It lets you use the result of one query as input to another — like nesting functions in a spreadsheet formula.
Nested Subquery (Runs Once)
The inner query runs first, returns a value, then the outer query uses it:
-- Find products priced above the average
SELECT name, price
FROM products
WHERE price > (
SELECT AVG(price) FROM products
);name | price ---------------|------ SQL Textbook | 45.00 Mechanical KB | 89.99 Webcam HD | 59.99
Subquery in WHERE with IN
-- Customers who have placed at least one order
SELECT name, city
FROM customers
WHERE id IN (
SELECT DISTINCT customer_id FROM orders
);Correlated Subquery (Runs Per Row)
A correlated subquery references the outer query's row, so it runs once for each row in the outer query. It's slower but more powerful:
-- For each customer, find their most expensive order
SELECT c.name, o.product, o.amount
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.amount = (
SELECT MAX(o2.amount)
FROM orders o2
WHERE o2.customer_id = o.customer_id -- references outer query!
);name | product | amount --------------|---------------|------ Sara Ahmed | USB-C Hub | 39.99 James Wilson | SQL Textbook | 45.00 Priya Sharma | Desk Lamp | 34.99
EXISTS: Check If Rows Exist
-- Customers who have NOT placed any orders
SELECT name
FROM customers c
WHERE NOT EXISTS (
SELECT 1 FROM orders o
WHERE o.customer_id = c.id
);EXISTS vs IN: EXISTS stops as soon as it finds one matching row (efficient for large tables). IN builds the full list first. For large subqueries, EXISTS is usually faster. For small lists, IN is fine.
Key Takeaways
- Nested subqueries run once and return a single value or list
- Correlated subqueries run per row — they reference the outer query
-
IN (subquery)checks membership;EXISTSchecks existence (and is faster for large data) - Subqueries can appear in WHERE, SELECT, FROM, and HAVING clauses