BeginnerCoder

Lesson 12 — CTEs (WITH)

CTEs: name a step, then use it

A CTE (Common Table Expression) is written WITH name AS (SELECT ...) before the main query. It gives a step a readable name, like a variable in Python. The main query can then SELECT from it as if it were a table.

WITH totals AS (SELECT customer, SUM(total) AS spent FROM orders GROUP BY customer)
SELECT * FROM totals WHERE spent > 100

Why it matters: long reports become a readable sequence of named steps instead of nested brackets.

Want it another way?
Task

Write the main query: select customer and spent from totals where spent > 50, sorted by spent descending.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.