Optimizing joins in BigQuery
A slow BigQuery join usually has rows that multiply, skew or a hidden cross join, and the execution plan shows which. BigQuery runs each join as a broadcast or a hash join, and each problem has its own fix.
Practice this in free lessons on learn.querylab.io: Self-join and 1 more.
BigQuery runs a join in one of two ways. If one side is small, it sends that side to every worker and joins locally, which is a broadcast join. If both sides are large, it splits both by the join key so that matching keys land on the same worker, which is a hash join, and that moves both tables through shuffle. You don’t pick one. The optimizer does, from the sizes it expects. What you can change is how much data reaches the join and whether the join multiplies rows, and this page goes through those in order of what usually costs most.
The plan labels, stage counts and bytes below come from jobs we ran on generated tables. They show how BigQuery planned those queries. Timings from a test table wouldn’t tell you what a change will do to your query, so this page has none of its own. To measure a fix on your data, see confirm the fix.
Find what the join is doing
Open the plan of the slow run, find the stage with the JOIN step, and match what you see:
| What you see in the plan | Likely cause | Go to |
|---|---|---|
| The stage writes more rows than it read | Keys repeat on both sides | Row multiplication |
| Few rows out, but far more slot time than the input explains | The same, aggregated in-stage | Row multiplication |
| Compute max far above compute avg | One key has most of the rows | Skew |
CROSS in the join step | No equality to hash on | Range joins |
| Both inputs are large and most rows don’t survive the join | Too much reaches the join | Shrink the sides |
| Lots of shuffle bytes into the join | Wide rows or long keys | Keys and columns |
Before you run a join again, you can predict its size from the key counts of each side. In Prism Insights, JOIN impact on the Cost tab shows the bytes each joined table adds.
What the plan says about a join
The JOIN step in a plan names the type, and the label shows how the inputs were distributed. We saw three:
| Label in the plan | Where we saw it | Stages |
|---|---|---|
INNER HASH JOIN EACH WITH EACH | 10 million rows joined to 10 million rows | 4: two input stages, the join, the output |
INNER HASH JOIN EACH WITH ALL | 2 million rows joined to 2 million rows, result written to a table | 4 shown, one hidden |
INNER HASH JOIN ALL WITH ALL | 10 million rows joined to a 100,000-row table, or a big side filtered to a tenth | 1 |
Google says EACH WITH ALL is a broadcast join and EACH WITH EACH is a hash join. ALL WITH ALL appeared only in plans with a single stage and no shuffle, which BigQuery picks for queries it expects to finish quickly on a small amount of data. A join that keeps one side small avoids moving the big side at all.
Watch for row multiplication
A join on a key that repeats on both sides returns every pairing. Three shipments for one order make three joined rows for that order, and any SUM over the order’s columns counts it three times:
WITH orders AS ( SELECT 1 AS order_id, 100 AS amount UNION ALL SELECT 2, 50 UNION ALL SELECT 3, 25 ), shipments AS ( SELECT 1 AS order_id, 'box-a' AS parcel UNION ALL SELECT 1, 'box-b' UNION ALL SELECT 1, 'box-c' UNION ALL SELECT 2, 'box-d' ) SELECT COUNT(*) AS joined_rows, SUM(o.amount) AS summed_amount FROM orders AS o JOIN shipments AS s USING (order_id)
| Row | joined_rows | summed_amount |
|---|---|---|
| 1 | 4 | 350 |
The query says 350 where the shipped orders total 150. The cost grows with the product of the matches on each side, so a key that repeats 1,000 times on both sides makes a million rows for that one key.
BigQuery reports this as a high-cardinality join in the job’s performance insights, when the output has far more rows than the inputs. The report matters most when the same stage joins and aggregates, because the stage then writes few rows and looks calm. Querylab.io’s plan shows that report as High-cardinality join, and flags a join stage that wrote many times more rows than it read as Join explosion detected.
The fix is to join at the grain you need. Aggregate the many-side first, so each key appears once:
WITH orders AS ( SELECT 1 AS order_id, 100 AS amount UNION ALL SELECT 2, 50 UNION ALL SELECT 3, 25 ), shipments AS ( SELECT 1 AS order_id, 'box-a' AS parcel UNION ALL SELECT 1, 'box-b' UNION ALL SELECT 1, 'box-c' UNION ALL SELECT 2, 'box-d' ) SELECT o.order_id, o.amount, s.parcels FROM orders AS o LEFT JOIN ( SELECT order_id, COUNT(*) AS parcels FROM shipments GROUP BY order_id ) AS s USING (order_id) ORDER BY o.order_id
| Row | order_id | amount | parcels |
|---|---|---|---|
| 1 | 1 | 100 | 3 |
| 2 | 2 | 50 | 1 |
| 3 | 3 | 25 | null |
Google’s guide gives the same advice for queries that have both a join and a GROUP BY: aggregate before the join, so less data is joined. On a many-to-one join to a small table there is nothing to shrink, and the extra GROUP BY is more work.
Skew
If one key holds most of the rows, the worker that gets that key does most of the work while the others finish and wait. The plan shows it as a stage whose compute max is much larger than its compute avg. The stage takes as long as its slowest worker, and adding slots doesn’t help, because one worker has to process that key. See what the workers did.
Google’s performance insights include a partition skew insight for the case where BigQuery can’t rebalance the partitions, and Querylab.io’s plan lists it as Partition skew. Google’s advice for skewed joins is to filter as early as possible or to split the query into two or more queries.
Try these in order:
- Find the key. Count the hot keys. Fintel Analytics reports that the usual culprits are
NULLand placeholder values such as'UNKNOWN', and those can often be filtered out before the join. - Aggregate the other side, so the hot key arrives as one row. Instead of joining and then summing
amount * price, sumpriceper key first and then join. The answer is the same: for each row of the big side, the sum ofamount * priceover its matches equalsamounttimes the sum of their prices. - Process the hot keys separately and combine the two results with
UNION ALL. - Salt the key when none of those fit. It spreads one key over many workers at the price of more complex SQL. See skew for a worked example and published results.
Range joins become cross joins
A join with no equality in its condition has nothing to hash, so BigQuery compares every pair of rows. A join of timestamps to intervals with ON ts BETWEEN start_ts AND end_ts planned as CROSS ALL WITH ALL followed by a FILTER, on a single worker. With an extra equality on a bucket, ON r.bucket = w.bucket AND r.ts BETWEEN ..., it ran as a hash join. Pairs grow with the product of the two sides, so this is the join that is fine in a test and hangs on real data. Both of these return the same count:
WITH readings AS ( SELECT x AS ts FROM UNNEST(GENERATE_ARRAY(1, 2000)) AS x ), windows AS ( SELECT y AS start_ts, y + 9 AS end_ts FROM UNNEST(GENERATE_ARRAY(1, 2000, 10)) AS y ) SELECT COUNT(*) AS matched_pairs FROM readings AS r JOIN windows AS w ON r.ts BETWEEN w.start_ts AND w.end_ts
| Row | matched_pairs |
|---|---|
| 1 | 2000 |
WITH readings AS ( SELECT x AS ts, DIV(x - 1, 10) AS bucket FROM UNNEST(GENERATE_ARRAY(1, 2000)) AS x ), windows AS ( SELECT y AS start_ts, y + 9 AS end_ts, DIV(y - 1, 10) AS bucket FROM UNNEST(GENERATE_ARRAY(1, 2000, 10)) AS y ) SELECT COUNT(*) AS matched_pairs FROM readings AS r JOIN windows AS w ON r.bucket = w.bucket AND r.ts BETWEEN w.start_ts AND w.end_ts
| Row | matched_pairs |
|---|---|
| 1 | 2000 |
Compute a coarse bucket on both sides (a day, a 10-unit range) so the equality cuts the candidate pairs, and keep the range test as the second condition. This works when each interval falls inside one bucket. An interval that spans buckets needs one row per bucket it touches, or it will miss matches.
Other conditions with no plain equality also plan a cross join, such as a.k IN (b.k, b.j) and STARTS_WITH(a.s, b.s). The IN form is easy to avoid, because a.k = b.k OR a.k = b.j means the same and stays a hash join. An OR of equalities on different columns, like a.k = b.k OR a.j = b.j, hashes too. A prefix join has no such rewrite. a.s LIKE CONCAT(b.s, '%') and a.s LIKE b.s || '%' plan a cross join as well, and in a small test the LIKE form used far more slot time than STARTS_WITH(a.s, b.s), so try that one. STARTS_WITH gives the same rows only if b.s holds no %, _ or backslash.
All of these are a problem only on their own. Add one plain equality, as in a.j = b.j AND a.s LIKE CONCAT(b.s, '%'), and BigQuery hashes on it and applies the rest as a filter. Querylab.io warns about the IN and LIKE forms when the join has no equality, and offers the rewrite.
Shrink the sides before the join
Google’s advice is to filter each table before the join. You don’t have to move the filter yourself. We wrote the same filter on an inner join three ways, in WHERE, in the ON clause and in a subquery in FROM, and all three produced the same plan and read the same bytes, because BigQuery moves the filter below the join. On an outer join the place changes the answer, so check that first.
What matters is whether the filter shrinks a side. With no filter, our join of two 10-million-row tables was a hash join in four stages. A filter that kept about a tenth of one side turned it into the single-stage plan. Bytes read didn’t change, because there was no partition or cluster to prune. Filtering before a join reduces compute. It reduces bytes only when the filter prunes partitions or clusters.
Keys and columns
Everything a hash join needs from a row goes through shuffle, including the key and every column selected later. Select only the columns you need in the CTE before the join.
Google says to join on INT64 over STRING, because comparing strings costs more. Long keys also move more bytes. Daniel Imfeld hit the shuffle limit on keys of 64 and 128 characters and solved it by replacing them with integers. On short keys the difference is small, so don’t rework a table for it until the Shuffle column points there. Google also advises against calling functions on join columns. A CAST in the condition means the cast value is what moves through shuffle.
Long value lists
A filter on thousands of values is usually an IN (...) list. One suggested rewrite moves the list into a CTE and uses EXISTS. Which is better depends on the table. On a table clustered on the filtered column, we saw the EXISTS form lose block pruning and read more bytes, because BigQuery decides what to read before it runs the CTE. Teads reported the opposite on a wide, nested table, where the rewrite cut slot time by 89 percent and ended resourcesExceeded failures. Run both on your table and compare total_slot_ms. IN UNNEST([...]) is the shape to use when the values arrive as an array parameter.
Table order
Google’s guide says to put the largest table first, then the smallest. With a 10-million-row table and a 100,000-row one, inner and outer joins written either way round all planned as one stage with ALL WITH ALL, so the optimizer had chosen the sides itself. Follow the advice, since it costs nothing, and compare the two plans if a join of inputs that are hard to size looks wrong.
Self-joins and window functions
Google says to avoid self-joins and use window functions. The common case is “the latest row per key”. A self-join finds the maximum and joins back. A window function ranks the rows:
WITH readings AS ( SELECT 'a' AS sensor, 1 AS seq, 20.5 AS temp UNION ALL SELECT 'a', 2, 21.0 UNION ALL SELECT 'a', 3, 21.4 UNION ALL SELECT 'b', 1, 18.0 UNION ALL SELECT 'b', 2, 17.2 ) SELECT r.sensor, r.seq, r.temp FROM readings AS r JOIN ( SELECT sensor, MAX(seq) AS last_seq FROM readings GROUP BY sensor ) AS latest ON r.sensor = latest.sensor AND r.seq = latest.last_seq ORDER BY r.sensor
| Row | sensor | seq | temp |
|---|---|---|---|
| 1 | a | 3 | 21.4 |
| 2 | b | 2 | 17.2 |
WITH readings AS ( SELECT 'a' AS sensor, 1 AS seq, 20.5 AS temp UNION ALL SELECT 'a', 2, 21.0 UNION ALL SELECT 'a', 3, 21.4 UNION ALL SELECT 'b', 1, 18.0 UNION ALL SELECT 'b', 2, 17.2 ) SELECT sensor, seq, temp FROM readings WHERE TRUE QUALIFY ROW_NUMBER() OVER (PARTITION BY sensor ORDER BY seq DESC) = 1 ORDER BY sensor
| Row | sensor | seq | temp |
|---|---|---|---|
| 1 | a | 3 | 21.4 |
| 2 | b | 2 | 17.2 |
Both read the same bytes on our test table, and the self-join plan had twice as many stages, 6 against 3. In our dry runs a self-join was billed for each column of the table once, so a self-join of the public Shakespeare table costs exactly what a plain read of the same columns does:
SELECT a.word, b.corpus FROM `bigquery-public-data.samples.shakespeare` AS a JOIN `bigquery-public-data.samples.shakespeare` AS b USING (word)
This query will process 3.6 MB when run.
SELECT word, corpus FROM `bigquery-public-data.samples.shakespeare`
This query will process 3.6 MB when run.
Both are 3,797,568 bytes. So the bill doesn’t change, and the difference is in the plan. The window version is shorter and has fewer ways to go wrong. Where self-joins do hurt is when the key repeats, which is the fan-out above. See QUALIFY and window functions.
Constraints let BigQuery drop joins
PRIMARY KEY and FOREIGN KEY constraints can be declared as NOT ENFORCED, and the optimizer uses them. A LEFT JOIN from a 10-million-row table to a 100,000-row one, selecting only columns of the big table, was dry-run at 160.8 MB with no constraints and 80 MB once the small table had a primary key and the big one a matching foreign key. The join was removed. See primary and foreign keys. The cheapest join is one you don’t need, and nested and repeated columns avoid joins in the same way. See nested and repeated data.