Module 5 · Advanced queries

Break queries into steps with CTEs

By the end you will be able to name a step of a query to use it later.

About 14 min

0 of 52 lessons

Before you start, you need

Answer questions with subqueries · Filter groups with HAVING

Give an intermediate result a name

A long query is easier to follow if you split off a step and give it a name. For example, you can call shipped the list of orders with that status, and then query that list.

WITH defines that result with a name. This tool is called a CTE, short for common table expression. Write the name, AS and the query in parentheses; then comes the query that uses it.

The name is used in FROM just like a table name. Choose one that explains its rows: shipped contains orders and customer_totals would hold a summary per customer. That way you know what you are reading at each step.

The CTE exists only for that statement. It does not store a new table you can open in another run. To check the intermediate step, run the query that defines it and check its rows before carrying on.

Minimal syntax
WITH name AS (SELECT ... FROM ...)
SELECT ... FROM name;

See it in action

We want to prepare the shipped orders and read that result.

SQL
WITH shipped AS (
  SELECT id, total
  FROM orders
  WHERE status = 'shipped'
)
SELECT id, total
FROM shipped;
Example result: 8 of 9 rows
idtotal
101128.4
104179
1061088
10736.9
11061.5
11254
11398
11524
  1. WITH defines shipped as the result of the filter. Each row is still one order.
  2. The outer query reads id and total from shipped just as it would read those columns from a table.
  3. The name exists only during this statement. A separate query cannot use shipped.
  4. Once the input has been checked, you can summarise it in the outer query. If a summary fails, first check which rows the CTE supplied.

Practice with help

Getting things wrong is part of learning: you can run your query as many times as you like and nothing is lost. If you get stuck, open a hint (each one reveals a bit more) and save the solution for last.

Guided practice

First, a minimal CTE

Not started

Create a CTE called shipped with id and total for the shipped orders. Return id and total from that CTE.

Expected result: 9 rows with the columns id, total, in that order. Row order does not matter.

View tables and data

Open this panel to see the full data.

Use a named summary

Guided practice

Use a named summary

Not started

Prepare the non-cancelled orders in a CTE called valid_orders. Then summarise and filter that result using these rules:

  • The CTE returns customer_id and total for orders whose status is not cancelled.
  • Group by customer_id and show customer_id and the sum of total, rounded to two decimal places, with the alias valid_total.
  • Keep only the customers whose sum is at least 200.
  • Sort by valid_total from highest to lowest, and by customer_id from lowest to highest when there is a tie.

Expected result: 5 rows with the columns customer_id, valid_total, in that order. Keep the row order requested.

View tables and data

Open this panel to see the full data.

Your turn

Solve this variation. Spot the part that has changed before you look for help.

Practice

Then another summary

Not started

Use a CTE called valid with customer_id and total for non-cancelled orders. Return customer_id and COUNT(*) as orders per customer.

Expected result: 10 rows with the columns customer_id, orders, in that order. Row order does not matter.

View tables and data

Open this panel to see the full data.

Key takeaways

  • WITH names an intermediate result.
  • The outer query can read it.
  • A CTE lasts for one statement.

Next: Turn a summary into a table with a subquery in FROM