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:
Or
Is the best way to use a NULLIF
clause?
Is there better way, or how can this be enforced?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With