Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally handle division by zero with MySQL

Tags:

In MySQL, this query might throw a division by zero error:

SELECT ROUND(noOfBoys / noOfGirls) AS ration FROM student; 

If noOfGirls is 0 then the calculation fails.

What is the best way to handle this?

I would like to conditionally change the value of noOfGirls to 1 when it is equal to 0.

Is there a better way?

like image 940
Pushpendra Kuntal Avatar asked Nov 23 '11 16:11

Pushpendra Kuntal


People also ask

How to handle divide by zero error in MySQL?

The first solution uses the NULLIF() function, which takes two numbers as arguments. When the first argument is equal to the other argument, the function returns NULL as a result. If number_b is equal to zero, the divisor is NULL , and the result of the division is NULL . The second solution uses the CASE statement.

Can you do division in MySQL?

MySQL allows you to divide integer or floating point numbers by using the division operator ( / ) or the integer division DIV operator. The division operator returns a floating number even when the division result is an integer.

What is divide in MySQL?

DIV() function : This function in MySQL is used to return a quotient (integer) value when integer division is done. For example, when 7 is divided by 3, then 2 will be returned.


1 Answers

Yes, you can do a case:

select case when noOfGirls=0 then noOfBoys         else  round(noOfBoys/noOfGirls) end as ration  from student; 

But you probably want:

select case when noOfGirls=0 then 1         else  round(noOfBoys/noOfGirls) end as ration  from student; 
like image 132
Icarus Avatar answered Sep 17 '22 19:09

Icarus