Sub topic 2
Where a CTE name is visible
This chapter assumes you know SELECT, WHERE, JOIN, and GROUP BY, and that you have read the earlier chapters on basic CTE syntax. The examples use PostgreSQL 12 or later.
A CTE name exists only inside the single statement that defines it. The WITH clause can define several CTEs, and each one can read the CTEs defined before it. The main query can read all of them.
WITH big_orders AS (
SELECT id, customer_id, amount
FROM orders
WHERE amount > 500
)
SELECT customer_id, COUNT(*) AS n
FROM big_orders
GROUP BY customer_id;Once the statement ends, big_orders no longer exists. Running SELECT * FROM big_orders; in a later statement fails with "relation does not exist" unless a real table has that name.
Recursive CTEs: anchor member, recursive member, and UNION ALL
A recursive CTE has two parts joined by UNION ALL. The anchor member runs once and produces the starting rows. The recursive member references the CTE's own name. Each pass reads only the rows produced by the previous pass, and it stops when it returns no rows.
WITH RECURSIVE numbers(n) AS (
SELECT 1
UNION ALL
SELECT n + 1 FROM numbers WHERE n < 5
)
SELECT n FROM numbers;Stopping recursion: conditions, depth limits, and cycle guards
A recursive member with no stop condition runs forever. Use a WHERE condition on the recursive member to end the loop. For graphs that contain cycles, a depth limit and a path check together protect the query.
WITH RECURSIVE walk AS (
SELECT 1 AS id, 0 AS depth, ARRAY[1] AS path
UNION ALL
SELECT e.to_id, w.depth + 1, w.path || e.to_id
FROM walk w
JOIN edges e ON e.from_id = w.id
WHERE w.depth < 10
AND e.to_id <> ALL (w.path)
)
SELECT id, depth FROM walk;The depth < 10 condition caps the number of rounds. The <> ALL (w.path) check skips any node already on the current path, so a cycle cannot repeat forever.
Exercise
The numbers example stops at 5. Which change makes it stop at 3 instead, and what is the result?
Show answer
Change the condition to WHERE n < 3. The result is the rows 1, 2, and 3.