Request a demo

BigQuery · Query syntax

BigQuery WITH RECURSIVE

WITH RECURSIVE defines a CTE that references itself, so a query can walk hierarchies and graphs of unknown depth: org charts, category trees, dependency lineage. BigQuery stops a recursive CTE with an error after 500 iterations.

GoogleSQL for BigQuery · Checked against the official reference in November 2026

A recursive CTE has a base term, UNION ALL, and a recursive term that references the CTE itself exactly once. BigQuery runs the base term first; each following iteration runs the recursive term against the rows produced by the previous iteration, and the rows of every iteration are added to the result. Recursion stops when an iteration returns no rows. The RECURSIVE keyword is required as soon as any CTE in the WITH clause refers to itself, and it also lets CTEs reference ones defined later in the clause.

The base term decides the column names and types; the recursive term must return the same number of columns with types that coerce to them. That is why a depth counter that starts as 1 (INT64) works, while a path that starts as a short literal string is fine but a NULL in the base term needs a CAST(NULL AS STRING). Only UNION ALL is allowed (no UNION DISTINCT), and the recursive reference cannot be aggregated, windowed, used with LIMIT or ORDER BY, put on the outer side of an outer join, or placed in an expression subquery.

The iteration limit is 500. A cycle in the data (A reports to B, B reports to A) recurses until it hits the limit and fails, so track the visited path and stop when a node repeats, or cap the depth explicitly. Unlike ordinary CTEs, recursive CTEs are materialized, and each iteration is a step of query work: deep recursion over large tables is slow and slot-hungry. WITH RECURSIVE is only allowed at the top level of a query, not in UDFs or materialized views, and there is no CREATE RECURSIVE VIEW, but a normal view can contain WITH RECURSIVE.

Syntax

WITH RECURSIVE
  cte_name AS (
    base_query
    UNION ALL
    recursive_query  -- references cte_name once
  )[, other_cte AS (...)]
SELECT ... FROM cte_name

Arguments and return value

ArgumentDescription
base_queryNon-recursive starting rows. Fixes the column names and types of the CTE.
recursive_queryReads the previous iteration's rows through exactly one reference to the CTE. Must return compatible columns and eventually return no rows.

Returns: All rows produced by the base term and by every iteration of the recursive term.

Examples

Walk an org chart with depth and path

WITH RECURSIVE
  employees AS (
    SELECT 1 AS id, 'Maria' AS name, CAST(NULL AS INT64) AS manager_id UNION ALL
    SELECT 2, 'Jonas', 1 UNION ALL
    SELECT 3, 'Aiko', 1 UNION ALL
    SELECT 4, 'Lena', 2
  ),
  chain AS (
    SELECT id, name, 1 AS depth, name AS path
    FROM employees
    WHERE manager_id IS NULL
    UNION ALL
    SELECT e.id, e.name, c.depth + 1, CONCAT(c.path, ' > ', e.name)
    FROM employees AS e
    JOIN chain AS c ON e.manager_id = c.id
  )
SELECT id, depth, path
FROM chain
ORDER BY id;
Result
iddepthpath
11Maria
22Maria > Jonas
32Maria > Aiko
43Maria > Jonas > Lena

Generate a series with a stop condition

The recursive term returns nothing once n reaches 5, which ends the recursion. For plain number or date series, GENERATE_ARRAY and GENERATE_DATE_ARRAY are simpler.

WITH RECURSIVE seq AS (
  SELECT 1 AS n
  UNION ALL
  SELECT n + 1 FROM seq WHERE n < 5
)
SELECT ARRAY_AGG(n ORDER BY n) AS numbers
FROM seq;
Result
numbers
[1, 2, 3, 4, 5]

Downstream lineage with cycle protection

Finds every table downstream of raw.orders. The visited array stops the walk if the dependency graph contains a loop, instead of running into the 500-iteration limit.

WITH RECURSIVE
  edges AS (
    SELECT 'raw.orders' AS upstream, 'stg.orders' AS downstream UNION ALL
    SELECT 'stg.orders', 'mart.revenue' UNION ALL
    SELECT 'mart.revenue', 'stg.orders'
  ),
  lineage AS (
    SELECT downstream AS table_name, 1 AS hops, ['raw.orders', downstream] AS visited
    FROM edges
    WHERE upstream = 'raw.orders'
    UNION ALL
    SELECT e.downstream, l.hops + 1, ARRAY_CONCAT(l.visited, [e.downstream])
    FROM lineage AS l
    JOIN edges AS e ON e.upstream = l.table_name
    WHERE e.downstream NOT IN UNNEST(l.visited)
  )
SELECT table_name, hops
FROM lineage
ORDER BY hops;
Result
table_namehops
stg.orders1
mart.revenue2

Common mistakes

  • Recursing over cyclic data. A loop never produces an empty iteration, and the query fails with "A recursive CTE has reached the maximum number of iterations: 500." Track visited nodes or add WHERE depth < n.
  • Writing WITH instead of WITH RECURSIVE. The self-reference is then read as a table name and fails with Table "cte" must be qualified with a dataset.
  • Letting the base term fix a too-narrow type. If the base term yields NULL or an INT64 where later rows need STRING or FLOAT64, cast it in the base term.
  • Using UNION DISTINCT to deduplicate as you recurse, as in PostgreSQL's UNION. BigQuery allows only UNION ALL; deduplicate in the final SELECT and guard against cycles explicitly.

Cost and performance

  • Each iteration is a separate step of query execution, and on-demand you are billed for the bytes processed across all of them. Join the recursive term to a small, pre-filtered edge table rather than to a large raw table.
  • Recursive CTEs are materialized, unlike plain CTEs, so referencing the result several times does not rerun the recursion.

FAQ

What is the recursion limit in BigQuery?

500 iterations per recursive CTE. Exceeding it fails the query; the docs suggest checking for infinite recursion or splitting the work across several recursive CTEs or a loop.

How do I query a hierarchy (parent-child table) in BigQuery?

Use a recursive CTE whose base term selects the roots (WHERE parent_id IS NULL) and whose recursive term joins children to the previous level, carrying depth and path columns, as in the first example.

Can I use WITH RECURSIVE in a view?

Yes. CREATE RECURSIVE VIEW does not exist, but CREATE VIEW v AS WITH RECURSIVE ... works. Materialized views and UDFs cannot contain recursive CTEs.

Errors you may hit

More query syntax

All BigQuery query syntax · All statements and clauses · BigQuery error messages

Observability for every BigQuery table, in about 15 minutes

Masthead detects freshness, volume and schema anomalies, monitors pipeline errors and maps column-level lineage across all your projects, from logs and metadata only.