Docs/Performance/Performance best practices
Performance

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.

1. TriageWhat kindof slow?Plan tab stripquery history2. LocateWhich stageor CTE?Stage tableCost tab, diamonds3. ExplainWhy does itcost that?Stage stepskey checks4. ChangeOne thingat a timeEstimate firstthen a real run5. ConfirmSame answer,better run?Data comparequery historystill too slow: the bottleneck moved, so locate it again
Fixing the worst stage usually reveals the next one, so the loop runs until the query is fast enough. Locating is where most of the time goes, and it is what most of this page is about.

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.

WideLots of work on many workers.Fast to wait for, costly on a reservation.HeavyLots of work, and you wait for it.Read the stage table, then reduce the work.HealthyLittle work, short wait.Look at the bytes, then stop.Waiting, or one workerTime passed, but little work was done.Queued for slots, or a stage can't spread out.high slot timelow slot timeshort durationlong duration
Slot time is the work done and duration is your wait. Divided, they give the average number of slots that were busy. The bottom right corner is the one a SQL rewrite often can't fix by reducing work.

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:

Data read is more than the queryshould need?yesReading too muchpartitions, clusters, columnsnoRows go up at a stage, or slot timejumps with no rows to show for it?yesRows multipliedjoin keys repeat on both sidesnoOne stage is long on the clockwith few workers busy?yesOne worker has the jobglobal sort, or a hot keynoWait is far above compute, orSlot starvation detected?yesQueuedother jobs have the slotsnoThe query is doing real workShrink what moves between stages: fewer columns, smaller keys, earlier aggregates. Or split the query.
Ask in this order. The first needs no run at all, because the estimate is a free dry run. The rest need the plan, which is the next step.

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:

CompareIf it differs
Cache hitThe fast run didn’t run at all. Find a fast run that wasn’t cached
Bytes processedThe table grew, the query reads a larger partition, or a view’s definition changed
Tables readThe SQL or a view now reads something else
Time before the startThe job waited. In the REST API, quotaDeferments shows quota delays
finalExecutionDurationMsIf it is far below the wall time, BigQuery may have retried the job internally
Materialized viewsOne the fast run used was rejected. chosen and rejectedReason say why
BI EngineThe acceleration mode changed. The Plan tab shows it, with BigQuery’s reasons
Performance insightsSlot contention, a high-cardinality join, a shuffle quota limit or skew appeared
ReservationThe 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
Prism Insights → Plan
PRISM INSIGHTS×
Data read160 MB
Slot time77.6 slot-s
Duration13.4 s
Sort or window function ran on one worker
It read two columns, so the bytes are small. The time went somewhere else, and the issue says where.

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.

StageWall time, secondsSlot time, slot-secondsRowsSlot ÷ wallS00 Input0.144.410M → 10M32S01 Aggregate+0.851.310M → 12S02 Aggregate0.921.91 → 12S03 Sort+8.433.910M → 10M4S04 Aggregate0.032.60 → 10080S05 Aggregate0.030.02100 → 11S06 Join+0.098.410M → 10M92S07 Repartition0.943.410M → 10M4S08 Repartition0.334.310M → 10M13S09 Output0.4517.310M → 10M39
The stages from the stage table, with one column we added: slot time divided by wall time, which is about how many slots were busy. Google's admin guide does the same division.

Read it in this order:

  1. 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.
  2. 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 + in Sort+ means the stage does more than its name says.
  3. Is the work spread out? S06 and S09 kept dozens of slots busy. S03 didn’t: BigQuery reports parallel_inputs of 1 for it, because a window with no PARTITION BY needs 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.
  4. Do the rows go up or down? In most queries they should drop early. Rows going up is the sign of a join problem.
  5. Are the extra stages yours? BigQuery adds Repartition and Coalesce stages 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 a GROUP BY of 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.

Evenhealthycompute avg close to maxslot ÷ wall is highSkeweda hot keycompute max far above avgone bar sets the clockOne workera global sortparallel inputs: 1slot ÷ wall is lowQueuedno free slotswait far above computethe SQL may be fineEach row is one worker. Time runs left to right. Filled is compute, hatched is waiting.
Four stages that can take the same time for four different reasons. The average and the maximum per worker, with parallel inputs, tell them apart.
What you seeWhat it meansWhat to do
Compute avg close to compute maxWork is even. A well-tuned stage spends most of its time hereReduce the work, if anything
Compute max far above compute avgOne worker got far more data than the restSkew
Wait far above computeWorkers weren’t scheduled, or an earlier stage was slow to produceQueued for slots
Wait or read max far above avgInput is uneven. One engineer traced this to a few oversized date partitionsCompare row counts per partition
Most of the time in the input stageIt reads far more than it keeps. Teads saw up to 99.5 percent of slot time in input for some queriesRead 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:

a row ledger: count every CTE in one queryOpen in Querylab.io
1234567891011121314151617
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
Result in BigQuery
Rowstepcterow_count
11orders5
22paid_orders4
33with_payments8
3 rows

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.

CheckCTERows, log scaleWhat you expectedevents2.1Bthe tablerecent40Mone month: about 40M1with_customer40Msame rows: 40M2with_payments1.2Bsame rows: 40Mby_day31one row a day: 31
An invented example. Check 1 in the middle is right, so the fault is below it. Check 2 finds a step that should keep 40M rows and returns 1.2B.

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:

