Why it happens: the CTE does not exist in the next query
WITH active_customers AS (
SELECT id, name
FROM customers
WHERE active = 1
)
SELECT *
FROM active_customers;
SELECT COUNT(*)
FROM active_customers;The first statement can use active_customers. Once it ends at the semicolon, that CTE is no longer in scope. The second statement needs to define it again or query another real object.
How to fix it in SQL
The same CTE can be referenced several times within the statement that contains it. For example, you can compare it with itself, use it in subqueries or build other CTEs on top of it.
WITH active_customers AS (
SELECT id, name
FROM customers
WHERE active = 1
)
SELECT
(SELECT COUNT(*) FROM active_customers) AS total,
(SELECT MIN(id) FROM active_customers) AS first_id;How to check it
Check where the statement ends: the semicolon also ends the CTE's scope.
How to avoid it next time
WITH does not create a persistent table.
Related cases worth checking
If you need to reuse it across statements, choose another mechanism
The solution depends on the intent:
- Repeat the logic in a few queries: declare the CTE again.
- Share a stable query: consider a view.
- Keep intermediate results during a session or process: a temporary table may be a better fit, with syntax and a life cycle specific to each engine.
- Persist data: use an ordinary table if they really are part of the model.
Do not automatically turn a CTE into a permanent table: first decide whether you want to reuse a definition or store data.
You can chain several CTEs within the same WITH
WITH active_customers AS (
SELECT id, name
FROM customers
WHERE active = 1
),
first AS (
SELECT id, name
FROM active_customers
WHERE id <= 100
)
SELECT *
FROM first;The CTEs share the statement and can form a readable sequence of transformations.