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?
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With