← Back to SQL, page 6

sql-0103 · Easy fresher

What is a common table expression (CTE), and why use one instead of a nested subquery?

A CTE is a named, temporary result defined with WITH name AS (SELECT ...) and used by the query that follows. It lets you build a query in readable steps, reuse the same intermediate result more than once, and write recursive queries. It lasts only for that one statement.

Full answer

A CTE gives a subquery a name and moves it to the top of the statement, so the main query reads like a short story instead of an inside-out puzzle.

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');

"Departments whose total pay is above the average department total", as a chain of named steps:

sql
WITH dept_totals AS (
  SELECT dept_id, SUM(salary) AS total
  FROM employees
  WHERE dept_id IS NOT NULL
  GROUP BY dept_id
),
avg_total AS (
  SELECT AVG(total) AS avg_t FROM dept_totals
)
SELECT d.name, t.total
FROM dept_totals t
JOIN departments d ON d.id = t.dept_id
WHERE t.total > (SELECT avg_t FROM avg_total)
ORDER BY t.total DESC;
nametotal
Engineering310000

Each step has a name that explains it, and dept_totals is used twice without being written twice. The nested version needs the same derived table copied into two places:

sql
SELECT d.name, t.total
FROM (SELECT dept_id, SUM(salary) AS total FROM employees
      WHERE dept_id IS NOT NULL GROUP BY dept_id) t
JOIN departments d ON d.id = t.dept_id
WHERE t.total > (SELECT AVG(total)
                 FROM (SELECT dept_id, SUM(salary) AS total FROM employees
                       WHERE dept_id IS NOT NULL GROUP BY dept_id))
ORDER BY t.total DESC;
nametotal
Engineering310000

Both return Engineering. The CTE version is easier to review and to change.

A CTE is not stored anywhere; it exists for one statement. Whether the engine computes it once or inlines it into the main query is an optimizer decision. PostgreSQL 12 and later usually inline a CTE that is referenced once, and you can force either behaviour with AS MATERIALIZED or AS NOT MATERIALIZED.

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');

WITH dept_totals AS (
  SELECT dept_id, SUM(salary) AS total
  FROM employees
  WHERE dept_id IS NOT NULL
  GROUP BY dept_id
),
avg_total AS (
  SELECT AVG(total) AS avg_t FROM dept_totals
)
SELECT d.name, t.total
FROM dept_totals t
JOIN departments d ON d.id = t.dept_id
WHERE t.total > (SELECT avg_t FROM avg_total)
ORDER BY t.total DESC;

SELECT d.name, t.total
FROM (SELECT dept_id, SUM(salary) AS total FROM employees
      WHERE dept_id IS NOT NULL GROUP BY dept_id) t
JOIN departments d ON d.id = t.dept_id
WHERE t.total > (SELECT AVG(total)
                 FROM (SELECT dept_id, SUM(salary) AS total FROM employees
                       WHERE dept_id IS NOT NULL GROUP BY dept_id))
ORDER BY t.total DESC;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • WITH name AS (...) defines a named result for one statement
  • CTEs make multi-step logic readable and reusable within the query
  • They enable recursive queries
  • The optimizer may inline or materialize them

Common mistakes

  • Assuming a CTE is a temporary table that persists after the statement
  • Assuming a CTE is always computed only once

Follow-ups

  • When would you choose a temporary table over a CTE?
  • What does AS MATERIALIZED change in PostgreSQL?

Tips

  • Name each CTE after what it contains, like dept_totals, not t1