Practical SQL

Raising ERRORS in BigQuery

Constantin LunguUpdated 1 min read

Photo by Etienne Girardet on Unsplash

Does anyone have interesting use cases for the ERROR function in BigQuery?

If you like BQ errors so much that you've decided to create your own, or if you're debugging with dirty data, maybe check it out.

If will raise an error that you specify whenever executed. Plus you can also combine it with FORMAT to see what was the value that generated the issue.

Input data: input_data with population and surface, five rows labelled OK or ERROR: 10000 / 60 and 7000 / 35 are OK; 20000 / 0, 25000 / null and 25000 / -1 are ERROR.

BigQuery results for the two OK rows: population_density 166.6666666666... and 200.0.

SELECT population/surface AS population_density
FROM input_data
WHERE IF(IFNULL(surface,0) > 0,
         TRUE,
         ERROR(FORMAT('Error: surface must be strictly greater than 0, but is %t', surface)));

The query fails with the error Error: surface must be strictly greater than 0, but is 0.

SELECT population / CASE WHEN IFNULL(surface,0) > 0 THEN surface
                         ELSE ERROR(FORMAT('Error: surface must be strictly greater than 0, but is %t', surface)) END AS population_density

FROM input_data

The query fails with the error Error: surface must be strictly greater than 0, but is NULL.