๐งฉ SQL Subqueries โ Using One Query Inside Another
So far, we've learned how to retrieve, filter, group, transform, and combine data.
But sometimes a business question requires one query to use the result of another query.
For example:
ยซFind employees whose salary is higher than the average salary.ยป
First, we need to calculate:
SELECT AVG(salary)
FROM employees;
Then compare every employee against that result.
A subquery allows us to do both inside one SQL statement.
๐ง 1. What Is a Subquery?
A subquery is a SQL query written inside another SQL query.
SELECT *
FROM employees
WHERE salary > (
SELECT AVG(salary)
FROM employees
);
The inner query:
SELECT AVG(salary) FROM employees
calculates the average salary. The outer query then uses that result.
Think of it as:
Outer Query โ Needs an answer โ Subquery calculates the answer โ Outer Query uses it
๐น 2. Basic Subquery Structure
SELECT column_name
FROM table_name
WHERE column_name operator (
SELECT ...
);
The inner query is enclosed in
( ... ).๐ 3. Subquery Returning One Value
A scalar subquery returns a single value.
SELECT
employee_name,
salary
FROM employees
WHERE salary > (
SELECT AVG(salary)
FROM employees
);
The inner query returns something like
65000. The outer query then finds employees earning more than 65000.๐ฐ 4. Employees Earning Above Average
Classic interview question.
SELECT
employee_name,
salary
FROM employees
WHERE salary > (
SELECT AVG(salary)
FROM employees
);
Logic: Calculate average salary โ Compare every employee โ Keep salary > average
๐ 5. Products More Expensive Than Average
SELECT
product_name,
price
FROM products
WHERE price > (
SELECT AVG(price)
FROM products
);
๐ข 6. Subquery with COUNT()
Customers who have placed more than 5 orders:
SELECT
customer_id,
customer_name
FROM customers
WHERE customer_id IN (
SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING COUNT(*) > 5
);
๐ 7. Subquery with IN
Useful when a subquery returns multiple values.
SELECT *
FROM customers
WHERE customer_id IN (
SELECT customer_id
FROM orders
);
Returns customers who have at least one order.
โ ๏ธ 8. Single Value vs Multiple Values
One value โ Use
=, >, <, >=, <=WHERE salary > (
SELECT AVG(salary)
FROM employees
)
Multiple values โ Use
INWHERE customer_id IN (
SELECT customer_id
FROM orders
)
๐ซ 9. NOT IN
SELECT
customer_id,
customer_name
FROM customers
WHERE customer_id NOT IN (
SELECT customer_id
FROM orders
);
โ ๏ธ Important NULL Warning:
NOT IN can produce unexpected results if the subquery contains NULL. For anti-matching, NOT EXISTS is often safer.๐ 10. EXISTS
SELECT
c.customer_id,
c.customer_name
FROM customers c
WHERE EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
);
Means: Return the customer if at least one matching order exists.
๐ซ 11. NOT EXISTS
SELECT
c.customer_id,
c.customer_name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
);