How to conditionally handle division by zero with MySQL

前端 未结 7 1070
春和景丽
春和景丽 2020-12-28 16:01

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

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

If noOfGirls

7条回答
  •  萌比男神i
    2020-12-28 16:46

    Division by NULL actually works in MySQL server and returns NULL. So you can do:

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

    I think NULL ratio is the most accurate for this case. If you need the ratio to be equal to numOfBoys then you can use:

    SELECT COALESCE(ROUND(noOfBoys / NULLIF(noOfGirls, 0)), noOfBoys) AS ration FROM student;
    

提交回复
热议问题