the join will return 11 rows, and 6 come from one keyOpen in Querylab.io
123456789101112131415
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)
Result in BigQuery
Roworder_rowspayment_rowsjoined_rowsbiggest_key
156116
1 row

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:

NULL holds 60 percent of the rowsOpen in Querylab.io
1234567891011
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
Result in BigQuery
Rowmerchant_idrow_countpercent_of_rows
1null660.0
2m1220.0
3m2110.0
4m3110.0
4 rows

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.

#CauseWhy it comes hereWhere Querylab.io shows it
1Reading data you don’t needIt is on the on-demand bill, and every later stage pays tooEstimate, code quality warnings, Partitions read
2Joins that multiply rowsCost grows with the product of both sides, and totals breakRows and slot time of the join stage, High-cardinality join
3SkewOne worker sets the pace, however many slots you haveData skew detected, job_stages
4Global sorts and windowsOne worker does it, so it stops scaling, then failsA long Sort+ stage, ORDER BY Without LIMIT
5Moving too much between stagesShuffle is limited, and it spillsShuffle column, Shuffle spill to disk
6A query that is too complexIt fails during planningThe error, Cost tab for its parts
7JavaScript UDFsA cost on every rowSlot time of the stage that calls one
8Exact distinct countsHas to track every valueCOUNT(DISTINCT) Performance hint and quick fix
9Small things per rowRarely the reason a query is slowNothing in the plan

Here is what people have published about some of them:

WhoProblemWhat they didWhat they report
TRM Labs, 2025DATETIME(ts, "EST") on a partition columnCompared the column directlySlot time from 4 hr 29 min to 2 min 56 s
Shopify, 2022A query that would have cost nearly $1M a monthClustered on two WHERE columns150 times less data scanned
Oudar, 2024A skewed joinBucketed the key on both sides6 min 27 s to 23 s on a generated 100M-row table, about 18 times on production data
TRM Labs, 2025A hot key with 85 percent of the rowsSalted the key8 times faster, same slot time
TRM Labs, 2025A join on value IN UNNEST(array)Unnested first, joined on equality30 minutes to 3
Slalom, 2020A self-join that selected all columnsCompared with COUNT(*)43 minutes against 18.9 seconds
Daniel Imfeld, 2021Shuffle limit, on GROUP BY keys of 64 and 128 charactersReplaced the strings with integersThe query stopped failing
Teads, 202622.7 percent of slots went to duplicate, racing queriesMerged the duplicates, among other fixesAverage 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:

three payments and two orders make six rowsOpen in Querylab.io
1234567891011121314151617
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
Result in BigQuery
Rowmethodorderedpaid
1join, then sum450300
2sum, then join150150
2 rows
The grid is the example above. When BigQuery joins and aggregates inside one stage, the joined rows never appear in the stage table.

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:

  1. Filter it out. If the hot value is NULL or a placeholder, and a filter is what the query means, use one.
  2. Route it around the join. NULL keys match nothing, so send them through a UNION ALL branch that skips the join.
  3. Aggregate first. Collapse the hot key to one row before the join. See skew in optimizing joins.
  4. Salt it. Split the hot key over several workers.
Salting trades a little extra work for parallelism. TRM Labs reports the same slot time and a far shorter wait. Oudar reports a shorter wait and less slot time in the join, before counting the preparation.

Add a salt to the big side, and copy the small side once per salt value, so that every row still finds its match:

the totals don't change, the hot key is split four waysOpen in Querylab.io
1234567891011121314151617181920
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
Result in BigQuery
Rowmethodcountrytotal
1plain joinFR10
2plain joinUS80
3salted joinFR10
4salted joinUS80
4 rows

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.

rank only the three oldest accountsOpen in Querylab.io
1234567891011121314151617
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
Result in BigQuery
Rowidcreatedage_rank
112008-07-311
232008-07-311
322009-04-222
3 rows

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:

close, but the rows land in different bucketsOpen in Querylab.io
123456789101112
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
Result in BigQuery
Rowscorentile_bucketrange_bucket
1311
2711
3812
41222
51523
62123
72233
84034
94144
109045
10 rows

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 outGo to
Top memory consumer(s): ORDER BY operationsOne worker sortingThe error page
Top memory consumer(s): analytic OVER() clausesA window with too much in one partitionThis section
...limit available for shuffle operationsData moving between stagesMoving too much
Not enough resources for query planningThe query itself is too complexToo 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:

exact and approximate agree on small cardinalitiesOpen in Querylab.io
1234
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
Result in BigQuery
Rowexact_countapprox_count
1997997
1 row

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:

the same matches, and both are case-sensitiveOpen in Querylab.io
12345678910111213
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
Result in BigQuery
Rowurllike_matchregexp_match
1/Checkoutfalsefalse
2/blog/checkout-tipstruetrue
3/checkout/donetruetrue
4/shop/cartfalsefalse
5/shop/checkouttruetrue
5 rows

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:

on a LEFT JOIN, ON keeps customers and WHERE removes themOpen in Querylab.io
123456789101112131415161718
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
Result in BigQuery
Rowplacementcustomer_rows
1filter in ON3
2filter in WHERE1
2 rows

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 fixedCheck
Reading too muchData read, which the estimate shows free
A join or shuffleRows and Shuffle at that stage
Skew or a global sortWall time of that stage, compute max
WaitingWait 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.

Count the rows at every CTE with a row ledger. Open this query in the playground. It is the real app on public datasets and needs no sign-in.