SQL Subqueries
Definition
A SQL subquery is a query nested inside another SQL statement, used to compute values, filter rows, or define temporary datasets for the outer query.
Introduction to SQL Subqueries
Subqueries let you use the result of one query as input to another. They can appear in SELECT, FROM, WHERE, and HAVING clauses. While CTEs are often more readable for complex logic, subqueries are compact and powerful for embedding one-off calculations or filters directly in a query.
Syntax
-- Subquery in WHERE SELECT * FROM employees WHERE salary > (SELECT AVG(salary) FROM employees); -- Subquery in FROM (derived table) SELECT dept, avg_sal FROM (SELECT department AS dept, AVG(salary) AS avg_sal FROM employees GROUP BY department) sub;
Examples
Scalar Subquery — Single Value
SELECT name, salary, salary - (SELECT AVG(salary) FROM employees) AS vs_avg FROM employees ORDER BY vs_avg DESC;
The subquery computes the company average once. Each row shows how much above or below average the employee's salary is.
Try in PlaygroundCorrelated Subquery
SELECT name, department, salary FROM employees e WHERE salary > ( SELECT AVG(salary) FROM employees WHERE department = e.department -- references outer query );
A correlated subquery references the outer query (e.department). It is re-executed for each outer row, returning employees who earn above their own department's average.
Try in PlaygroundIN with Subquery
SELECT name FROM employees WHERE dept_id IN ( SELECT id FROM departments WHERE budget > 1000000 );
The subquery returns a list of high-budget department IDs, and the outer query finds all employees in those departments.
Try in PlaygroundCommon Mistakes
Using correlated subqueries on large tables — executes N times (once per outer row), very slow
Subquery returns multiple rows when scalar expected — causes runtime error
Forgetting to alias derived tables: FROM (SELECT ...) — the alias is required in most databases
Using subqueries where a JOIN would be more efficient and readable
Frequently Asked Questions
What is a subquery in SQL?
What is a correlated subquery?
When should I use a subquery vs JOIN?
What is a derived table in SQL?
Related SQL Topics
Practice This in the SQL Playground
Write real queries, see live results, and master SQL Subqueries hands-on. 100% free.