BigQuery · Scripting statement
BigQuery LOOP, WHILE and FOR...IN
BigQuery scripts loop with LOOP ... END LOOP (exit with BREAK or LEAVE), WHILE condition DO ... END WHILE, REPEAT ... UNTIL ... END REPEAT, and FOR row IN (query) DO ... END FOR. Use them for backfills and maintenance, not row-by-row processing: each statement inside runs as its own job.
LOOP ... END LOOP repeats its statements until BREAK (or its synonym LEAVE) exits; CONTINUE (or ITERATE) jumps to the next iteration. WHILE condition DO ... END WHILE checks the condition before each iteration, and REPEAT ... UNTIL condition END REPEAT checks it after, so its body always runs at least once. FOR record IN (query) DO ... END FOR runs the query once, then executes the body for each result row, with the row available as a STRUCT (record.column). The row order is undefined unless the query has an ORDER BY. Loops can carry a label (backfill: LOOP ... END LOOP backfill;) so BREAK backfill can leave an outer loop from inside an inner one.
Loops are only available in multi-statement queries, so the script usually starts with DECLARE statements for counters and dates. Blocks and conditionals nest up to 50 levels. A loop can't be generated dynamically: EXECUTE IMMEDIATE can't contain LOOP, WHILE or REPEAT, but a loop can contain EXECUTE IMMEDIATE to build each iteration's SQL. A script can run for at most 24 hours in total and 6 hours per statement.
The cost model follows from how scripts run. Every query inside the loop is a separate child job, billed on demand for its own bytes (with the 10 MB minimum per table) and visible in INFORMATION_SCHEMA.JOBS with the script as parent_job_id. A WHILE condition that queries a table is billed on every evaluation. Statements that are skipped are not billed, and if the script fails, the statements already run stay billed. A loop that processes one partition per iteration is the right shape for backfills that would otherwise hit the 4,000 partitions per job limit; a loop over individual rows is almost always better written as one set-based statement.
Syntax
[label:] LOOP
statements;
END LOOP [label];
[label:] WHILE boolean_expression DO
statements;
END WHILE [label];
[label:] REPEAT
statements;
UNTIL boolean_expression
END REPEAT [label];
[label:] FOR loop_variable IN (table_expression) DO
statements;
END FOR [label];
BREAK [label]; | LEAVE [label]; | CONTINUE [label]; | ITERATE [label];Arguments and return value
| Argument | Description |
|---|---|
boolean_expression | WHILE checks it before each iteration; REPEAT ... UNTIL checks it after each one. |
loop_variable | FOR ... IN: a STRUCT holding the current row's columns, scoped to the loop body. |
table_expression | FOR ... IN: a query evaluated once at the start. Add ORDER BY if the order matters. |
label | Optional name so BREAK or CONTINUE can target an outer loop. |
Returns: No result set of its own; statements inside the loop return their own results.
Examples
WHILE with a counter
DECLARE i INT64 DEFAULT 0;
DECLARE total INT64 DEFAULT 0;
WHILE i < 5 DO
SET i = i + 1;
SET total = total + i;
END WHILE;
SELECT i AS iterations, total;| iterations | total |
|---|---|
| 5 | 15 |
LOOP with CONTINUE and BREAK
Adds the odd numbers up to 9 and stops once the counter passes 9.
DECLARE n INT64 DEFAULT 0;
DECLARE odd_sum INT64 DEFAULT 0;
LOOP
SET n = n + 1;
IF n > 9 THEN
BREAK;
END IF;
IF MOD(n, 2) = 0 THEN
CONTINUE;
END IF;
SET odd_sum = odd_sum + n;
END LOOP;
SELECT odd_sum;| odd_sum |
|---|
| 25 |
FOR ... IN over a query result
The loop variable is a STRUCT of the row's columns.
DECLARE report STRING DEFAULT '';
FOR plan IN (
SELECT name, price FROM UNNEST([STRUCT('free' AS name, 0 AS price), ('pro', 49), ('team', 99)])
ORDER BY price
) DO
SET report = CONCAT(report, plan.name, '=', CAST(plan.price AS STRING), ';');
END FOR;
SELECT report;| report |
|---|
| free=0;pro=49;team=99; |
Backfill one day per iteration
Each iteration is a child job that reads and writes one partition, which keeps every job small and well under the 4,000 partitions per job limit.
DECLARE d DATE DEFAULT DATE '2026-01-01';
WHILE d <= DATE '2026-11-22' DO
DELETE FROM `project.dataset.daily_revenue` WHERE day = d;
INSERT INTO `project.dataset.daily_revenue` (day, store_id, revenue)
SELECT d, store_id, SUM(amount)
FROM `project.dataset.orders`
WHERE DATE(created_at) = d AND status = 'paid'
GROUP BY store_id;
SET d = DATE_ADD(d, INTERVAL 1 DAY);
END WHILE;Common mistakes
- Looping over rows to update them one at a time. Each UPDATE is a separate job that bills the partitions it rewrites and queues behind the others; write one set-based UPDATE or MERGE instead.
- A WHILE condition that queries a large table. The query runs, and is billed, on every iteration. Compute the bound once into a variable.
- Expecting FOR ... IN to see rows inserted by the loop body. The query is evaluated once, before the first iteration.
- Forgetting to change the loop variable in WHILE or LOOP. The script runs until the 6-hour statement or 24-hour script limit; add a BREAK guard on an iteration counter while developing.
Cost and performance
- Each statement in an iteration is billed separately on demand, including the 10 MB minimum per table referenced, so a loop of 300 tiny queries over one table bills at least 3,000 MB even if each reads a few rows.
- Child jobs of a loop appear in INFORMATION_SCHEMA.JOBS with the script's job as
parent_job_id. Exclude theSCRIPTparent row when summing cost, or the loop is counted twice.
FAQ
How do I write a loop in BigQuery?
In a multi-statement query: DECLARE i INT64 DEFAULT 0; WHILE i < 10 DO SET i = i + 1; END WHILE; or LOOP ... END LOOP with BREAK, or FOR row IN (SELECT ...) DO ... END FOR to iterate over a result.
What is the difference between BREAK and LEAVE, CONTINUE and ITERATE?
None: LEAVE is a synonym for BREAK and ITERATE is a synonym for CONTINUE.
Is there a limit on loop iterations in BigQuery scripts?
There is no iteration count limit, but a script can run for at most 24 hours and each statement for 6 hours. Recursive CTEs, by contrast, stop at 500 iterations.
Related
Errors you may hit
More scripting and data movement
All BigQuery scripting and data movement · All statements and clauses · BigQuery error messages
