Request a demo

BigQuery · Query syntax

BigQuery WITH (CTE)

WITH defines named subqueries (common table expressions) that the rest of a query can reference like tables. In BigQuery a non-recursive CTE is not materialized: each reference runs it again, so a CTE over a large table used three times is scanned and billed three times.

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

WITH name AS (subquery) binds a query to a name for the duration of one query expression. You can define several CTEs separated by commas, and each one can reference the CTEs defined before it. CTEs make long queries readable: staging, filtering and aggregating in named steps instead of nesting subqueries. They are also the standard way to write self-contained examples and tests with inline data, as on every page of this reference.

The detail that matters for cost: BigQuery only materializes recursive CTEs. A non-recursive CTE is inlined, so if it is referenced in several places, the work runs once per reference. For a CTE that reads a large table and is joined to itself or used in three branches of a UNION ALL, on-demand bytes billed and slot time multiply accordingly. When a CTE is expensive and reused, write its result to a temporary table in a multi-statement query instead, or reduce it to the columns and rows the later steps need.

Scope rules: a CTE is visible only inside the query expression that defines it, a CTE name shadows a table with the same name, and a CTE cannot reference itself unless the WITH RECURSIVE keyword is used (see WITH RECURSIVE). WITH can start a query, a subquery, a CREATE TABLE ... AS, an INSERT ... SELECT or a view definition. In INSERT, the WITH goes after INSERT INTO table (columns), not before it. Without RECURSIVE, a CTE sees only the CTEs defined before it in the same WITH clause.

Syntax

WITH cte_name AS (query_expr)[, cte_name AS (query_expr) ...]
SELECT ... FROM cte_name ...

Arguments and return value

ArgumentDescription
cte_nameName used to reference the CTE later in the query. Must be unique within the WITH clause.
query_exprAny query, which may reference earlier CTEs, tables and views.

Returns: Nothing by itself: it names subqueries for the SELECT (or other statement) that follows.

Examples

Step-by-step funnel with inline test data

WITH events AS (
  SELECT 'u1' AS user_id, 'view_item' AS event_name UNION ALL
  SELECT 'u1', 'add_to_cart' UNION ALL
  SELECT 'u1', 'purchase' UNION ALL
  SELECT 'u2', 'view_item' UNION ALL
  SELECT 'u2', 'add_to_cart' UNION ALL
  SELECT 'u3', 'view_item'
),
per_user AS (
  SELECT
    user_id,
    LOGICAL_OR(event_name = 'add_to_cart') AS added,
    LOGICAL_OR(event_name = 'purchase') AS purchased
  FROM events
  GROUP BY user_id
)
SELECT
  COUNT(*) AS users,
  COUNTIF(added) AS added_to_cart,
  COUNTIF(purchased) AS purchased
FROM per_user;
Result
usersadded_to_cartpurchased
321

A CTE referenced twice runs twice

Both branches read orders in full, so on-demand you are billed for two scans of the referenced columns. Materialize the CTE into a temporary table if it is expensive and reused.

WITH daily AS (
  SELECT DATE(created_at) AS day, SUM(amount) AS revenue
  FROM `project.dataset.orders`
  GROUP BY day
)
SELECT 'best day' AS label, day, revenue FROM daily
QUALIFY ROW_NUMBER() OVER (ORDER BY revenue DESC) = 1
UNION ALL
SELECT 'worst day', day, revenue FROM daily
QUALIFY ROW_NUMBER() OVER (ORDER BY revenue) = 1;

WITH inside INSERT

The WITH clause belongs to the SELECT that feeds the insert, so it comes after the column list.

INSERT INTO `project.dataset.daily_revenue` (day, revenue)
WITH paid AS (
  SELECT DATE(created_at) AS day, amount
  FROM `project.dataset.orders`
  WHERE status = 'paid'
    AND DATE(created_at) = '2026-11-22'
)
SELECT day, SUM(amount)
FROM paid
GROUP BY day;

Common mistakes

  • Assuming a CTE is computed once and cached, as it can be in PostgreSQL with MATERIALIZED. In BigQuery each reference reruns it; reuse of an expensive CTE multiplies cost.
  • Referencing a CTE defined later in the same WITH clause. Without RECURSIVE, a CTE only sees the ones before it; reorder them.
  • Putting WITH before INSERT INTO. Write INSERT INTO t (...) WITH x AS (...) SELECT ....
  • Naming a CTE like an existing table and forgetting. The CTE shadows the table for the whole query, which is handy for tests and confusing in production code.

Cost and performance

  • Non-recursive CTEs are not materialized. If a CTE that scans a 1 TiB table is referenced three times, on-demand billing can approach 3 TiB for those columns. Use a temporary table, or restructure so the scan happens once.
  • Filters written outside a CTE are usually pushed into it, so partition pruning still works when you filter a CTE on the partitioning column. Check with a dry run that the estimate is what you expect.

FAQ

Does BigQuery materialize CTEs?

Only recursive ones. A non-recursive CTE is executed once for each place it is referenced.

What is the difference between a CTE and a temporary table in BigQuery?

A CTE is a named subquery inside one statement and is re-evaluated per reference. A temporary table stores the result once and lasts for the multi-statement query or session, at the cost of a little storage.

Can I use a CTE in CREATE TABLE AS SELECT?

Yes: CREATE TABLE t AS WITH x AS (...) SELECT ... FROM x. The same works in views and in INSERT ... SELECT.

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.