SQL Joins and Subqueries/Correlated subquery

Reference outer query columns inside the subquery.

Section: Subqueries

Correlated subquery

sql
sql
SELECT e.employee_id, e.salary
FROM employees e
WHERE e.salary > (
  SELECT AVG(e2.salary)
  FROM employees e2
  WHERE e2.department_id = e.department_id
);
Explanation

Correlated subqueries execute relative to each outer row.

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing Subqueries
Use a subquery in WHERE
Filter rows based on results from another query.
OpenIn sheetsqlsame section
Scalar subquery
Return a single value from a nested query.
OpenIn sheetsqlsame section
Subquery in FROM
Use a derived table as a query source.
OpenIn sheetsqlsame section
Filter with EXISTS
Return rows when a related row exists.
OpenIn sheetsql1 tag match
Filter with NOT EXISTS
Return rows with no related matches.
OpenIn sheetsql1 tag match
Join to an aggregated subquery
Pre-aggregate a table and join the result.
OpenIn sheetsql1 tag match