xralf
xralf

Reputation: 3692

Correcting division by zero in SQLite

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

Upvotes: 3

Views: 3027

Answers (1)

MatBailie
MatBailie

Reputation: 86765

You need to check for the value 0 and do something different. One common way is to divide by NULL as many SQL varieties have NULLIF() to turn a value into a NULL instead.

select t1.id, cast(:totalItems as float) / NULLIF(count(t2.ref_id), 0) as scarsity
from t1 left join t2 on t1.id = t2.ref_id
group by t1.id
order by scarsity

But I'm not sure that SQLite has NULLIF(), so you could use the more long winded CASE version instead...

select t1.id, cast(:totalItems as float) / CASE WHEN count(t2.ref_id) = 0 THEN NULL ELSE count(t2.ref_id) END as scarsity
from t1 left join t2 on t1.id = t2.ref_id
group by t1.id
order by scarsity

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...

select t1.id, CASE WHEN count(t2.ref_id) = 0 THEN 9999999 ELSE cast(:totalItems as float) / count(t2.ref_id) END as scarsity
from t1 left join t2 on t1.id = t2.ref_id
group by t1.id
order by scarsity

Then you can check for NULLs as being the highest value, or just check for 9999999, etc, etc.

Upvotes: 2

Related Questions