Chapter 14 · Lesson 3 of 4

Common Table Expressions with WITH

Name an intermediate result with WITH, then query it like a table, such as computing team salary averages first and filtering them in a second step.

A common table expression (CTE) gives a subquery a name. You define it at the top of the query with WITH, then use it like a table:

WITH team_stats AS (
  SELECT team, AVG(salary) AS avg_salary
  FROM team_members
  GROUP BY team
)
SELECT team, avg_salary
FROM team_stats
WHERE avg_salary > 70000
ORDER BY avg_salary DESC

CTEs do not make queries more powerful than subqueries, but they make them much easier to read. Each step has a name, and the final SELECT reads like a summary of the steps.

You can define several CTEs, separated by commas, and later ones can use earlier ones:

WITH team_stats AS (
  SELECT team, AVG(salary) AS avg_salary
  FROM team_members
  GROUP BY team
),
top_teams AS (
  SELECT team FROM team_stats WHERE avg_salary > 70000
)
SELECT name, team
FROM team_members
WHERE team IN (SELECT team FROM top_teams)

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

Use a CTE named team_stats that computes each team's average salary as avg_salary. Then return team and avg_salary for teams whose average is above 70000, ordered by avg_salary descending.

Hint: WITH team_stats AS (SELECT team, AVG(salary) AS avg_salary FROM team_members GROUP BY team) SELECT ...

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