Search code examples
mysqlsqldivide-by-zero

MySQL: How to avoid division by zero when ordering?


I need to do something like the following:

SELECT * FROM Video WHERE visible = 1 ORDER BY votesUp/votesDown DESC

But I'm aware that votesDown can bear 0 (zero) as its value. How can I workaround to avoid the division by zero?

OBS: In my case, it's okay to make votesDown turn to 1, when 0.


Solution

  • With IF() function, you can convert 0 to 1. Could you try this?

    SELECT *
    FROM Video
    WHERE visible = 1 
    ORDER BY votesUp / IF(votesDown = 0, 1, votesDown) DESC