Sub topic 4
Where a CTE Name Is Visible
Assume you already know SELECT, WHERE, JOIN, GROUP BY, and aggregate functions such as SUM. This chapter also assumes you have seen a subquery. A common table expression (CTE) is a named query result that exists only while one SQL statement runs.
A CTE belongs to one statement
A CTE name is visible inside the statement that follows its WITH clause. It is not a permanent table, and it is not available to the next statement.
WITH order_totals AS (
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
)
SELECT customer_id, total
FROM order_totals
WHERE total > 1000;Here, order_totals is visible to the final SELECT. After the semicolon, the name disappears. A later statement cannot query order_totals unless it defines the CTE again.
The CTE can be used anywhere the statement can use a table expression, including the FROM clause and joins.
Earlier CTEs are visible to later CTEs
When one WITH clause defines several CTEs, later CTEs can refer to earlier ones. This creates a left-to-right pipeline.
WITH order_totals AS (
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
),
high_value_customers AS (
SELECT customer_id, total
FROM order_totals
WHERE total > 1000
)
SELECT c.name, h.total
FROM customers AS c
JOIN high_value_customers AS h
ON h.customer_id = c.id;The second CTE reads from order_totals. The final query reads from high_value_customers.
A CTE cannot normally refer to a CTE that appears later in the same list. For example, if high_value_customers appeared before order_totals, its reference would fail because order_totals had not yet been introduced. Recursive CTEs are a special case because they are explicitly allowed to refer to themselves.
| Reference | Usually allowed? | Reason |
|---|---|---|
| Final query reads an earlier CTE | Yes | The CTE is in scope for the statement |
| Later CTE reads an earlier CTE | Yes | CTEs form a left-to-right pipeline |
| Earlier CTE reads a later CTE | No | The later name is not defined yet |
| A later statement reads the CTE | No | CTE scope ends at the semicolon |
| A recursive CTE reads itself | Yes, with recursive syntax | Recursion is explicitly enabled |
Scope inside nested queries
A CTE is generally visible to subqueries nested inside the same statement. This lets a CTE provide shared input to a deeper query.
WITH order_totals AS (
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
)
SELECT c.name
FROM customers AS c
WHERE EXISTS (
SELECT 1
FROM order_totals AS t
WHERE t.customer_id = c.id
AND t.total > 1000
);The nested EXISTS query can read order_totals because it belongs to the same overall statement.
A nested query can also have its own table or CTE name that hides, or shadows, an outer name. Shadowing makes a query harder to read because the same name can refer to different result sets in different parts of the statement. Use distinct, descriptive names such as customer_totals and monthly_totals.
Column names and aliases
The CTE name identifies the result set. Its output columns come from the CTE's SELECT list. You can also specify the column names directly after the CTE name.
WITH order_totals(customer_id, total_amount) AS (
SELECT customer_id, SUM(amount)
FROM orders
GROUP BY customer_id
)
SELECT customer_id, total_amount
FROM order_totals;The number of declared column names should match the number of selected columns. Clear column names reduce confusion when several CTEs are joined.
A scope-checking method
When a CTE query produces a name error, check it in this order:
- Find the
WITHclause that defines the name. - Check whether the reference is in the same statement.
- Check whether the referenced CTE appears earlier in the list.
- Check for a local table, subquery, or CTE with the same name.
- Qualify columns with aliases, such as
totals.total, when several sources have similar columns.
Exercise
In the query pipeline WITH a AS (...), b AS (SELECT * FROM a) SELECT * FROM b;, which names can the final SELECT use, and which CTE can b use?
Show answer
The final SELECT can use both a and b. CTE b can use a because a appears earlier. A later statement cannot use either name.