SQL error · The query will not run

The CTE does not exist in the next query

Problem: A CTE is in scope only within the statement that WITH belongs to.

Solution: Reuse it within that statement, or use a view or temporary table if you need it across several queries.

Why it happens: the CTE does not exist in the next query

Two separate statements
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.

“The CTE does not exist in the next query” error messages by engine

The exact wording depends on the database. Compare these common messages with the one in your console.

EngineTypical message
PostgreSQLERROR: relation "active_customers" does not exist
MySQLERROR 1146 (42S02): Table 'store.active_customers' doesn't exist
SQL ServerMsg 208, Level 16: Invalid object name 'active_customers'.
OracleORA-00942: table or view does not exist
SQLiteError: no such table: active_customers

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.

One statement, one scope
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

CTE based on another CTE
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.