Solving correlated subquery error in BigQuery

Nick Lydon
Apr 28, 2022

Recently I had to create an array whilst selecting from another array in Google BigQuery:

SELECT ARRAY(
SELECT AS STRUCT
b.Column
FROM UNNEST(a.Parts) p
LEFT OUTER JOIN TableB b ON b.JoinColumn = p.JoinColumn
)
FROM TableA a

Unfortunately trying to use an outer join prompts the error message: Error: Correlated subqueries that reference other tables are not
supported unless they can be de-correlated, such as by transforming
them into an efficient JOIN.'

The solution for me was to extract the outer join into a separate subquery and do a left join on that one instead:

WITH separateSubquery AS (
SELECT *
FROM TableA a,
UNNEST(a.Parts) p
LEFT OUTER JOIN TableB b ON b.JoinColumn = p.JoinColumn
)
SELECT ARRAY(
SELECT AS STRUCT
b.Column
FROM UNNEST(a.Parts) p
LEFT JOIN separateSubquery b ON b.Id = p.Id
)
FROM TableA a

--

--

Nick Lydon

British software developer working as a freelancer in Berlin. Mainly dotnet, but happy to try new things! https://github.com/NickLydon