Divizion by zero ошибка sql

EDIT:
I’m getting a lot of downvotes on this recently…so I thought I’d just add a note that this answer was written before the question underwent it’s most recent edit, where returning null was highlighted as an option…which seems very acceptable. Some of my answer was addressed to concerns like that of Edwardo, in the comments, who seemed to be advocating returning a 0. This is the case I was railing against.

ANSWER:
I think there’s an underlying issue here, which is that division by 0 is not legal. It’s an indication that something is fundementally wrong. If you’re dividing by zero, you’re trying to do something that doesn’t make sense mathematically, so no numeric answer you can get will be valid. (Use of null in this case is reasonable, as it is not a value that will be used in later mathematical calculations).

So Edwardo asks in the comments «what if the user puts in a 0?», and he advocates that it should be okay to get a 0 in return. If the user puts zero in the amount, and you want 0 returned when they do that, then you should put in code at the business rules level to catch that value and return 0…not have some special case where division by 0 = 0.

That’s a subtle difference, but it’s important…because the next time someone calls your function and expects it to do the right thing, and it does something funky that isn’t mathematically correct, but just handles the particular edge case it’s got a good chance of biting someone later. You’re not really dividing by 0…you’re just returning an bad answer to a bad question.

Imagine I’m coding something, and I screw it up. I should be reading in a radiation measurement scaling value, but in a strange edge case I didn’t anticipate, I read in 0. I then drop my value into your function…you return me a 0! Hurray, no radiation! Except it’s really there and it’s just that I was passing in a bad value…but I have no idea. I want division to throw the error because it’s the flag that something is wrong.

This article explores the SQL divide by zero error and various methods for eliminating this.

Introduction

We all know that in math, it is not possible to divide a number by zero. It leads to infinity:

SQL Divide by Zero

Source: www.1dividedby0.com

If you try to do in calculator also, you get the error message – Cannot Divide by zero:

Divide by Zero message in calculator

We perform data calculations in SQL Server for various considerations. Suppose we perform an arithmetic division operator for calculating a ratio of products in a store. Usually, the division works fine, and we get the ratio:

DECLARE @Product1 INT;

    DECLARE @Product2 INT;

    SET @Product1 = 50;

    SET @Product2 = 10;

    SELECT @Product1 / @Product2 ProductRatio;

SQL divide

Someday, the product2 quantity goes out of stock and that means we do not have any quantity for product2. Let’s see how the SQL Server query behaves in this case:

DECLARE @Product1 INT;

    DECLARE @Product2 INT;

    SET @Product1 = 50;

    SET @Product2 = 0;

    SELECT @Product1 / @Product2 ProductRatio;

We get SQL divide by zero error messages (message id 8134, level 16):

SQL error message

We do not want our code to fail due to these errors. It is a best practice to write code in such a way that it does not give divide by zero message. It should have a mechanism to deal proactively with such conditions.

SQL Server provides multiple methods for avoiding this error message. Let’s explore it in the next section.

Method 1: SQL NULLIF Function

We use NULLIF function to avoid divide by zero error message.

The syntax of NULLIF function:

NULLIF(expression1, expression2)

It accepts two arguments.

  • If both the arguments are equal, it returns a null value

    For example, let’s say both arguments value is 10:

    SELECT NULLIF(10, 10) result;

    In the screenshot, we can see that the output is null:

    NULLIF function

  • If both the arguments are not equal, it returns the value of the first argument

    In this example, both argument values differ. It returns the output as value of first argument 10:

    SELECT NULLIF(10, 5) result;

    NULLIF function output

Let’s modify our initial query using the SQL NULLIF statement. We place the following logic using NULLIF function for eliminating SQL divide by zero error:

  • Use NULLIF function in the denominator with second argument value zero
  • If the value of the first argument is also, zero, this function returns a null value. In SQL Server, if we divide a number with null, the output is null as well
  • If the value of the first argument is not zero, it returns the first argument value and division takes place as standard values

DECLARE @Product1 INT;

        DECLARE @Product2 INT;

        SET @Product1 = 50;

        SET @Product2 = 0;

        SELECT @Product1 / NULLIF(@Product2,0) ProductRatio;

Execute this modified query. We can see the output NULL because denominator contains value zero.

NULLIF to avoid error message

Do we want null value in the output? Is there any method to avoid null and display a definite value?

Yes, we can use SQL ISNULL function to avoid null values in the output. This function replaces the null value in the expression1 and returns expression2 value as output.

