A Common Table Expression (CTE) lets you create a temporary, named result set with WITH, making BigQuery queries easier to read, reuse, and maintain.
A CTE is a named, temporary sub-query introduced with the WITH
keyword. It exists only for the duration of the main query and can be referenced like a table.
CTEs improve readability, allow modular query building, and let you reference the same intermediate result multiple times without repeating code.
Start with WITH cte_name AS (SELECT …) SELECT … FROM cte_name;
. Place the main SELECT after all CTE definitions.
Yes. Separate each CTE with a comma. Later CTEs can reference earlier ones, enabling step-by-step transformations.
BigQuery inlines non-recursive CTEs during optimization, so performance usually matches equivalent sub-queries. Reusing a CTE may even lower cost by preventing redundant scans.
Use fully qualified names like project.dataset.Customers
. Aliasing inside a CTE keeps column names clear.
Use descriptive CTE names, keep each CTE focused, filter early to reduce scanned bytes, and comment complex logic.
Placing a semicolon after a CTE, reusing a name twice, or selecting from a later CTE cause syntax errors. Order matters.
Run only the CTE body as a standalone query, or add LIMIT
clauses to inspect intermediate results.
CTEs make BigQuery SQL cleaner and more maintainable. Mastering them speeds up query writing and collaboration.
Yes. Defining complex logic once and joining it several times reduces duplication and improves clarity.
No. BigQuery currently allows only non-recursive CTEs. Use self-joins or scripting loops for recursion.
There is no documented hard limit, but extremely large chains can hit the 256 MB compiled query limit. Keep chains manageable.