Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bigQuery throws "division by zero: 0 / 0" error

I am doing the percentage by the frequency of column value using bigquery. However, some of the value might be zero, so the query will return error for sure

(division by zero: 0 / 0)

How to apply kind of IFERROR(x/y,null) in this case? so the query will bounce null value as the result instead of error?

SELECT 
    User_ID, 
   ROUND(SUM(CASE WHEN Name LIKE '%MIKE%' THEN 1 ELSE 0 END) / COUNT(Name) * 100 ,1) AS Percentage_of_MIKE,
    
FROM
  table
GROUP BY 
  User_ID

TRIED:

ROUND(SAFE_DIVIDE(SUM(CASE WHEN Name LIKE '%MIKE%' THEN 1 ELSE 0 END) / COUNT(Name) * 100 ,1)) AS Percentage_of_MIKE,
like image 685
swm Avatar asked Feb 19 '26 22:02

swm


1 Answers

You can just use SAFE_DIVIDE function in such cases

Something like in below example

ROUND(SAFE_DIVIDE(SUM(CASE WHEN Name LIKE '%MIKE%' THEN 1 ELSE 0 END), COUNT(Name) * 100) ,1) AS Percentage_of_MIKE
like image 65
Mikhail Berlyant Avatar answered Feb 22 '26 11:02

Mikhail Berlyant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!