Sub topic 1
A quick refresher on WITH and common table expressions
A common table expression, or CTE, is a named query result that you define with WITH and use in the statement that follows it. A CTE helps you split a long query into clear steps. This chapter assumes you know SELECT, WHERE, ORDER BY, joins, grouping, and basic subqueries.
Prerequisites
You should be able to:
- Select rows from a table.
- Filter rows with
WHERE. - Join related tables.
- Group rows and calculate aggregates such as
SUMandCOUNT. - Read a subquery in a
FROMorWHEREclause.
Why use a CTE?
Suppose you need the average order total, then want to list only orders above that average. Without a CTE, you might repeat the average calculation inside another query. A CTE gives that intermediate result a name:
WITH average_order AS (
SELECT AVG(total) AS average_total
FROM orders
)
SELECT o.id, o.total
FROM orders AS o
CROSS JOIN average_order AS a
WHERE o.total > a.average_total
ORDER BY o.total DESC;The query has two parts:
- The CTE named
average_ordercalculates one value. - The main query reads that value and filters
orders.
The CTE exists only while this statement runs. It does not create a permanent table or view.
The basic shape
A nonrecursive CTE follows this pattern:
WITH cte_name AS (
SELECT ...
)
SELECT ...
FROM cte_name;You can define multiple CTEs by separating them with commas. Later CTEs can use earlier ones:
WITH recent_orders AS (
SELECT id, customer_id, total
FROM orders
WHERE order_date >= DATE '2026-01-01'
),
customer_totals AS (
SELECT customer_id, SUM(total) AS total_spent
FROM recent_orders
GROUP BY customer_id
)
SELECT customer_id, total_spent
FROM customer_totals
WHERE total_spent >= 1000
ORDER BY total_spent DESC;This creates a readable flow:
flowchart TD
A[orders] --> B[recent_orders]
B --> C[customer_totals]
C --> D[Final SELECT]The database may optimize a CTE in different ways. Depending on the database and query, it may merge the CTE into the main query or temporarily materialize its result. Therefore, treat a CTE primarily as a query-organization tool, not automatically as a performance feature.
CTEs compared with subqueries
A CTE and a subquery can often express the same logic. A CTE is usually easier to read when:
- The intermediate result has a meaningful name.
- The query has several stages.
- You need to refer to the same intermediate result more than once.
- You are preparing to write a recursive CTE.
A subquery can be a better choice for a short calculation used only once. Choose the form that makes the data flow easiest to verify.
| Technique | Best use | Main limitation |
|---|---|---|
| CTE | Named, multi-step query logic | Scope ends with the statement |
| Subquery | Small, local calculation | Can become difficult to read when nested |
| View | Reusable saved query | Requires database schema management |
Preparing for recursive CTEs
A recursive CTE adds a second query joined with UNION ALL. The first query supplies starting rows, called the anchor member. The second query produces more rows from rows already found. The next chapters build on the same WITH structure you have used here.
Exercise
Rewrite a query that calculates SUM(total) from orders and then selects rows from that result using a CTE named order_summary.
Show answer
Use WITH order_summary AS (SELECT SUM(total) AS grand_total FROM orders) SELECT grand_total FROM order_summary;