Chapter 14 · Lesson 4 of 4

Correlated Subqueries

Write a subquery that refers to the outer row to compare each person with their own team's average, and see how a CTE join expresses the same idea.

So far, each subquery could run on its own. A correlated subquery refers to a column from the outer query, so it is evaluated for each outer row.

This compares every team member with the average of their own team:

SELECT m.name, m.team, m.salary
FROM team_members AS m
WHERE m.salary > (
  SELECT AVG(t.salary)
  FROM team_members AS t
  WHERE t.team = m.team
)
ORDER BY m.name

The condition t.team = m.team links the inner query to the current outer row. Table aliases (m and t) are required here, because both sides use the same table.

The same question can be answered with a CTE and a join, which some people find easier to read and debug:

WITH team_avg AS (
  SELECT team, AVG(salary) AS avg_salary
  FROM team_members
  GROUP BY team
)
SELECT m.name, m.team, m.salary
FROM team_members AS m
JOIN team_avg AS a ON a.team = m.team
WHERE m.salary > a.avg_salary
ORDER BY m.name

DuckDB optimizes both forms well, so choose the one that reads best for your question.

Sample data

This lesson loads the team_members (8 rows) and projects (7 rows) tables into DuckDB in your browser with one click, so you can run every example without uploading anything.

Setup SQL for team_members, projects
CREATE OR REPLACE TABLE team_members (
    id INTEGER,
    name VARCHAR,
    team VARCHAR,
    salary INTEGER,
    hire_date DATE
  );

INSERT INTO team_members VALUES
    (1, 'Alice', 'Engineering', 120000, '2019-04-01'),
    (2, 'Bruno', 'Engineering', 95000, '2021-06-15'),
    (3, 'Chen', 'Engineering', 105000, '2020-01-10'),
    (4, 'Dara', 'Marketing', 70000, '2022-03-01'),
    (5, 'Elif', 'Marketing', 82000, '2018-09-20'),
    (6, 'Femi', 'Sales', 60000, '2023-01-05'),
    (7, 'Gita', 'Sales', 75000, '2020-11-11'),
    (8, 'Hugo', 'Support', 52000, '2021-02-01');

CREATE OR REPLACE TABLE projects (
    project_id INTEGER,
    member_id INTEGER,
    project VARCHAR
  );

INSERT INTO projects VALUES
    (1, 1, 'Search'),
    (2, 1, 'Billing'),
    (3, 3, 'Search'),
    (4, 5, 'Rebrand'),
    (5, 7, 'Q3 Push'),
    (6, 2, 'Billing'),
    (7, NULL, 'Research spike');

Practice challenge

Return name, team, and salary for team members who earn more than the average salary of their own team, ordered by name.

Hint: WHERE m.salary > (SELECT AVG(t.salary) FROM team_members AS t WHERE t.team = m.team)

Run your query in the editor and the lesson checks the result automatically.

Open this lesson in the SQL editor

Lessons in Subqueries and CTEs

Nest one query inside another with subqueries, test membership with IN and EXISTS, and break long queries into named steps with WITH (common table expressions).

  1. 01 · Subqueries in WHERE
  2. 02 · IN, EXISTS, and the NOT IN Trap
  3. 03 · Common Table Expressions with WITH
  4. 04 · Correlated Subqueries

Related guides