Q:

Can I catch out of memory errors when using STRING_AGG on BigQuery?

This question explains what happens when you try to aggregate too many things with STRING_AGG in BigQuery.
Is there a way I can do something like "Try STRING_AGG, but if it's too much data, return null (or something) instead"? So I can fallback from errors without the query failing.

A:

In What is the max limit of group_concat/string_agg in bigquery output? Elliott explains why STRING_AGG might produce out of memory errors.
To prevent this error, you can use LIMIT to stop aggregating after certain number of strings:
#standardSQL
SELECT STRING_AGG(CONCAT(word, corpus) LIMIT 10) AS words
FROM `bigquery-public-data.samples.shakespeare`
CROSS JOIN UNNEST(GENERATE_ARRAY(1, 1000));

