Skip to content
Advertisement

Divide by zero error encountered error. Null value is eliminated by an aggregate or other SET operation

In this specific part of a SP I’m trying to create, I’m getting an error:

[Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Divide by zero error encountered. Additional error <2>: ErrorMsg: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Warning: Null value is eliminated by an aggregate or other SET operation., SqlState: 01003, NativeError: 8153

I believe this is because I’m trying to divide by a null or 0. I’m unsure how I can work around this. I tried to use ISNULL but I think I’m not doing it right.

select 
    id_date,
    id_company,
    id_kpi,
    sum(CASE WHEN id_kpi=50 THEN -actual_mes END) /
    sum(CASE WHEN id_kpi=51 THEN actual_mes END) Amount
from dual;

Can someone point me in the right direction? I’ve looked at a few other threads on this, but I’m still not sure how to solve this.

Advertisement

Answer

Rather than the CASE, I usually opt for NullIf() on the denominator

Example

select id_date,
       id_company,
       id_kpi,
       sum(CASE  WHEN id_kpi=50 THEN -actual_mes END) /
       nullif(sum(CASE  WHEN id_kpi=51 THEN actual_mes END),0) Amount
  from dual;
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement