capypad
0 day streak
sql / intermediate
Snippet

Correlated Subqueries

A correlated subquery references columns from the outer query. It is evaluated once for each row processed by the outer query to perform row-specific logic.

snippet.sql
sql
1
2
3
4
5
6
7
SELECT e1.name
FROM employees e1
WHERE e1.salary > (
SELECT AVG(e2.salary)
FROM employees e2
WHERE e2.department_id = e1.department_id
);
Breakdown
1
WHERE e1.salary > (
Initiates a comparison between a row value and the result of the subquery.
2
WHERE e2.department_id = e1.department_id
The correlation step that links the subquery to the current outer row's department.