runtime
31 / 88

lesson 31 Dates, strings & subqueries · intermediate

Readable queries with CTEs

Break a query into named, readable steps.

the idea

WITH names a temporary query result for this statement. Common table expressions help you separate a complicated question into understandable stages. They do not create permanent tables.

tables in this lesson

The challenges use this data. Each column shows its type underneath; → marks a link to another table.

orders6 columns · 12 rows
idinteger · keycustomer_idintegerproduct_idintegerquantityintegerstatustextordered_attext
101112paid2025-01-01
102231paid2025-01-02
103121paid2025-01-05
104352pending2025-01-08
105445paid2025-02-01

showing 5 of 12 rows

products4 columns · 6 rows
idinteger · keynametextcategorytextpricereal
1NotebookStationery12
2Desk lampHome45
3KeyboardTech80
4Pen setStationery8
5HeadphonesTech120

showing 5 of 6 rows

example

The idea in one query. Press Run to see what it returns; running examples never affects your progress.

example.sql
WITH totals AS (
  SELECT customer_id, SUM(quantity) AS units
  FROM orders
  GROUP BY customer_id
)
SELECT customer_id, units
FROM totals
WHERE units > 3;

Watch for: A CTE exists only for the statement that follows it.

build it step by step

Each step changes one thing. Run them in order and watch the result change.

  1. Name an intermediate total. WITH defines a temporary result you can read like a table. Here each customer gets a units total before filtering.

    step-1.sql
    SELECT customer_id, SUM(quantity) AS units
    FROM orders
    GROUP BY customer_id
    ORDER BY customer_id;
  2. Filter the named CTE. The outer query reads totals as if it were a table. CTEs make multi-step logic easier to follow than nested subqueries.

    step-2.sql
    WITH totals AS (
      SELECT customer_id, SUM(quantity) AS units
      FROM orders
      GROUP BY customer_id
    )
    SELECT customer_id, units
    FROM totals
    WHERE units > 3;

challenge 1

Use a CTE to return customer_id and units for customers whose total quantity exceeds 3.

Return customer_idunitsany row order

challenge-1.sql
 
To master this lesson, solve both challenges without hints and pass the concept check. 3 of 3 to go.