Module 04 · Lesson 4 of 16Detailed study · about 18 min

CTEs and bounded recursion

A CTE names an intermediate query within one statement. A recursive CTE repeatedly uses its previous result to build a hierarchy or sequence.

Understand the idea

A CTE is like a labeled step in a calculation: first summarize sales, then filter the summary. It improves readability but does not create a permanent table or guarantee materialization.

Key ideas in simple English
ConceptWhat it means
WITHNames a query result used later in the same statement.
AnchorThe starting rows of a recursive CTE.
Recursive memberProduces the next rows from the previous iteration.
Stop conditionPrevents endless recursion and unnecessary work.

A concrete example

The first CTE supplies rows; totals produces East 100 and West 25; the outer query keeps East 100.

Remember: The recursive predicate controls expansion. A real hierarchy also needs a strategy for cyclic relationships.

Explain it step by step · full theory

Let us understand the idea

A CTE is like a labeled step in a calculation: first summarize sales, then filter the summary. It improves readability but does not create a permanent table or guarantee materialization.

Recursion begins with an anchor, combines it with repeated work using UNION ALL, and stops when the recursive member produces no more rows. The column list makes each output position explicit.

Reason through the SQL

The number example starts at 1. Each step adds 1 while the previous number is below 4, so the result is 1, 2, 3, 4. The stop test is applied to the current input row, not after an unlimited loop.

For real hierarchies, detect cycles and consider a depth limit. A depth limit prevents unlimited expansion but can truncate legitimate paths. Snowflake restricts the recursive member: perform aggregates, window calculations and ordering outside that member.

Words used in this lesson
WITH
Names a query result used later in the same statement.
Anchor
The starting rows of a recursive CTE.
Recursive member
Produces the next rows from the previous iteration.
Stop condition
Prevents endless recursion and unnecessary work.

See how it works

Choose a step to explore the idea at your own pace.

Open the interactive explanation
Interactive explainer1 / 3

CTEs and bounded recursion

Input rows
Business question

Begin with the question

A CTE names an intermediate query within one statement. A recursive CTE repeatedly uses its previous result to build a hierarchy or sequence.

Automatic playback is off for reduced motion. Select any step or use Previous and Next. Illustrations explain behavior; they are not live measurements.

Read the complete diagram explanation
  1. Begin with the question

    A CTE names an intermediate query within one statement. A recursive CTE repeatedly uses its previous result to build a hierarchy or sequence.

  2. Choose the operation

    A CTE is like a labeled step in a calculation: first summarize sales, then filter the summary. It improves readability but does not create a permanent table or guarantee materialization.

  3. Check the meaning

    The recursive predicate controls expansion. A real hierarchy also needs a strategy for cyclic relationships.

Try the SQL or command

Read → predict → run in your learning environment → compare. You can also learn by reading without an account.

New to SQL? Where to run it and how to read it

A query is a question written in SQL. Snowflake runs it and returns a result table. This website shows examples; it does not connect to your account.

  1. No account yet? Read and predict the output first. Follow the account and Snowsight lesson when you are ready.
  2. For SQL practice, use a learning account in Snowsight and select an authorized role and warehouse. A role determines permissions; a warehouse supplies processing power. Follow the example’s database/schema setup when it refers to stored objects.
  3. Read the entire example, including comments beginning with --. Run the selected statement or labeled block in the stated order. Examples labeled Python, shell or HTTP belong in that client, not in a SQL editor.
  4. Compare values and row counts with the explained result. If an example deliberately causes an error, follow its rollback and cleanup steps before continuing.
SELECT / FROM
Choose the values to return / identify their input.
VALUES / COLUMN1
VALUES supplies tiny example rows. COLUMN1 means their first column, COLUMN2 their second.
AS / WITH
AS gives a result a readable name. WITH names a temporary query step within one statement.
NULL / ::
NULL means missing or unknown. The :: notation converts a value to a named data type.
Session
One connection and its settings. Keep related transaction steps in the same session.
Database.schema.table
A full address for stored data. It is separate from the warehouse that processes queries.

Need the L2_OBJECTS_LAB setup? Open the first database-object lesson →

Help with common practice errors
  • No active warehouse: select a warehouse your role can use. Do not assume you need to create a new one.
  • Object missing or not authorized: check the full name, required setup and active role. Ask the account owner for access if needed.
  • Object already exists: setup may already have run. Read the current state or choose a fresh lab name consistently; do not add OR REPLACE blindly.
  • Different result: check whether an earlier INSERT or UPDATE changed the data. VALUES examples provide their own fresh input for each statement.

Before running this lesson

Read first, then run manually in an authorized Snowflake learning session with a warehouse. Each WITH/VALUES example includes its own inputs and creates no stored tables. Expected results are illustrative, not live execution.

Name a summary before filtering it

SQL · example
WITH orders AS (SELECT COLUMN1 AS REGION, COLUMN2 AS AMOUNT
FROM VALUES ('East',40),('East',60),('West',25)),
totals AS (SELECT REGION, SUM(AMOUNT) AS SALES FROM orders GROUP BY REGION)
SELECT REGION, SALES FROM totals WHERE SALES >= 50 ORDER BY REGION;

What to expect and why

The first CTE supplies rows; totals produces East 100 and West 25; the outer query keeps East 100.

A small recursive sequence

SQL · example
WITH RECURSIVE numbers(n) AS (
 SELECT 1
 UNION ALL
 SELECT n + 1 FROM numbers WHERE n < 4
)
SELECT n FROM numbers ORDER BY n;

What to expect and why

Four rows are returned. The final ordering is outside the recursive member.

Expected result for the supplied input (not live output)
N
1
2
3
4

Check your understanding

Choose an answer, then check your reasoning. This is practice, not a scored test.

What stops this recursion?

Try it yourself

Change the bound from 4 to 6 and predict both the final value and row count.

Compare your reasoning

The result becomes 1 through 6: six rows, with 6 as the final value. The row containing 6 produces no further row.

Official sources and curriculum

Module 04 · See module scope