Subqueries and CTEs · Lesson 54 of 64

SQL Chained CTEs

What you will learn

  • How to write several CTEs separated by commas
  • How a later CTE uses an earlier one
  • How to test each step on its own
  • How to keep the final query short

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. A chain of steps

List the CTEs one after another, separated by commas (only one WITH). Each can use the ones written above it:

Customers whose total spending is above the average customer:

WITH line_totals AS (
    SELECT o.customer_id, ROUND(oi.quantity * oi.unit_price, 2) AS line_total
    FROM orders AS o
    JOIN order_items AS oi ON oi.order_id = o.order_id
    WHERE o.status <> 'cancelled'
),
per_customer AS (
    SELECT customer_id, ROUND(SUM(line_total), 2) AS spent FROM line_totals GROUP BY customer_id
)
SELECT customer_id, spent
FROM per_customer
WHERE spent > (SELECT AVG(spent) FROM per_customer)
ORDER BY spent DESC, customer_id
LIMIT 5;
customer_id    spent
-----------  -------
         72   1776.7
        395  1604.92
        404  1600.02
         59  1587.68
        134  1571.75
(5 rows)

Accounts whose total deposits are above the average account:

WITH deposits AS (
    SELECT account_id, amount_cents FROM transactions WHERE kind = 'deposit'
),
per_account AS (
    SELECT account_id, SUM(amount_cents) AS deposited FROM deposits GROUP BY account_id
)
SELECT account_id, deposited
FROM per_account
WHERE deposited > (SELECT AVG(deposited) FROM per_account)
ORDER BY deposited DESC, account_id
LIMIT 5;
account_id  deposited
----------  ---------
       398     606300
       186     576900
       295     556300
       357     544900
       238     501500
(5 rows)

Students whose total points are above the average student:

WITH graded AS (
    SELECT student_id, points FROM submissions WHERE points IS NOT NULL
),
per_student AS (
    SELECT student_id, ROUND(SUM(points), 2) AS total_points FROM graded GROUP BY student_id
)
SELECT student_id, total_points
FROM per_student
WHERE total_points > (SELECT AVG(total_points) FROM per_student)
ORDER BY total_points DESC, student_id
LIMIT 5;
student_id  total_points
----------  ------------
        81        1188.1
       235        1091.0
       181        1008.5
       319         953.3
       124         950.3
(5 rows)

Read it from the top: first pick the rows, then summarise per owner, then compare with the average. Each step is small enough to check.

2. Test a step alone

When a long query gives a strange answer, run each CTE on its own, in order. Replace the final SELECT with SELECT * FROM step LIMIT 5:

WITH line_totals AS (
    SELECT o.customer_id, ROUND(oi.quantity * oi.unit_price, 2) AS line_total
    FROM orders AS o
    JOIN order_items AS oi ON oi.order_id = o.order_id
    WHERE o.status <> 'cancelled'
)
SELECT * FROM line_totals ORDER BY customer_id, line_total LIMIT 3;
customer_id  line_total
-----------  ----------
          1         9.0
          1        17.0
          1        18.7
(3 rows)
WITH deposits AS (
    SELECT account_id, amount_cents FROM transactions WHERE kind = 'deposit'
)
SELECT * FROM deposits ORDER BY account_id, amount_cents LIMIT 3;
account_id  amount_cents
----------  ------------
         1          4300
         1         19400
         1         30800
(3 rows)
WITH graded AS (
    SELECT student_id, points FROM submissions WHERE points IS NOT NULL
)
SELECT * FROM graded ORDER BY student_id, points LIMIT 3;
student_id  points
----------  ------
         1     7.5
         1     7.8
         1    13.2
(3 rows)

This is the best debugging habit for SQL: look at the data between the steps.

3. Compare two summaries

Two CTEs can be joined to each other. Here, a count and a total for the same owner are put side by side:

WITH order_counts AS (
    SELECT customer_id, COUNT(*) AS orders FROM orders GROUP BY customer_id
),
review_counts AS (
    SELECT customer_id, COUNT(*) AS reviews FROM reviews GROUP BY customer_id
)
SELECT o.customer_id, o.orders, COALESCE(r.reviews, 0) AS reviews
FROM order_counts AS o
LEFT JOIN review_counts AS r ON r.customer_id = o.customer_id
ORDER BY o.orders DESC, o.customer_id
LIMIT 4;
customer_id  orders  reviews
-----------  ------  -------
         72      17        5
        292      17        5
        134      15        5
         42      14        4
(4 rows)
WITH account_counts AS (
    SELECT customer_id, COUNT(*) AS accounts FROM accounts GROUP BY customer_id
),
loan_counts AS (
    SELECT customer_id, COUNT(*) AS loans FROM loans GROUP BY customer_id
)
SELECT a.customer_id, a.accounts, COALESCE(l.loans, 0) AS loans
FROM account_counts AS a
LEFT JOIN loan_counts AS l ON l.customer_id = a.customer_id
ORDER BY a.accounts DESC, a.customer_id
LIMIT 4;
customer_id  accounts  loans
-----------  --------  -----
         96         7      0
        142         6      0
        230         6      0
        236         6      0
(4 rows)
WITH enrollment_counts AS (
    SELECT student_id, COUNT(*) AS enrollments FROM enrollments GROUP BY student_id
),
absence_counts AS (
    SELECT student_id, COUNT(*) AS absences FROM attendance WHERE status = 'absent' GROUP BY student_id
)
SELECT e.student_id, e.enrollments, COALESCE(a.absences, 0) AS absences
FROM enrollment_counts AS e
LEFT JOIN absence_counts AS a ON a.student_id = e.student_id
ORDER BY e.enrollments DESC, e.student_id
LIMIT 4;
student_id  enrollments  absences
----------  -----------  --------
        37            8         4
        16            7         3
        74            7         5
        81            7         3
(4 rows)

Summarising each table separately and joining the summaries avoids the repeated-rows trap of joining two "many" tables first (lesson 4.8).

4. Habits for chains

  • Name steps by what they hold (per_customer, deposits), not t1, t2.
  • One idea per step: filter, summarise, or join, not all three.
  • Keep the final query short: just the comparison and the ordering.
  • Put the filters in the early steps so later steps handle fewer rows.

Worked example: plan a chain

"Which departments have more teachers than the average department?"

Step CTE Holds
1 per_department department_id, number of teachers
2 final query per_department rows above AVG(teachers)
3 join the names departments.name, added to the final query

Write the steps in plain words first; each one becomes a CTE. The question is from the School sample.

Common mistakes

  • A second WITH keyword instead of a comma.
  • Using a CTE before it is defined (it must be above).
  • Unclear names like a, b, c.
  • Joining two summaries on the wrong key.
  • Never looking at the data between steps.

Key takeaways

  • One WITH, then CTEs separated by commas; each can use the ones above it.
  • Plan the steps in words, then write one CTE per idea.
  • Test each step with SELECT * FROM step LIMIT 5.
  • Summarise tables separately before joining them.

Practice

1. How do you separate two CTEs?

Show answer

With a comma, after the closing bracket of the first.

2. Can the second CTE use the first?

Show answer

Yes. A CTE can use any CTE written above it.

3. How do you check one step of a long query?

Show answer

Keep the WITH part up to that step and finish with SELECT * FROM step LIMIT 5.

4. Why summarise two tables separately before joining?

Show answer

Joining two "many" tables first repeats rows and inflates the counts and sums.

5. Where should filters go in a chain?

Show answer

In the early steps, so later steps work on fewer rows.

6. Give a good name for a CTE holding the total per customer.

Show answer

per_customer (or customer_totals): a name that says what it holds.