In my SQLite statement below there is a problem with division by zero in the case count(t2.ref_id) is zero.
Could I adjust the SQLite statement so that if the count(t2.ref_id) is zero the scarsity (scarsity factor) will be higher than the highest non-zero scarsity?
select t1.id, cast(:totalItems as float) / count(t2.ref_id) as scarsity
from t1 left join t2 on t1.id = t2.ref_id
group by t1.id
order by scarsity
You need to check for the value 0 and do something different. One common way is to divide by
NULLas many SQL varieties haveNULLIF()to turn a value into aNULLinstead.But I’m not sure that SQLite has
NULLIF(), so you could use the more long windedCASEversion instead…The
COUNT()won’t be calculated twice even though you typed it twice. The value will be re-used 🙂Alternatively, do something completely different if you get 0 rows…
Then you can check for NULLs as being the highest value, or just check for 9999999, etc, etc.