Let’s explore the following query with a combination of SQL NULLIF and SQL ISNULL function:

  • First argument ((@Product1 / NULLIF(@Product2,0)) returns null
  • We use the ISNULL function and specify the second argument value zero. As we have the first argument null, the output of overall query is zero (second argument value)

DECLARE @Product1 INT;

        DECLARE @Product2 INT;

        SET @Product1 = 50;

        SET @Product2 = 0;

        SELECT ISNULL(@Product1 / NULLIF(@Product2,0),0) ProductRatio;

NULLIF and ISNULL function

Method 2: Using CASE statement to avoid divide by zero error

We can use a CASE statement in SQL to return values based on specific conditions. Look at the following query. It does the following task with the Case statement.

The Case statement checks for the value of @Product2 parameter:

  • If the @Product2 value is zero, it returns null
  • If the above condition is not satisfied, it does the arithmetic operation (@Product1/@Product2) and returns the output

Using CASE statement to avoid divide by zero error

Method 3: SET ARITHABORT OFF

We can use set methods to control query behavior. By default, SQL Server has a default value of SET ARITHABORT is ON. We get SQL divide by zero error in the output using the default behavior.

The T-SQL syntax for controlling the ARITHABORT option is shown below:

SET ARITHABORT { ON | OFF }

  • Using ARITHABORT ON, the query will terminate with divide by zero message. It is the default behavior. For this demo, let’s enable it using the SET ARITHABORT ON statement:

    SET ARITHABORT ON   — Default

            SET ANSI_WARNINGS ON

            DECLARE @Product1 INT;

            DECLARE @Product2 INT;

            SET @Product1 = 50;

            SET @Product2 = 0;

            SELECT @Product1 / @Product2 ProductRatio;

    We get the SQL divide by zero error messages:

    default property ARITHABORT ON

  • Using ARITHABORT OFF, the batch will terminate and returns a null value. We need to use ARITHABORT in combination with SET ANSI_WARNINGS OFF to avoid the error message:

     ARITHABORT OFF to supress error message

    We can use the following query to check the current setting for the ARITHABORT parameter:

    DECLARE @ARITHABORT VARCHAR(3) = ‘OFF’;  

        IF ( (64 & @@OPTIONS) = 64 ) SET @ARITHABORT = ‘ON’;  

        SELECT @ARITHABORT AS ARITHABORT;

    The default ARITHABORT setting for SSMS is ON. We can view it using SSMS Tools properties. Navigate to Tools -> Options -> Advanced:

    SSMS tool default property

    Many client applications or drivers provide a default value of ARITHABORT is OFF. The different values might force SQL Server to produces a different execution plan, and it might create performance issues. You should also match the setting similar to a client application while troubleshooting the performance issues.

    Note: You should not modify the value of ARITHABORT unless required. It might create performance issues, as well. I would suggest using alternative methods (as described earlier) for avoiding SQL divide by zero error.

Conclusion

In this article, we explored the various methods for avoiding SQL divide by zero error. It is best practice to be proactive and use these mechanisms so that code does not fail in real-time.

  • Author
  • Recent Posts

Rajendra Gupta

Hi! I am Rajendra Gupta, Database Specialist and Architect, helping organizations implement Microsoft SQL Server, Azure, Couchbase, AWS solutions fast and efficiently, fix related issues, and Performance Tuning with over 14 years of experience.

I am the author of the book «DP-300 Administering Relational Database on Microsoft Azure». I published more than 650 technical articles on MSSQLTips, SQLShack, Quest, CodingSight, and SeveralNines.

I am the creator of one of the biggest free online collections of articles on a single topic, with his 50-part series on SQL Server Always On Availability Groups.

Based on my contribution to the SQL Server community, I have been recognized as the prestigious Best Author of the Year continuously in 2019, 2020, and 2021 (2nd Rank) at SQLShack and the MSSQLTIPS champions award in 2020.

Personal Blog: https://www.dbblogger.com
I am always interested in new challenges so if you need consulting help, reach me at rajendra.gupta16@gmail.com

View all posts by Rajendra Gupta

Rajendra Gupta

Stuck with ‘SQL server divide by zero error encountered’? We can help you.

Recently, one of our customer came across this error as it is not possible to divide a number by zero. It leads to infinity. We perform data calculations in SQL Server for various considerations.

As part of your Server Management Services, we assist our customers with several SQL queries.

Today, let us see how to fix this error.

Cause for the error ‘SQL Server divide by zero error encountered’

Let us see what could cause the error ‘SQL Server divide by zero error encountered’.

To start with, If the product2 quantity goes out of stock and that means we do not have any quantity for product2.

DECLARE @Product1 INT;
DECLARE @Product2 INT;
SET @Product1 = 50;
SET @Product2 = 0;
SELECT @Product1 / @Product2 ProductRatio;

We get SQL divide by zero error messages (message id 8134, level 16):

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

How to solve the error ‘SQL Server divide by zero error encountered’?

Always, it is a best practice to write code in such a way that it does not give divide by zero message. It should have a mechanism to deal proactively with such conditions.

Moving ahead, let us see an effective methods followed by our Support Techs employ in order to solve this error.

Method 1: SQL NULLIF Function

Initially, we use NULLIF function to avoid divide by zero error message.

The syntax of NULLIF function:

NULLIF(expression1, expression2)

It accepts two arguments.

  • Firstly, If both the arguments are equal, it returns a null value

For example, suppose that the value of both arguments is 10.

SELECT NULLIF(10, 10) result;

In this case, the output will be null.

  •  Secondly, If both the arguments are not equal, it returns the value of the first argument.

In this example, both argument values differ. It returns the output as value of first argument 10.

SELECT NULLIF(10, 5) result;

We can modify our initial query using the SQL NULLIF statement. We place the following logic using NULLIF function for eliminating SQL divide by zero error:

  • Use NULLIF function in the denominator with second argument value zero
  • If the value of the first argument is also zero, this function returns a null value. In SQL Server, if we divide a number with null, the output is null as well.
  • If the value of the first argument is not zero, it returns the first argument value and division takes place as standard values.
DECLARE @Product1 INT;
DECLARE @Product2 INT;
SET @Product1 = 50;
SET @Product2 = 0;
SELECT @Product1 / NULLIF(@Product2,0) ProductRatio;

Execute this modified query. We will get the output as NULL because denominator contains value zero.

If we do not want null value in the output, we can use SQL ISNULL function to avoid null values in the output and display a definite value. This function replaces the null value in the expression1 and returns expression2 value as output.

Method 2: Using CASE statement to avoid divide by zero error

Secondly, you can use a CASE statement in SQL to return values based on specific conditions. The Case statement checks for the value of @Product2 parameter:

  •  If the @Product2 value is zero, it returns null.
  • If the above condition is not satisfied, it does the arithmetic operation (@Product1/@Product2) and returns the output.
DECLARE @Product1 INT;
DECLARE @Product2 INT;
SET @Product1 = 50;
SET @Product2 = 0;
SELECT CASE
WHEN @Product2 = 0
THEN NULL
ELSE @Product1 / @Product2
END AS ProductRatio;

We will get output as NULL.

Method 3: SET ARITHABORT OFF

By default, SQL Server has a default value of SET ARITHABORT is ON. We get SQL divide by zero error in the output using the default behavior.

The T-SQL syntax for controlling the ARITHABORT option is shown below:

SET ARITHABORT { ON | OFF }

  •  Using ARITHABORT ON, the query will terminate with divide by zero message. It is the default behavior.
SET ARITHABORT ON — Default
SET ANSI_WARNINGS ON
DECLARE @Product1 INT;
DECLARE @Product2 INT;
SET @Product1 = 50;
SET @Product2 = 0;
SELECT @Product1 / @Product2 ProductRatio;

We get the SQL divide by zero error messages.

  • Using ARITHABORT OFF, the batch will terminate and returns a null value. We need to use ARITHABORT in combination with SET ANSI_WARNINGS OFF to avoid the error message:
SET ARITHABORT OFF
SET ANSI_WARNINGS OFF
DECLARE @Product1 INT;
DECLARE @Product2 INT;
SET @Product1 = 50;
SET @Product2 = 0;
SELECT @Product1 / @Product2 ProductRatio;

We will get the output as NULL.

Finally, you can use the following query to check the current setting for the ARITHABORT parameter:

DECLARE @ARITHABORT VARCHAR(3) = ‘OFF’;
IF ( (64 & @@OPTIONS) = 64 ) SET @ARITHABORT = ‘ON’;
SELECT @ARITHABORT AS ARITHABORT;

The default ARITHABORT setting for SQL Server Management Studio (SSMS) is ON. We can view it using SSMS Tools properties. Navigate to Tools -> Options -> Advanced.

We should not modify the value of ARITHABORT unless required. It might create performance issues, as well. It is better to use other methods for avoiding SQL divide by zero error.

[Need assistance? We can help you]

Conclusion

In short, we saw how our Support Techs resolve error ‘SQL Server divide by zero error encountered’

Are you using Docker based apps?

There are proven ways to get even more out of your Docker containers! Let us help you.

Spend your time in growing business and we will take care of Docker Infrastructure for you.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

In this article, we will look at how to avoid the “divide by zero” error in SQL. If we divide any number by zero, it leads to infinity, and we get an error message. We can avoid this error message using the following three methods:

  • Using NULLIF() function
  • Using CASE statement
  • Using SET ARITHABORT OFF

We will be creating a database first to perform SQL operations.

Query:

CREATE DATABASE Test;

Output:

Commands completed successfully show the database “Test” is created.

For all the methods we need to declare two variables that will store the values of the numerator and denominator.

DECLARE @Num1 INT;
DECLARE @Num2 INT;

After declaring the variable we have to set the values. Set the second variable value as zero.

SET @Num1=12;
SET @Num2=0;

Method 1: Using NULLIF() function

If both arguments are equal, it returns NULL. If both arguments are not equal, it returns the value of the first argument.

Syntax:

NULLIF(exp1, exp2);

Now we are using the NULLIF() function in the denominator with the second argument value zero. 

SELECT @Num1/NULLIF(@Num2,0) AS Division;
  • In the SQL server, if we divide any number with a NULL value its output will be NULL.
  • If the first argument is zero, it means if the Num2 value is zero, then NULLIF() function returns the NULL value.
  • If the first argument is not zero, then NULLIF() function returns the value of that argument. And the division takes place as regular.

Here is the complete query.

Query:

DECLARE @Num1 INT;
DECLARE @Num2 INT;
SET @Num1=12;
SET @Num2=0;
SELECT @Num1/NULLIF(@Num2,0) AS Division;

Output:

Method 2: Using the CASE statement

The SQL CASE statement is used to check the condition and return a value. It checks the conditions until it is true and if no conditions are true it returns the value in the else part.

We have to check the value of the denominator i.e the value of the Num2 variable. If it is zero then return NULL otherwise return the regular division.

SELECT CASE
WHEN @Num2=0
THEN NULL
ELSE @Num1/@Num2
END AS Division;

Here is the complete query:

Query:

DECLARE @Num1 INT;
DECLARE @Num2 INT;
SET @Num1=12;
SET @Num2=0;
SELECT CASE
    WHEN @Num2=0
    THEN NULL
    ELSE @Num1/@Num2
END AS Division;

Output:

Method 3: SET ARITHABORT OFF

To control the behavior of queries, we can use SET methods. By default, ARITHABORT is set as ON. It terminates the query and returns an error message. If we set it OFF it will terminate and returns a NULL value.

Like ARITHBORT, we have to set ANSI_WARNINGS OFF to avoid the error message.

SET ARITHABORT OFF;
SET ANSI_WARNINGS OFF;

Here is the complete query:

Query:

SET ARITHABORT OFF;
SET ANSI_WARNINGS OFF;
DECLARE @Num1 INT;
DECLARE @Num2 INT;
SET @Num1=12;
SET @Num2=0;
Select @num1/@Num2;

Output:

Last Updated :
25 Oct, 2021

Like Article

Save Article

In this article, we will be discussing about the “Divide by zero error encountered” error message in SQL Server.

About the “Divide by zero error encountered” error message

Well, as the error message says, whenever we have a division within a SQL query and the denominator has the value of zero (0) we get this error.

The exact error we get in SQL Server is:

Msg 8134, Level 16, State 1, Line [Here goes the line of the denominator in your query]
Divide by zero error encountered.

So, which is the best way of addressing this issue? As it is data-related we should be precautious anyway when having a division within a query and effectively control the denominator values for handling the case where a zero might be produced.

Just for reproducing the divide by zero error, consider the following example query:

declare @denominator int
set @denominator=0

select 1/@denominator

Different Approaches for Handling the Issue

There are a few approaches of handling such problem. Here I present three.

Approach 1 – Using the “SET ANSI_WARNINGS OFF” Command

By using the “SET ANSI_WARNINGS OFF” command just right before the rest of the queries, it will allow your query that produces the error not to stop the execution of the rest of the queries.

Example:

SET ANSI_WARNINGS OFF

declare @denominator int
set @denominator=0

select 1/@denominator

.... Other queries go here

Approach 2 – Using the CASE Statement

By using the CASE statement it is possible to check the denominator value for a zero and if it is so you can use 1 in order for the division not to fail.

Example Query:

declare @denominator int
set @denominator=0

select 1/(case @denominator when 0 then 1 else @denominator end)

Alternatively, you can create a custom scalar-valued function that given an input parameter, it can check for a zero and if it is encountered it can return 1 else it should return the input:

CREATE FUNCTION check_denominator
(
-- Function parameter
@input int
)
RETURNS int
AS
BEGIN

-- Declare local variable
DECLARE @result int

-- Check for 0, if so then return 1 else return the input
SET @result =(SELECT (CASE @input when 0 then 1 else @input end))

-- Return the result
RETURN @result

END
GO

Then you can use the above function as follows:

declare @denominator int
set @denominator=0

select 1/dbo.check_denominator(@denominator)

Strengthen you SQL Server Development Skills – Enroll to our Online Course!

Check our online course titled “Essential SQL Server Development Tips for SQL Developers
(special limited-time discount included in link).

Via the course, you will sharpen your SQL Server database programming skills via a large set of tips on T-SQL and database development techniques. The course, among other, features over than 30 live demonstrations!

Essential SQL Server Development Tips for SQL Developers - Online Course

(Lifetime Access/ Live Demos / Downloadable Resources and more!)

Enroll from $12.99

Approach 3 – Using the NULLIF Function

Yep, by using the NULLIF function it is possible to handle the issue of a zero denominator.
But how? 🙂

The NULLIF function takes two arguments and if they have equal values it then returns a NULL.

The idea here is to compare the denominator value with a zero via NULLIF and if it returns a NULL then to handle it with the ISNULL function (by placing the number 1)!

Example:

declare @denominator int
set @denominator=0

select 1/ISNULL(NULLIF(@denominator,0),1)

Concluding Remarks

Which of the above three approaches is the best one? Well, this is up to you 🙂

Personally I do not prefer Approach 1 as it does not solve the problem but rather “says” to SQL Server to ignore it.

So we have Approach 2 and 3 left. Approach 2 looks appealing but still I would only use it with a function.

My personal opinion is that Approach 3 is the best one; it just uses two built-in SQL Server functions and you do not need to write much additional code for handling a zero denominator!

Tip: Also, whenever you have a division in your query keep in mind that if you use only integer variables (like in this example 🙂 and the calculated denominator value is below zero it will return a zero so be careful with that as well (you can use float or decimal instead)!

Featured Online Courses:

  • Introduction to Azure SQL Database for Beginners
  • SQL Server 2019: What’s New – New and Enhanced Features
  • SQL Server Fundamentals – SQL Database for Beginners
  • Essential SQL Server Administration Tips
  • Boost SQL Server Database Performance with In-Memory OLTP 
  • Essential SQL Server Development Tips for SQL Developers
  • Working with Python on Windows and SQL Server Databases
  • Introduction to Computer Programming for Beginners
  • .NET Programming for Beginners – Windows Forms with C#
  • Introduction to SQL Server Machine Learning Services
  • Entity Framework: Getting Started – Complete Beginners Guide
  • How to Import and Export Data in SQL Server Databases
  • Learn How to Install and Start Using SQL Server in 30 Mins
  • A Guide on How to Start and Monetize a Successful Blog

Check Some of Our Other SQL Server Articles:

  • Essential SQL Sever Administration Tips
  • How to Patch a Standalone SQL Server Instance
  • The SQL Server Browser Service and UDP Port 1434
  • The Maximum Number of Concurrent Connections Setting in SQL Server
  • Top 10 SQL Server DBA Daily Tasks List
  • There is no SQL Server Failover Cluster Available to Join
  • Encrypting a SQL Server Database Backup
  • …more

Rate this article: 1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading…

Reference: SQLNetHub.com (https://www.sqlnethub.com)

© SQLNetHub

Artemakis Artemiou

Artemakis Artemiou is a Senior SQL Server Architect, Author, a 9 Times Microsoft Data Platform MVP (2009-2018). He has over 20 years of experience in the IT industry in various roles. Artemakis is the founder of SQLNetHub and {essentialDevTips.com}. Artemakis is the creator of the well-known software tools Snippets Generator and DBA Security Advisor. Also, he is the author of many eBooks on SQL Server. Artemakis currently serves as the President of the Cyprus .NET User Group (CDNUG) and the International .NET Association Country Leader for Cyprus (INETA). Moreover, Artemakis teaches on Udemy, you can check his courses here.

Views: 6,108

We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit «Cookie Settings» to provide a controlled consent. Read More

  • Divinity original sin 2 ошибка подключения к серверу
  • Divinity original sin 2 ошибка записи на диск
  • Divinity original sin 2 ошибка directx
  • Divinity original sin 2 ошибка 503 504
  • Divinity original sin 2 квест ошибки прошлого