Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid the "divide by zero" error in SQL?

I have this error message:

Msg 8134, Level 16, State 1, Line 1 Divide by zero error encountered.

What is the best way to write SQL code so that I will never see this error message again?

I could do either of the following:

  • Add a where clause so that my divisor is never zero

Or

  • I could add a case statement, so that there is a special treatment for zero.

Is the best way to use a NULLIF clause?

Is there better way, or how can this be enforced?

like image 911
Henrik Staun Poulsen Avatar asked May 14 '09 06:05

Henrik Staun Poulsen


People also ask

How do I stop divide by 0 in SQL?

If you'd like to handle division by zero gracefully, you can use the NULLIF function. NULLIF takes two arguments: the expression of interest, and the value you want to override. If the first argument is equal to the second, then NULLIF returns NULL; otherwise, it returns the first argument.

How do I stop division by zero in MySQL?

We often use the NULLIF function to prevent the division by zero error in a query. If the MySQL server has ERROR_FOR_DIVISION_BY_ZERO mode enabled, it will issue an error when a division by zero occurred. Because zero is equal to zero, the expression NULLIF(0,0) returns NULL. As the result, the statement returns NULL.

How do I stop dividing by zero error in Python?

In Python, we use a try block that contains a return statement to divide 2 numbers. If there is no division by zero error, then it will return the result. Otherwise, the except line will check if the specified exception name is a match, and then it will execute the code under the except block.


2 Answers

In order to avoid a "Division by zero" error we have programmed it like this:

Select Case when divisor=0 then null Else dividend / divisor End ,,, 

But here is a much nicer way of doing it:

Select dividend / NULLIF(divisor, 0) ... 

Now the only problem is to remember the NullIf bit, if I use the "/" key.

like image 81
Henrik Staun Poulsen Avatar answered Oct 05 '22 12:10

Henrik Staun Poulsen


In case you want to return zero, in case a zero devision would happen, you can use:

SELECT COALESCE(dividend / NULLIF(divisor,0), 0) FROM sometable 

For every divisor that is zero, you will get a zero in the result set.

like image 31
Tobias Domhan Avatar answered Oct 05 '22 11:10

Tobias Domhan