How to conditionally handle division by zero with MySQL

前端 未结 7 831
春和景丽
春和景丽 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条回答
  • 2020-12-28 16:41

    GREATEST(x, 1)

    Can be used since the number of girls must be positive:

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

    But it is not very portable across SQL implementations.

    Documentation: http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_greatest

    0 讨论(0)
  • 2020-12-28 16:41

    Well if you want to set noOfGirls to 1 if it's 0, then the following should work:

    SELECT ROUND(noOfBoys / if(noOfGirls, noOfGirls, 1)) as ration FROM student;
    
    0 讨论(0)
  • 2020-12-28 16:43

    check if the denominator is zero and the nominator is not NULL - if yes then use 'NaN'.

    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-12-28 16:49

    You can use this (over-expressive) way:

    select IF(noOfGirls=0, NULL, round(noOfBoys/noOfGirls)) as ration from student;
    

    Which will put out NULL if there are no girls, which is effectively what 0/0 should be in SQL semantics.

    MySQL will anyway give NULL if you try to do 0/0, as the SQL meaning fo NULL is "no data", or in this case "I don't know what this value can be".

    0 讨论(0)
  • 2020-12-28 16:52
    select
        case student.noOfGirls
               when 0 then 1
               else  round(noOfBoys/noOfGirls)
        end as ration
    from
        `student`
    
    0 讨论(0)
提交回复
热议问题