Sub topic 4
Where a CTE name is visible
A CTE name is only usable in certain places. This chapter maps those places. It also covers the errors you get outside them and the one case where a wrong reference doesn't fail and gives you wrong results instead.
This chapter assumes you can write a basic WITH clause and chain two or three CTEs, as covered in the previous chapters. Examples use PostgreSQL. Where other databases differ, the text says so.
The one-statement rule
A CTE exists for exactly one statement: the one that carries the WITH clause. The database does not save it. When the statement finishes, the name is gone. Nothing is added to the catalog, and no other session or statement can see it.
The following setup is used throughout the chapter:
CREATE TABLE orders (
id integer PRIMARY KEY,
customer_id integer NOT NULL,
amount numeric(10,2) NOT NULL,
order_date date NOT NULL
);
INSERT INTO orders VALUES
(1, 1, 400.00, DATE '2026-01-05'),
(2, 1, 700.00, DATE '2026-02-10'),
(3, 2, 250.00, DATE '2026-02-11'),
(4, 3, 1500.00, DATE '2026-03-01');Now run two statements in a row:
WITH t AS (SELECT 1 AS n)
SELECT n FROM t;
SELECT n FROM t;The first statement returns one row. The second fails with relation "t" does not exist. If you need a name to outlive one statement, use a view, a temporary table, or a CREATE TABLE AS. A CTE won't do it.
The visibility rules
Inside the statement, a CTE name is visible in three places and invisible in one:
| Place | Can it use the CTE name? |
|---|---|
| The main query that follows the `WITH` clause | Yes |
| A CTE defined later in the same `WITH` clause | Yes |
| A subquery anywhere in the main query or in a later CTE | Yes |
| A CTE defined earlier in the same `WITH` clause | No (non-recursive CTEs) |
| Any other statement | No |
The rule behind the table is that a CTE can see the CTEs written above it, never those written below. Read a WITH clause from top to bottom, like a script.
Every arrow points forward. No arrow goes from a later definition back to an earlier one.
Later CTEs and subqueries can use earlier CTEs
WITH customer_totals AS (
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
),
big_spenders AS (
SELECT customer_id, total
FROM customer_totals
WHERE total > 1000
)
SELECT b.customer_id,
b.total,
(SELECT AVG(total) FROM customer_totals) AS avg_total
FROM big_spenders b;This returns customers 1 (1100.00) and 3 (1500.00), each with an average of 950. customer_totals is used twice: by big_spenders and by the scalar subquery in the main select list. Subqueries are part of the statement, so they see every CTE the main query sees.
Earlier CTEs cannot use later ones
Swap the order of the two definitions:
WITH big_spenders AS (
SELECT customer_id, total
FROM customer_totals
WHERE total > 1000
),
customer_totals AS (
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
)
SELECT * FROM big_spenders;PostgreSQL stops with relation "customer_totals" does not exist. When you see that message and the CTE is plainly defined in the query, check the order first. The fix is to move the definition up.
Only output columns are visible
A CTE hides the tables behind it. The outer query sees the columns the CTE selects and nothing else:
WITH t AS (
SELECT customer_id FROM orders
)
SELECT amount FROM t;This fails with column "amount" does not exist, even though orders has that column. Select every column you will need later. If you rename columns, you can list the new names after the CTE name, as in WITH t(cust, total) AS (...). The outer query must then use the renamed columns.
Shadowing: a CTE name can hide a real table
A CTE name wins over a table or view with the same name, for the whole statement. This is called shadowing.
WITH orders AS (
SELECT * FROM orders WHERE amount > 500
)
SELECT COUNT(*) FROM orders;This returns 2. Two things happen here:
- Inside the CTE's own definition,
ordersstill means the real table. A non-recursive CTE cannot see itself, so the name resolves to the table. - In the main query,
ordersmeans the CTE. The real table is hidden.
Shadowing is legal and sometimes handy for testing a filtered version of a table without changing the rest of the query. But it can mislead readers. In a long query, someone might assume FROM orders reads every order when it reads only the filtered ones.
The silent version of the forward-reference error
The forward-reference error above is easy to spot because it fails loudly. It becomes dangerous when a real table has the same name as a CTE you defined later:
WITH recent AS (
SELECT * FROM daily_totals -- the real table, not the CTE below
),
daily_totals AS (
SELECT order_date, SUM(amount) AS total
FROM orders
GROUP BY order_date
)
SELECT * FROM recent;If a table named daily_totals exists, the first CTE reads that table, because the CTE of the same name is defined below it and isn't visible yet. The query runs without error and returns different data than you meant. If no such table exists, you get the usual "does not exist" error. So the same code can fail in one database and quietly return the wrong rows in another.
To avoid this, order definitions from the most basic to the most derived. Don't give a CTE the name of an existing table unless shadowing is the point.
Names must be unique within one WITH clause
Two CTEs in the same WITH clause cannot share a name:
WITH t AS (SELECT 1 AS n),
t AS (SELECT 2 AS n)
SELECT * FROM t;PostgreSQL rejects this with WITH query name "t" specified more than once. Since order matters and names are unique, each reference to a CTE name has exactly one meaning.
Nested WITH clauses
In PostgreSQL, you can put a WITH clause inside a subquery or inside another CTE's definition. The inner names are visible only inside the subquery that contains them:
SELECT *
FROM (
WITH inner_cte AS (SELECT 1 AS n)
SELECT n FROM inner_cte
) AS d;Referring to inner_cte from outside the parentheses is an error. If the inner clause reuses an outer name, the inner definition shadows the outer one inside its own subquery only.
Support for this varies:
| Database | `WITH` inside a subquery or CTE |
|---|---|
| PostgreSQL | Supported |
| MySQL 8.0 and later | Supported |
| SQLite | Supported |
| SQL Server | Not supported. A `WITH` clause cannot appear in a subquery, derived table, or CTE definition. |
If you must run on several databases, keep WITH at the top level. Nesting buys little over a flat chain, and flat chains are easier to read.
WITH and the statement it belongs to
The WITH clause attaches to one complete statement. Two forms are worth knowing.
Set operations. In a query that combines results with UNION, INTERSECT, or EXCEPT, the WITH clause at the start applies to the whole combined query, so every branch can use it:
WITH big AS (
SELECT customer_id FROM orders WHERE amount > 500
)
SELECT customer_id FROM big
UNION
SELECT customer_id FROM orders WHERE amount < 300;Data-modifying statements. INSERT, UPDATE, and DELETE can carry a WITH clause too, in PostgreSQL and in several other databases. The CTE is visible in the statement's WHERE clause, FROM or USING clause, and subqueries:
WITH big AS (
SELECT customer_id FROM orders WHERE amount > 1000
)
DELETE FROM orders
WHERE customer_id IN (SELECT customer_id FROM big);Placement differs between databases. In PostgreSQL the WITH goes before the statement keyword, as above. Some engines, such as older MySQL versions, do not support it for DELETE at all. Check your engine's documentation before relying on it.
Recursive CTEs: a name that sees itself
A recursive CTE is the one case where a CTE name is visible inside its own definition. That is the whole mechanism. The recursive member reads the CTE name to get the rows produced in the previous round.
The visibility is narrow:
- The name is visible only in the recursive member, not in the anchor member.
- PostgreSQL requires the self-reference to appear once and not inside a subquery or on the nullable side of an outer join. The rules for this are in the chapter on recursive CTEs.
- Everything else still works as described above. The recursive CTE is visible to later CTEs and the main query, and it is invisible to earlier ones.
Debugging visibility errors
When a CTE name is "not found" or resolves to the wrong thing, check these in order:
- Is the definition above the place where you use it? Move it up if not.
- Did you put a semicolon between the
WITHclause and the main query? A semicolon ends the statement and discards the CTEs. A stray;after a CTE's closing parenthesis produces this error. - Is there a comma between CTEs and none after the last one? A missing comma gives a syntax error. A trailing comma before the main
SELECTdoes too. - Does a real table share the CTE's name? If a query returns surprising rows, rename the CTE.
- Are you selecting a column the CTE didn't output?
- Are you running on SQL Server or an older MySQL, and using a nested
WITHor aWITHon aDELETE?
Summary of the rules
- A CTE lives for one statement. A semicolon ends it.
- A CTE can be used in the main query, in later CTEs, and in subqueries anywhere in the statement.
- A CTE cannot be used in earlier CTEs. For a non-recursive CTE, this includes itself.
- A CTE name hides a real table of the same name for the rest of the statement, except inside its own non-recursive definition.
- Names within one
WITHclause must be unique. - Outer queries see only the columns a CTE selects.
- Nested
WITHis a dialect feature. Avoid it if you need portability.
Exercise
A query defines WITH a AS (SELECT * FROM b), b AS (SELECT 1 AS x) SELECT * FROM a;. A real table named b also exists, with columns different from x. The query runs without error. Which b does a read, and why is this a risk?
Show answer
The real table b. The CTE b is defined below a, so it is not visible inside a's definition, and the name resolves to the table. The risk is that nothing fails: the query returns rows from the wrong source. Fix it by defining b first, or by giving the CTE a different name.
Exercise
You run WITH t AS (SELECT customer_id, amount FROM orders) SELECT customer_id, order_date FROM t;. What happens, and what are two ways to fix it?
Show answer
It fails with an error that column order_date does not exist, because the outer query sees only the columns that t selects. Fix it either by adding order_date to the select list inside t, or by joining orders in the outer query (which is rarely better than changing the CTE).
Exercise
Why does WITH orders AS (SELECT * FROM orders WHERE amount > 500) SELECT COUNT(*) FROM orders; work without RECURSIVE, and what changes if you add RECURSIVE?
Show answer
Without RECURSIVE, a CTE cannot see its own name, so orders inside the definition is the real table and orders in the main query is the CTE. With RECURSIVE in PostgreSQL, the name is visible inside its own definition, so the inner FROM orders refers to the CTE itself and the query is no longer a valid recursive CTE (it fails, because it has no anchor member).