BigQuery performance best practices: how to debug a slow query
To debug a slow BigQuery query, first find out what kind of slow it is, then read the execution plan. Divide a long query CTE by CTE, check the keys, fix the cause and confirm the fix on your own data.
Most advice about BigQuery performance is a list of tips. A list doesn’t help when a query is slow and you don’t know why. Debugging one is a loop: work out what kind of slow it is, find the stage or the CTE that costs the most, explain why, change one thing, and confirm the result. This page teaches that loop, then goes through the causes from the most important to the least.
How much a fix saves depends on your tables and your queries, so don’t expect one number here to hold for you. Where we quote a number, it comes from someone who published it, on data they chose.
Triage: what kind of slow is it?
Rule out the things that aren’t your query first. Google’s troubleshooting order starts with the service status page, then asks whether the time went to creating the job or to running it. If the slow part is before the job starts, no change to the SQL will help.
Then look at two numbers together. In Querylab.io, run the query and open the Plan tab of Prism Insights. The strip at the top has Data read, Slot time and Duration. Below it, N× slower than usual appears when this run took at least 1.5 times BigQuery’s average for earlier runs and at least a second more.
Under on-demand pricing the bill follows Data read. On a reservation it follows slot time, as the TRM Labs team stresses: a query can scan little and still be expensive. Know which one you are trying to lower before you start. Auto routing and the Pricing tab show which model suits a query.
With those numbers in hand, these four questions sort almost every slow query:
A job served from the query cache has no plan, so change the query slightly to get a real run. If the query failed, the Plan tab has no plan to show. BigQuery keeps the stages it got through, so job_stages can show how far it went, and divide and conquer needs no plan at all.
When a query got slower
If the same query used to be fast, you don’t need to study it. You need to find what changed. Query history folds runs of a query into one row and lists which values each run changed, and History Optimize lists what Got worse across the project. Then compare a slow run with a fast one, with this checklist based on Google’s:
| Compare | If it differs |
|---|---|
| Cache hit | The fast run didn’t run at all. Find a fast run that wasn’t cached |
| Bytes processed | The table grew, the query reads a larger partition, or a view’s definition changed |
| Tables read | The SQL or a view now reads something else |
| Time before the start | The job waited. In the REST API, quotaDeferments shows quota delays |
finalExecutionDurationMs | If it is far below the wall time, BigQuery may have retried the job internally |
| Materialized views | One the fast run used was rejected. chosen and rejectedReason say why |
| BI Engine | The acceleration mode changed. The Plan tab shows it, with BigQuery’s reasons |
| Performance insights | Slot contention, a high-cardinality join, a shuffle quota limit or skew appeared |
| Reservation | The job ran on a different reservation, or on-demand |
BigQuery groups runs by a hash of the query. This compares them in one result. Cache hits and failed runs have no hash, and a changed view changes it, so those runs won’t appear here:
SELECT
creation_time,
TIMESTAMP_DIFF(start_time, creation_time, MILLISECOND) AS pending_ms,
TIMESTAMP_DIFF(end_time, start_time, MILLISECOND) AS run_ms,
total_slot_ms,
total_bytes_processed,
query_info.resource_warning
FROM `region-us`.INFORMATION_SCHEMA.JOBS_BY_USER
WHERE creation_time > TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 30 DAY)
AND query_info.query_hashes.normalized_literals = 'your_query_hash'
ORDER BY creation_time DESC;
Locate: read the execution plan
A plan is a list of stages. Each stage is one kind of work done by many workers at once, and stages hand rows to each other through shuffle. How a query runs explains the model. Here is how to read one in practice.
This query gives each row a decile. It is a run on a test table of 10 million rows, so read it for its shape and not for its numbers.
SELECT id, NTILE(10) OVER (ORDER BY score) AS bucket
FROM events
The issue points at the stage, and the steps below show why. It won’t always be there: each detector has a threshold, so a wasteful query can stay under all of them and show “No problems found in this run.” Read the issues when they appear, and read the stages either way.
Read it in this order:
- Which stage has the time? S03 has 44 percent of the slot time and most of the wall time, so Querylab.io marks it Most slot time. A stage gets that mark at 40 percent. With no mark, compare the rows yourself.
- What is it doing? Click the stage to read its steps in plain words, and Go to line to jump to the SQL. Here it is a sort and a window function over all the rows. The
+inSort+means the stage does more than its name says. - Is the work spread out? S06 and S09 kept dozens of slots busy. S03 didn’t: BigQuery reports
parallel_inputsof 1 for it, because a window with noPARTITION BYneeds every row in one order. Its ratio of 4 is low without being 1, so read the ratio as a sign of little parallelism and not as an exact count of workers. - Do the rows go up or down? In most queries they should drop early. Rows going up is the sign of a join problem.
- Are the extra stages yours? BigQuery adds
RepartitionandCoalescestages while a query runs, to rebalance data. One or two are normal. Slalom’s walkthrough shows a query that repartitioned seven times before it failed, on aGROUP BYof two high-cardinality columns.
The diagnosis is a single unit of work sorting everything. On a bigger table that stage is the one that grows, then fails. See global sorts.
What the workers did
A stage’s duration doesn’t tell you how it spent that time. Each stage has four phases: wait to be scheduled, read input, compute, and write output. BigQuery reports each as an average and a maximum over the workers.
| What you see | What it means | What to do |
|---|---|---|
| Compute avg close to compute max | Work is even. A well-tuned stage spends most of its time here | Reduce the work, if anything |
| Compute max far above compute avg | One worker got far more data than the rest | Skew |
| Wait far above compute | Workers weren’t scheduled, or an earlier stage was slow to produce | Queued for slots |
| Wait or read max far above avg | Input is uneven. One engineer traced this to a few oversized date partitions | Compare row counts per partition |
| Most of the time in the input stage | It reads far more than it keeps. Teads saw up to 99.5 percent of slot time in input for some queries | Read less data |
The Plan tab shows wall time, slot time, rows and shuffle per stage. For the phases and parallel_inputs, read job_stages. Copy the job ID from the job’s row in query history:
SELECT
s.name,
s.slot_ms,
s.records_read,
s.records_written,
s.parallel_inputs,
s.wait_ms_avg,
s.read_ms_avg,
s.compute_ms_avg,
s.compute_ms_max,
ROUND(SAFE_DIVIDE(s.compute_ms_max, s.compute_ms_avg), 1) AS skew,
s.shuffle_output_bytes,
s.shuffle_output_bytes_spilled
FROM `region-us`.INFORMATION_SCHEMA.JOBS_BY_USER,
UNNEST(job_stages) AS s
WHERE job_id = 'your_job_id'
AND creation_time > TIMESTAMP_SUB(CURRENT_TIMESTAMP(), INTERVAL 7 DAY)
ORDER BY s.slot_ms DESC;
Don’t re-run a production query to measure it. The job you already ran has all of this, and so do the runs before it.
Locate: divide and conquer a long query
A plan tells you which stage is expensive. In a query of 300 lines and 12 CTEs, it often can’t tell you which part of your SQL that is, because BigQuery merges and reorders your CTEs into its own stages. And for a query that fails, the Plan tab has nothing to show. The answer is the oldest debugging method there is: cut the problem in half until it is small enough to see.
Go from the cheapest move to the most expensive.
Bytes per part, for free
The Cost tab of Prism Insights splits the query at each CTE, subquery and statement and dry-runs every part. The By column and By table views show the same thing per column and per table, with JOIN impact for what each join adds. The grey diamonds in the editor margin do the same for one part: click one to estimate the query up to that line.
All of this is free. If one part holds most of the bytes, you are done locating.
Later filters are pushed into the estimate of the parts above them, as BigQuery would at run time. To see what a CTE costs and returns as written, turn off Apply outer filters to CTE estimates in the ⋮ menu.
Rows per part
Bytes can’t show a join that multiplies rows, because they only count what is read. For that you need row counts, and they are the most useful numbers you can collect. Write down what each CTE should return, then check. One query can count all of them:
WITH orders AS ( SELECT * FROM UNNEST([ STRUCT(1 AS order_id, 10 AS customer_id, 'paid' AS status), (2, 10, 'paid'), (3, 20, 'paid'), (4, 30, 'refunded'), (5, 30, 'paid') ]) ), payments AS ( SELECT * FROM UNNEST([ STRUCT(10 AS customer_id, 40 AS amount), (10, 60), (10, 25), (20, 80), (30, 15) ]) ), paid_orders AS (SELECT * FROM orders WHERE status = 'paid'), with_payments AS (SELECT * FROM paid_orders JOIN payments USING (customer_id)) SELECT 1 AS step, 'orders' AS cte, COUNT(*) AS row_count FROM orders UNION ALL SELECT 2, 'paid_orders', COUNT(*) FROM paid_orders UNION ALL SELECT 3, 'with_payments', COUNT(*) FROM with_payments ORDER BY step
| Row | step | cte | row_count |
|---|---|---|---|
| 1 | 1 | orders | 5 |
| 2 | 2 | paid_orders | 4 |
| 3 | 3 | with_payments | 8 |
Going from 5 orders to 4 paid ones is right. Going from 4 to 8 at a step that should only add columns is the bug. Two shapes account for most surprises: a step that multiplies rows, and a filter that removes nearly all of them.
Shift-click a diamond to run the query up to that CTE and see its rows. It is a real run, billed and held to your cost limit. With Apply outer filters to CTE estimates on, later filters go into this run too, so turn it off to count what the CTE returns as written. It sends SELECT * FROM that CTE, so for a count alone, use a ledger like the one above, which reads only the columns it needs. To run a part you have selected, press ⌘Enter.
Bisect, don’t walk
With many CTEs, don’t check them from the top. Check the middle one. If it is right, the problem is below it. If it is wrong, the problem is in it or above it. Each check halves what is left, so 12 CTEs take about four checks.
One trap: a row count only clears the steps before it when no GROUP BY or DISTINCT sits between them, because an aggregate returns the expected rows from inflated input. In the figure, by_day has its 31 rows even though the step above it is 30 times too big. Check a total there as well, or check above the aggregate. With branching CTEs, bisect one branch at a time.
Remove until it gets fast
When row counts are fine but the query is still slow, take pieces away instead of looking at pieces. Remove one join, one window function or one DISTINCT, and run again. When the time drops, the last thing you removed is the expensive part. It doesn’t matter that the answer is wrong while you do this. The tab’s version history keeps the original.
Shrink the input and watch it grow
Debugging on the full table is slow and costs money. Add a partition filter for one day, and most runs get cheap. Then use the size to learn something: run one day, then two, then four.
- If slot time doubles when the data doubles, the query scales normally.
- If it quadruples, something grows with the square of the data, and a many-to-many join is the first suspect.
- If it follows the data up to a certain size and then jumps or fails, something stopped fitting on one worker.
This is the fastest way to catch a problem before it reaches the full table. Use real partitions, not a random sample, to debug a join. TABLESAMPLE on both sides of a join keeps few of the rows that would have matched, so the result looks far smaller than it is. Sampling is fine for exploring one table.
Checkpoint the expensive part
Once a part is known to be right, stop paying for it. Turn it into a temporary table in a script, and work on the statements after it. This is Google’s advice for a query that is too complex: split it and materialize the intermediate results.
CREATE TEMP TABLE recent AS
SELECT customer_id, amount
FROM events
WHERE event_date >= '2026-10-01';
-- Everything below reads the checkpoint, not the 2 TB table.
SELECT customer_id, SUM(amount) AS total
FROM recent
GROUP BY customer_id;
A script has a second benefit. Each statement is its own job with its own plan, so one plan of 40 stages becomes several you can read. In Querylab.io, pick the statement in the results bar and the Plan tab follows it.
Where this method can mislead you
- A part can cost more alone than inside the query. A filter further down gets pushed into a CTE when the whole query runs. Run with outer filters off, or copied out by hand, the CTE has no such filter.
- Stages don’t map one to one to CTEs. BigQuery can merge several CTEs into a stage, and split one over many.
- Fast on one day doesn’t prove fast on a year. Use the growth test.
- Removing a piece can change the plan. A join taken away can turn a four-stage plan into a one-stage plan.
Explain: check the data
Now you know where. The reason is usually in the data and not in the SQL: a key that repeats, a value that dominates, a NULL that matches too much. Two cheap queries answer most of these.
Predict a join before you run it. Count the rows per key on each side, and multiply. This reads only the keys and never builds the join, so it works on a join too big to finish:
WITH orders AS ( SELECT customer_id FROM UNNEST([10, 10, 20, 30, 30]) AS customer_id ), payments AS ( SELECT customer_id FROM UNNEST([10, 10, 10, 20, 30, 30]) AS customer_id ), order_keys AS (SELECT customer_id, COUNT(*) AS n FROM orders GROUP BY customer_id), payment_keys AS (SELECT customer_id, COUNT(*) AS n FROM payments GROUP BY customer_id) SELECT SUM(o.n) AS order_rows, SUM(p.n) AS payment_rows, SUM(o.n * p.n) AS joined_rows, MAX(o.n * p.n) AS biggest_key FROM order_keys o JOIN payment_keys p USING (customer_id)
| Row | order_rows | payment_rows | joined_rows | biggest_key |
|---|---|---|---|---|
| 1 | 5 | 6 | 11 | 6 |
Keys with no match are left out of these sums. If joined_rows is far above both inputs, the join multiplies. If biggest_key is a large part of it, one key will land on one worker.
Look for a hot key. Check the share of the top values of a join or GROUP BY key:
WITH events AS ( SELECT merchant_id FROM UNNEST(['m1', 'm1', 'm2', 'm3', NULL, NULL, NULL, NULL, NULL, NULL]) AS merchant_id ) SELECT merchant_id, COUNT(*) AS row_count, ROUND(100 * COUNT(*) / SUM(COUNT(*)) OVER (), 1) AS percent_of_rows FROM events GROUP BY merchant_id ORDER BY row_count DESC, merchant_id
| Row | merchant_id | row_count | percent_of_rows |
|---|---|---|---|
| 1 | null | 6 | 60.0 |
| 2 | m1 | 2 | 20.0 |
| 3 | m2 | 1 | 10.0 |
| 4 | m3 | 1 | 10.0 |
Fintel Analytics reports that the usual culprits are NULL and placeholder values like 'UNKNOWN' or 'TEST', and that a single value above 10 to 15 percent of the rows is worth a look. On a very large table, APPROX_TOP_COUNT(key, 20) gives the top values with less work.
Two views in Querylab.io help here. The Preview tab shows rows without running a query, and column lineage shows which source column feeds a suspicious output.
Change: the causes, most important first
The order is by how the cost behaves as data grows: the ones at the top get worse fastest, or are on the bill.
| # | Cause | Why it comes here | Where Querylab.io shows it |
|---|---|---|---|
| 1 | Reading data you don’t need | It is on the on-demand bill, and every later stage pays too | Estimate, code quality warnings, Partitions read |
| 2 | Joins that multiply rows | Cost grows with the product of both sides, and totals break | Rows and slot time of the join stage, High-cardinality join |
| 3 | Skew | One worker sets the pace, however many slots you have | Data skew detected, job_stages |
| 4 | Global sorts and windows | One worker does it, so it stops scaling, then fails | A long Sort+ stage, ORDER BY Without LIMIT |
| 5 | Moving too much between stages | Shuffle is limited, and it spills | Shuffle column, Shuffle spill to disk |
| 6 | A query that is too complex | It fails during planning | The error, Cost tab for its parts |
| 7 | JavaScript UDFs | A cost on every row | Slot time of the stage that calls one |
| 8 | Exact distinct counts | Has to track every value | COUNT(DISTINCT) Performance hint and quick fix |
| 9 | Small things per row | Rarely the reason a query is slow | Nothing in the plan |
Here is what people have published about some of them:
| Who | Problem | What they did | What they report |
|---|---|---|---|
| TRM Labs, 2025 | DATETIME(ts, "EST") on a partition column | Compared the column directly | Slot time from 4 hr 29 min to 2 min 56 s |
| Shopify, 2022 | A query that would have cost nearly $1M a month | Clustered on two WHERE columns | 150 times less data scanned |
| Oudar, 2024 | A skewed join | Bucketed the key on both sides | 6 min 27 s to 23 s on a generated 100M-row table, about 18 times on production data |
| TRM Labs, 2025 | A hot key with 85 percent of the rows | Salted the key | 8 times faster, same slot time |
| TRM Labs, 2025 | A join on value IN UNNEST(array) | Unnested first, joined on equality | 30 minutes to 3 |
| Slalom, 2020 | A self-join that selected all columns | Compared with COUNT(*) | 43 minutes against 18.9 seconds |
| Daniel Imfeld, 2021 | Shuffle limit, on GROUP BY keys of 64 and 128 characters | Replaced the strings with integers | The query stopped failing |
| Teads, 2026 | 22.7 percent of slots went to duplicate, racing queries | Merged the duplicates, among other fixes | Average slot usage down more than 90 percent |
Teads found those duplicates by grouping jobs in INFORMATION_SCHEMA, and no single plan would have shown them. Before you tune a query, check that it should run that often. History Optimize groups your jobs the same way.
Read less data
This comes first because it is the one fix that lowers an on-demand bill, and it makes every later stage cheaper. You can also see it before you run anything: the status bar estimate is a dry run, and the code quality checks warn on missing partition and cluster filters as you type.
Keep the partition column bare. WHERE event_date = '2026-03-01' reads one partition. WHERE FORMAT_DATE('%F', event_date) = '2026-03-01' means the same and reads all of them. After a run, Partitions read in the strip shows how many were scanned.
Not every function stops pruning, and the difference can be small. In a dry run, DATE_ADD(event_date, INTERVAL 7 DAY) > '2026-07-01' pruned and event_date + INTERVAL 7 DAY > '2026-07-01' read every partition. Check the estimate instead of trusting the shape. A value that comes from a subquery stops pruning too, because BigQuery picks the partitions before that subquery runs. Put it in a script variable first. Querylab.io warns about this one as Partition Filter from a Query. History Optimize finds arithmetic on the partition column and subquery filters in your past queries. It proposes a rewrite for the arithmetic when one is exact, and reports the subquery ones without a fix. See partitioned tables, clustered tables and partitioning vs clustering.
Name your columns. BigQuery stores each column separately, so a final SELECT * reads every column, and a LIMIT usually doesn’t change that. BigQuery can sometimes stop early, and limit hints says when, but the estimate won’t show it. To look at rows, use the free Preview tab.
Joins that multiply rows
A join on a key that repeats on both sides returns every pair. The cost grows with the product of the two sides, and the answer is wrong as well:
WITH orders AS ( SELECT 1 AS customer_id, 100 AS amount UNION ALL SELECT 1, 50 ), payments AS ( SELECT 1 AS customer_id, 90 AS amount UNION ALL SELECT 1, 40 UNION ALL SELECT 1, 20 ), order_totals AS (SELECT customer_id, SUM(amount) AS ordered FROM orders GROUP BY customer_id), payment_totals AS (SELECT customer_id, SUM(amount) AS paid FROM payments GROUP BY customer_id) SELECT 'join, then sum' AS method, SUM(o.amount) AS ordered, SUM(p.amount) AS paid FROM orders o JOIN payments p USING (customer_id) UNION ALL SELECT 'sum, then join', ordered, paid FROM order_totals JOIN payment_totals USING (customer_id) ORDER BY method
| Row | method | ordered | paid |
|---|---|---|---|
| 1 | join, then sum | 450 | 300 |
| 2 | sum, then join | 150 | 150 |
The fix is to join at the grain you need: aggregate to one row per key before the join. Predict the size to confirm it. See row multiplication.
When BigQuery joins and aggregates in one stage, as in the figure, the stage table looks calm. BigQuery does record the event, and Querylab.io shows it as High-cardinality join, with the rows on each side and the rows out. When a query keeps the joined rows, they show as a stage that writes more than it reads. Join explosion detected needs at least 10 times what the stage read, at least 1 million rows and at least 20 percent of the plan’s slot time, so treat rows going up as the signal whether the issue appears or not.
Aggregating first is a fix for joins that multiply. On a many-to-one join to a small table there is nothing to shrink, and the extra GROUP BY is more work.
Hidden cross joins are the worst case. A join with no equality to hash on compares every pair of rows. That is what an inequality like a.ts < b.ts does, and so do IS NOT DISTINCT FROM, IN (b.k, b.j) and LIKE CONCAT(b.s, '%') on their own. Querylab.io flags those last three as Join Condition Plans a Cross Join, with a rewrite. For inequalities, see range joins.
Skew: one key on one worker
BigQuery routes rows with the same key to the same worker. If one key has most of the rows, one worker does most of the work, and the stage lasts as long as that worker. More slots don’t help. The plan shows it as compute max far above compute avg, and Querylab.io reports Data skew detected when it is severe. Then apply the simplest fix that works:
- Filter it out. If the hot value is
NULLor a placeholder, and a filter is what the query means, use one. - Route it around the join.
NULLkeys match nothing, so send them through aUNION ALLbranch that skips the join. - Aggregate first. Collapse the hot key to one row before the join. See skew in optimizing joins.
- Salt it. Split the hot key over several workers.
Add a salt to the big side, and copy the small side once per salt value, so that every row still finds its match:
WITH orders AS ( SELECT order_id, 'hot' AS merchant, 10 AS amount FROM UNNEST(GENERATE_ARRAY(1, 8)) AS order_id UNION ALL SELECT 9, 'quiet', 10 ), merchants AS ( SELECT 'hot' AS merchant, 'US' AS country UNION ALL SELECT 'quiet', 'FR' ), salted_orders AS (SELECT *, MOD(order_id, 4) AS salt FROM orders), salted_merchants AS ( SELECT m.*, salt FROM merchants m, UNNEST(GENERATE_ARRAY(0, 3)) AS salt ) SELECT 'plain join' AS method, country, SUM(amount) AS total FROM orders JOIN merchants USING (merchant) GROUP BY country UNION ALL SELECT 'salted join', country, SUM(amount) FROM salted_orders JOIN salted_merchants USING (merchant, salt) GROUP BY country ORDER BY method, country
| Row | method | country | total |
|---|---|---|---|
| 1 | plain join | FR | 10 |
| 2 | plain join | US | 80 |
| 3 | salted join | FR | 10 |
| 4 | salted join | US | 80 |
Check that the totals match, as here, then that the wait dropped. Salt only when the simpler fixes don’t apply: it adds complexity, and Oudar notes that it doesn’t always help. If the other side is small, BigQuery may send it to every worker anyway, and key skew matters less.
Global sorts and windows
Anything that needs all rows in one order runs on one worker: a window with no PARTITION BY, and a final ORDER BY. Adding slots doesn’t help, and past a certain size the query fails. Watch for a Sort+ stage with a long wall time.
Limit before you rank. A LIMIT after a window doesn’t help, because the window has already sorted everything. Take the rows first, then rank them. Google’s guide gives this example at about 15 seconds against 2 on its table.
WITH accounts AS ( SELECT 7 AS id, DATE '2011-03-02' AS created UNION ALL SELECT 3, DATE '2008-07-31' UNION ALL SELECT 9, DATE '2014-01-15' UNION ALL SELECT 1, DATE '2008-07-31' UNION ALL SELECT 5, DATE '2012-10-09' UNION ALL SELECT 2, DATE '2009-04-22' ), oldest AS ( SELECT id, created FROM accounts ORDER BY created, id LIMIT 3 ) SELECT id, created, DENSE_RANK() OVER (ORDER BY created) AS age_rank FROM oldest ORDER BY age_rank, id
| Row | id | created | age_rank |
|---|---|---|---|
| 1 | 1 | 2008-07-31 | 1 |
| 2 | 3 | 2008-07-31 | 1 |
| 3 | 2 | 2009-04-22 | 2 |
The two forms agree when the window orders by what the subquery orders by. They don’t when the rank must reflect rows that the limit removes. See window functions.
Give ORDER BY a LIMIT. BigQuery then keeps only the top rows. Querylab.io warns about ORDER BY with no LIMIT on a large table. Keep ORDER BY out of the middle of a query unless it is in a window, and avoid a large OFFSET, which Google says can run out of memory on a single unit.
Partition your windows. ROW_NUMBER() OVER () on a huge table is a common way to hit this. If you need an ID, use a hash. If you need a rank, ask whether it can be per group.
Replace NTILE. With no PARTITION BY it is a global sort, and Google says to use APPROX_QUANTILES instead. RANGE_BUCKET on the quantiles is shorter than the subquery in Google’s guide:
WITH scores AS ( SELECT score FROM UNNEST([3, 7, 8, 12, 15, 21, 22, 40, 41, 90]) AS score ), bounds AS ( SELECT APPROX_QUANTILES(score, 4) AS q FROM scores ) SELECT score, NTILE(4) OVER (ORDER BY score) AS ntile_bucket, RANGE_BUCKET(score, q) AS range_bucket FROM scores, bounds ORDER BY score
| Row | score | ntile_bucket | range_bucket |
|---|---|---|---|
| 1 | 3 | 1 | 1 |
| 2 | 7 | 1 | 1 |
| 3 | 8 | 1 | 2 |
| 4 | 12 | 2 | 2 |
| 5 | 15 | 2 | 3 |
| 6 | 21 | 2 | 3 |
| 7 | 22 | 3 | 3 |
| 8 | 40 | 3 | 4 |
| 9 | 41 | 4 | 4 |
| 10 | 90 | 4 | 5 |
The buckets are close and not identical. NTILE gives them equal row counts, give or take one. RANGE_BUCKET follows the boundaries, and the largest value gets its own bucket, here 5. The rewrite adds a pass over the table, so if NTILE isn’t failing and the query aggregates the buckets anyway, compare the two first.
The error message tells you which of these you hit:
Text after Resources exceeded during query execution: | What ran out | Go to |
|---|---|---|
Top memory consumer(s): ORDER BY operations | One worker sorting | The error page |
Top memory consumer(s): analytic OVER() clauses | A window with too much in one partition | This section |
...limit available for shuffle operations | Data moving between stages | Moving too much |
Not enough resources for query planning | The query itself is too complex | Too complex |
Moving too much between stages
Most joins and GROUP BYs send rows through shuffle, along with every column they carry. When the data doesn’t fit, it spills to disk and the query slows down sharply. The Shuffle column shows it. Open the stage to see how much spilled.
- Carry fewer columns. Select what you need in the CTE before the join. Slalom’s self-join above is this effect.
- Shrink the keys. A 64-character string key moves 64 bytes per row, and a 64-bit integer moves 8.
FARM_FINGERPRINT(key)gives you the integer. TRM Labs warns that 64-bit hashes start to collide at billions of keys, so keep that in mind. - Aggregate or filter earlier. Fewer rows into the join means less to move.
A query that is too complex
Not enough resources for query planning means the plan itself is too big. Google names deeply nested or repeated WITH clauses, nested views, and repeated UNION ALL. A CTE referenced many times counts more than once, and so does a view, so a short query can expand into a huge one. The fix is a checkpoint: split it into statements. To catch it early, watch query_info.resource_warning in the jobs view.
JavaScript UDFs
Calling a JavaScript UDF starts a subprocess, and Google says the optimizer can work with SQL UDF definitions. Use a SQL UDF or the expression inline, and keep JavaScript for logic SQL can’t express. See user-defined functions.
Approximate counts
COUNT(DISTINCT x) has to track every value. APPROX_COUNT_DISTINCT keeps a small sketch. It is approximate by design, though on small cardinalities it can be exact:
SELECT COUNT(DISTINCT MOD(i, 997)) AS exact_count, APPROX_COUNT_DISTINCT(MOD(i, 997)) AS approx_count FROM UNNEST(GENERATE_ARRAY(1, 5000)) AS i
| Row | exact_count | approx_count |
|---|---|---|
| 1 | 997 | 997 |
Use it where the error doesn’t matter, as in a dashboard that shows “about 1.2M users”. Querylab.io hints at COUNT(DISTINCT x) and has a quick fix that replaces it. See approximate aggregation.
Small things per row
Do these when you write a query, and don’t go looking for them in a plan. Google says comparisons on BOOL, INT64, FLOAT64 and DATE are typically faster than on strings, and that LIKE is faster when you don’t need a regular expression. For a plain substring they match the same rows:
WITH pages AS ( SELECT '/shop/checkout' AS url UNION ALL SELECT '/shop/cart' UNION ALL SELECT '/checkout/done' UNION ALL SELECT '/blog/checkout-tips' UNION ALL SELECT '/Checkout' ) SELECT url, url LIKE '%checkout%' AS like_match, REGEXP_CONTAINS(url, r'checkout') AS regexp_match FROM pages ORDER BY url
| Row | url | like_match | regexp_match |
|---|---|---|---|
| 1 | /Checkout | false | false |
| 2 | /blog/checkout-tips | true | true |
| 3 | /checkout/done | true | true |
| 4 | /shop/cart | false | false |
| 5 | /shop/checkout | true | true |
Mind that % and _ are special in LIKE, and . and + in a regular expression.
The query waited for slots
Sometimes the SQL is fine. If wait is far above compute, the query was queued behind others. Querylab.io reports Slot starvation detected when BigQuery records slot contention, and Insufficient shuffle quota when shuffle was the limit. An analyst can reduce the data the query processes. An admin can add slots, or spread heavy queries over time or over reservations. Under on-demand, a project has up to 2,000 slots, shared. See slots.
Advice to check in your own plan
Some common advice depends on your query, so check it before you rewrite anything.
Table order in a join. Google says to put the largest table first, and says in the same paragraph that the optimizer decides which side each table goes on. The join steps in the plan show what BigQuery did with yours.
Where you write a filter. Many guides say to filter in a CTE before the join. On an inner join, WHERE, ON and a subquery give BigQuery the same thing, and the plan shows the filter at the read. Don’t carry this over to outer joins. There, placement changes the answer:
WITH customers AS ( SELECT 1 AS id, 'Ana' AS name UNION ALL SELECT 2, 'Ben' UNION ALL SELECT 3, 'Chi' ), orders AS ( SELECT 1 AS customer_id, 'paid' AS status UNION ALL SELECT 2, 'refunded' ) SELECT 'filter in ON' AS placement, COUNT(*) AS customer_rows FROM customers c LEFT JOIN orders o ON o.customer_id = c.id AND o.status = 'paid' UNION ALL SELECT 'filter in WHERE', COUNT(*) FROM customers c LEFT JOIN orders o ON o.customer_id = c.id WHERE o.status = 'paid' ORDER BY placement
| Row | placement | customer_rows |
|---|---|---|
| 1 | filter in ON | 3 |
| 2 | filter in WHERE | 1 |
A temporary table for a repeated CTE. Google warns that a CTE used in several places might be evaluated each time. A temporary table avoids that, and makes the query a script, which runs its statements one after another. Whether that pays depends on how expensive the CTE is and how often it is read.
Confirm the fix
A faster query that returns different rows is a bug. Run the old and new versions, and compare the results with Data compare, which lists the rows that were added, removed or changed. For an approximate rewrite, decide first how much difference you accept.
Then check that the number you meant to move has moved, and not only the duration:
| You fixed | Check |
|---|---|
| Reading too much | Data read, which the estimate shows free |
| A join or shuffle | Rows and Shuffle at that stage |
| Skew or a global sort | Wall time of that stage, compute max |
| Waiting | Wait in job_stages, or the issue is gone |
Be careful with slot time. The same query can vary a lot between runs, and BigQuery learns from repeated runs, so one run proves little. Compare a few, and only trust a large difference. Each run stays in query history with its slot time, so you rarely need extra runs.
Once it ships, History Optimize compares a query with its own past, so it tracks changes that keep the query’s shape, like a new filter value or a change to the table. Your fix is working shows those when a query now reads at most half as much and at least 1 GB less. A rewrite gets a new hash and starts with no history, so compare it by hand. Got worse catches the next regression. To stop the next bad query early, set a slot limit and a time limit per query.
When you want a second opinion at any step, Optimize with Prism AI appears under the plan’s issues and opens the agent with them in the prompt. Copy for AI in the ⋮ menu of the Plan tab copies a text summary of the plan to paste anywhere. Two structural fixes are covered elsewhere: primary and foreign keys let the optimizer drop joins, and materialized views store an aggregate so queries stop recomputing it.