What is a correlated subquery, and when would you use a join instead of a subquery?
MediumConceptSQL: Joins
Answer
A subquery is a query nested inside another query. A regular subquery is independent and can run once, while a correlated subquery refers to a column of the outer query, so it is logically re-evaluated for every outer row.
- Use a join when the output needs columns from both tables.
- Use
INorEXISTSwith a subquery when you only need to test whether related rows exist;NOT EXISTSis a clean way to find rows without a match. - Modern optimizers (MySQL 8, PostgreSQL, SQL Server) often rewrite subqueries as joins, so write the clearest form first and check the plan with
EXPLAINif it is slow. - Avoid
NOT INwhen the subquery can returnNULL: a singleNULLmakes it return no rows.
Example: Employees who earn more than the average of their own department:
SELECT e.name, e.salary
FROM employees e
WHERE e.salary > (SELECT AVG(x.salary)
FROM employees x
WHERE x.dept = e.dept); -- correlated: uses e.dept