Subqueries — Queries Inside Queries
Nest one query inside another to filter, calculate, or compare values that you cannot know until runtime.
A subquery is a query inside another query. The inner query runs first and its result feeds the outer query.
EXERCISE
1Subqueries — Queries Inside Queries
A subquery is a SELECT statement nested inside another SQL statement. The inner query runs first and its result is used by the outer query.
Think of a subquery as answering a question by first answering a smaller question:
"Who earns more than average?" → First answer: "What IS the average?" (inner query) → Then answer the main question using that result (outer query)
Subquery in WHERE:
-- Find employees earning above the company average:
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
-- Inner query: SELECT AVG(salary) FROM employees → returns 69000
-- Outer query: WHERE salary > 69000
Subquery returning a list (with IN):
-- Find employees in departments located in Bangalore:
SELECT name
FROM employees
WHERE department_id IN (
SELECT id FROM departments WHERE location = 'Bangalore'
);
-- Inner query returns: (1, 3, 5)
-- Outer query: WHERE department_id IN (1, 3, 5)
Subquery in SELECT — scalar subquery:
-- Show each employee's salary vs company average:
SELECT
name,
salary,
(SELECT AVG(salary) FROM employees) AS company_avg,
salary - (SELECT AVG(salary) FROM employees) AS diff_from_avg
FROM employees;
Subquery in FROM — derived table:
-- Average salary per department, then filter:
SELECT dept_summary.department, dept_summary.avg_sal
FROM (
SELECT department, AVG(salary) AS avg_sal
FROM employees
GROUP BY department
) AS dept_summary
WHERE dept_summary.avg_sal > 65000;
-- The subquery creates a temporary "table" named dept_summary
Pro Tip: Every subquery must be wrapped in parentheses. A subquery in FROM must have an alias. A subquery in WHERE that returns multiple rows must use IN, NOT IN, ANY, or ALL — not =.
EXERCISE
2Correlated Subqueries — Dynamic Inner Queries
A correlated subquery references the outer query's current row — it runs once for every row of the outer query, making it slower but far more powerful.
A correlated subquery is one that refers to a column from the outer query. It cannot run independently — it depends on the outer row.
Example — find employees earning more than their department average:
SELECT name, salary, department_id
FROM employees e_outer
WHERE salary > (
SELECT AVG(salary)
FROM employees e_inner
WHERE e_inner.department_id = e_outer.department_id
-- ↑ references the outer row!
);
How it executes:
- Outer query picks row 1: Ada, IT department
- Inner query runs:
AVG(salary) WHERE department_id = IT - Compare Ada's salary to IT average
- Repeat for every row
EXISTS — the most common correlated subquery:
-- Find customers who have placed at least one order:
SELECT name
FROM customers c
WHERE EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.id -- correlated reference
);
-- EXISTS returns TRUE as soon as the inner query finds any row
-- Much faster than IN for large datasets
NOT EXISTS — find the complement:
-- Find customers who have NEVER placed an order:
SELECT name
FROM customers c
WHERE NOT EXISTS (
SELECT 1 FROM orders o WHERE o.customer_id = c.id
);
-- Same as: LEFT JOIN ... WHERE orders.id IS NULL (both patterns valid)
EXISTS vs IN — the performance difference:
-- IN loads all matching values into memory:
WHERE id IN (SELECT customer_id FROM orders) -- can be slow with millions of orders
-- EXISTS stops at the first match:
WHERE EXISTS (SELECT 1 FROM orders WHERE customer_id = c.id) -- faster on large data
Pro Tip: Use EXISTS when you just need to know whether a related row exists. Use IN when you need to match against a specific list of values. EXISTS is almost always faster for large tables.
EXERCISE
3Subquery Patterns for Common Interview Questions
These are the subquery patterns that appear in every SQL interview and in real-world analytics work — master them and you are interview-ready.
Pattern 1 — Nth highest salary:
-- Second highest salary using subquery:
SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);
-- Generic Nth highest (here N=3):
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 2; -- skip top 2, take the 3rd
Pattern 2 — Employees earning more than their manager:
SELECT e.name AS employee, e.salary, m.name AS manager, m.salary AS mgr_salary
FROM employees e
JOIN employees m ON e.manager_id = m.id
WHERE e.salary > m.salary;
Pattern 3 — Highest salary per department:
SELECT name, department_id, salary
FROM employees e
WHERE salary = (
SELECT MAX(salary)
FROM employees
WHERE department_id = e.department_id
);
-- Correlated subquery: finds max salary for THIS employee's department
Pattern 4 — Employees who joined in the last 3 months:
SELECT name, hire_date
FROM employees
WHERE hire_date >= DATE_SUB(CURDATE(), INTERVAL 3 MONTH);
Pattern 5 — Find duplicates:
SELECT email, COUNT(*) AS count
FROM customers
GROUP BY email
HAVING COUNT(*) > 1;
Pattern 6 — Department with most employees:
SELECT department_id, COUNT(*) AS total
FROM employees
GROUP BY department_id
ORDER BY total DESC
LIMIT 1;
Pro Tip: These six patterns cover 80% of interview SQL questions. Understand the logic behind each one — not just the syntax — and you can adapt them to any variation an interviewer throws at you.
