Chapter 14 · Lesson 1 of 4
Subqueries in WHERE
Compare each row with a value computed by another query, such as finding team members who earn more than the overall average salary.
A subquery is a query inside another query, wrapped in parentheses. SQL runs the inner query and uses its result in the outer one.
A subquery that returns exactly one value is called a scalar subquery. You can use it anywhere a single value fits, such as a comparison in WHERE:
SELECT name, salary
FROM team_members
WHERE salary > (SELECT AVG(salary) FROM team_members)
ORDER BY salary DESCWhy not write WHERE salary > AVG(salary)? Because WHERE filters individual rows before any aggregation happens, so aggregate functions are not allowed there. The subquery computes the average first, as its own small query.
You can run the inner query on its own to check it:
SELECT AVG(salary) FROM team_membersSample 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 the name and salary of team members who earn more than the average salary of all team members, ordered by salary from highest to lowest.
Hint: WHERE salary > (SELECT AVG(salary) FROM team_members) ORDER BY salary DESC
Run your query in the editor and the lesson checks the result automatically.
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).