Subqueries and CTEs · Lesson 53 of 64

SQL WITH: Common Table Expressions

What you will learn

  • How to write a WITH query (a CTE)
  • How a CTE makes a query read top to bottom
  • How to use one CTE several times
  • How it differs from a view and a derived table

This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Run the cells from top to bottom.

1. Name a step

A common table expression (CTE) is a named query that exists only for the one statement that follows it. You write WITH name AS ( query ) and then use name like a table:

WITH per_customer AS (
    SELECT customer_id, COUNT(*) AS orders FROM orders GROUP BY customer_id
)
SELECT ROUND(AVG(orders), 2) AS avg_orders, MAX(orders) AS most_orders
FROM per_customer;
avg_orders  most_orders
----------  -----------
      7.12           17
(1 row)
WITH per_customer AS (
    SELECT customer_id, COUNT(*) AS accounts FROM accounts GROUP BY customer_id
)
SELECT ROUND(AVG(accounts), 2) AS avg_accounts, MAX(accounts) AS most_accounts
FROM per_customer;
avg_accounts  most_accounts
------------  -------------
        1.91              7
(1 row)
WITH per_student AS (
    SELECT student_id, COUNT(*) AS enrollments FROM enrollments GROUP BY student_id
)
SELECT ROUND(AVG(enrollments), 2) AS avg_enrollments, MAX(enrollments) AS most_enrollments
FROM per_student;
avg_enrollments  most_enrollments
---------------  ----------------
           2.95                 8
(1 row)

This is the "aggregate an aggregate" query of lesson 7.4, but the step has a name and comes first. A long query now reads from top to bottom like a recipe.

2. Use the name more than once

A derived table cannot be reused; a CTE can be named once and used in several places of the same statement:

Categories with more products than the average category:

WITH per_category AS (
    SELECT category_id, COUNT(*) AS products FROM products GROUP BY category_id
)
SELECT category_id, products
FROM per_category
WHERE products > (SELECT AVG(products) FROM per_category)
ORDER BY products DESC, category_id;
category_id  products
-----------  --------
          2         7
          5         7
         10         7
(3 rows)

Branches with more accounts than the average branch:

WITH per_branch AS (
    SELECT branch_id, COUNT(*) AS accounts FROM accounts GROUP BY branch_id
)
SELECT branch_id, accounts
FROM per_branch
WHERE accounts > (SELECT AVG(accounts) FROM per_branch)
ORDER BY accounts DESC, branch_id;
branch_id  accounts
---------  --------
        1        87
        2        79
        5        76
(3 rows)

Departments with more courses than the average department:

WITH per_department AS (
    SELECT department_id, COUNT(*) AS courses FROM courses GROUP BY department_id
)
SELECT department_id, courses
FROM per_department
WHERE courses > (SELECT AVG(courses) FROM per_department)
ORDER BY courses DESC, department_id;
department_id  courses
-------------  -------
            2        4
(1 row)

per_category is used twice: once as the table to read and once inside the average. Without a CTE you would repeat the whole GROUP BY query.

3. CTE and join

A CTE is a table, so you can join it to others:

WITH sales AS (
    SELECT product_id, SUM(quantity) AS units FROM order_items GROUP BY product_id
)
SELECT p.name, s.units
FROM sales AS s
JOIN products AS p ON p.product_id = s.product_id
ORDER BY s.units DESC, p.name
LIMIT 4;
name            units
--------------  -----
Pruning shears    271
Gel pens (10)     251
Storage box       242
Chopping board    236
(4 rows)
WITH activity AS (
    SELECT account_id, COUNT(*) AS txns FROM transactions GROUP BY account_id
)
SELECT a.account_id, a.account_type, t.txns
FROM activity AS t
JOIN accounts AS a ON a.account_id = t.account_id
ORDER BY t.txns DESC, a.account_id
LIMIT 4;
account_id  account_type  txns
----------  ------------  ----
        24  savings         37
       254  savings         37
       387  savings         36
        39  savings         35
(4 rows)
WITH sizes AS (
    SELECT section_id, COUNT(*) AS students FROM enrollments GROUP BY section_id
)
SELECT c.code, s.term, z.students
FROM sizes AS z
JOIN sections AS s ON s.section_id = z.section_id
JOIN courses AS c ON c.course_id = s.course_id
ORDER BY z.students DESC, c.code, s.term
LIMIT 4;
code     term         students
-------  -----------  --------
ART101   2026-Spring        34
ART201   2026-Spring        34
ART201   2025-Autumn        33
LANG101  2025-Spring        32
(4 rows)

4. CTE, view or derived table

Lives Reusable Use for
derived table inside one FROM no a quick one-off step
CTE (WITH) one statement several times in that statement a readable, named step
view in the database by any query a step many queries share

A CTE is not a saved result either: the database may run its query each time it is used.

5. The shape of WITH

  • WITH comes before the SELECT (or before an INSERT, UPDATE or DELETE).
  • The CTE query must give every column a name.
  • A CTE can list column names: WITH t(a, b) AS (...).
  • Several CTEs are separated by commas (lesson 7.6).
WITH squares(n, square) AS (
    SELECT 3, 9 UNION ALL SELECT 4, 16 UNION ALL SELECT 5, 25
)
SELECT n, square FROM squares ORDER BY n;
n  square
-  ------
3       9
4      16
5      25
(3 rows)
WITH squares(n, square) AS (
    SELECT 3, 9 UNION ALL SELECT 4, 16 UNION ALL SELECT 5, 25
)
SELECT n, square FROM squares ORDER BY n;
n  square
-  ------
3       9
4      16
5      25
(3 rows)
WITH squares(n, square) AS (
    SELECT 3, 9 UNION ALL SELECT 4, 16 UNION ALL SELECT 5, 25
)
SELECT n, square FROM squares ORDER BY n;
n  square
-  ------
3       9
4      16
5      25
(3 rows)

Worked example: from nested to WITH

Nested With WITH
SELECT ... FROM (SELECT ... ) AS t WHERE ... WITH t AS (SELECT ...) SELECT ... FROM t WHERE ...

Same result, but the inner query is now first, named, and the outer query is short. The queries are made up.

Common mistakes

  • Putting WITH after the SELECT.
  • Unnamed columns in the CTE query.
  • Assuming the CTE is stored or fast. It is only a name for a query.
  • Forgetting the comma between several CTEs.

Key takeaways

  • WITH name AS (query) SELECT ... names a step; the query then reads top to bottom.
  • A CTE can be used several times in the same statement and joined like a table.
  • It lives for one statement only; a view lives in the database.
  • Give every column of the CTE a name.

Practice

1. Write the first line of a CTE named totals.

Show answer

WITH totals AS (

2. How long does a CTE exist?

Show answer

For the one statement that follows it.

3. What is the advantage over a derived table?

Show answer

It has a name, comes first so the query reads top to bottom, and can be used several times.

4. How do you give a CTE column names without aliases?

Show answer

List them after the name: WITH t(a, b) AS (...).

5. Is a CTE a saved result?

Show answer

No, it is only a name for a query that runs with the statement.

6. When do you prefer a view?

Show answer

When many queries share the step, so it should live in the database.