Programming

What is a subquery in SQL?

Short answer

A subquery is a query nested inside another SQL query, used to compute an intermediate result that the outer query then uses — for filtering, comparison, or as a temporary data source.

Subqueries let you break a complex question into a smaller, self-contained query first, then use its result inside a larger one.

Example

SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);

Here, the subquery (SELECT AVG(salary) FROM employees) runs first, calculating the average salary. The outer query then uses that single value to filter for employees earning above it.

Common types of subqueries

Many subqueries can be rewritten as JOINs and vice versa — the right choice usually comes down to which is clearer to read and which performs better for a specific database and dataset.

Last reviewed: September 2026