Search code examples
sqloracle-databaseplsqloracle11gdivide-by-zero

divisor is equal to zero


i have the following data but in query i got the zero problem in division by zero. so i want the output as given below in two forms.

drop table t;

create table t (id number(9), val1 number(9), val2 number(9));
insert into t values (1,23,2);
insert into t values (2,0,4);
insert into t values (3,7,4);
insert into t values (4,0,3);
insert into t values (5,4,6);

select sqrt(val2*val1)/val1 from t ;

SQL> / ERROR: ORA-01476: divisor is equal to zero

expected reults

in two forms first query like this

        ID SQRT(VAL2*VAL1)/VAL1
---------- --------------------
         1           .294883912
         2                    0
         3           .755928946
         4                    0
         5           1.22474487

second query like this

       ID SQRT(VAL2*VAL1)/VAL1
---------- --------------------
         1           .294883912
         3           .755928946
         5           1.22474487

Solution

  • You can use

    select sqrt(val2*val1)/val1 from t where val1 != 0;

    That will avoid the rows where val1 is 0 and so will not cause the "divide by 0" error. This should give you the second format.

    For the first format where you want to show the 0 in the output you can use a case statement in the where clause.

    select id, 
    case 
        when val1 = 0 then 0
        when val1 != 0 then sqrt(val2*val1)/val1
    end
    from t