Question

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.

Was it helpful?

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

OTHER TIPS

This will do:

SELECT * FROM Video WHERE visible = 1
ORDER BY votesUp / CASE votesDown WHEN 0 THEN 1 ELSE votesDown END DESC;

However, you would usually order by the percentage of upvotes of all votes. When there are no votes at all, the result is undefined, so use NULL then:

SELECT * FROM Video WHERE visible = 1
ORDER BY votesUp / NULLIF(votesUp + votesDown, 0) DESC;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top