Division by Zero: Handling Error Messages in SQL Server When Dividing by 0

Ralf Sagmeister | July 6, 2026

Divisionbyzero

In this article, you’ll learn:

-Various alternatives

-the specific procedure

Then keep reading!

Methods for Proceeding

The "Division by 0" error is a common problem in SQL Server:
 

DECLARE @dividend INT
DECLARE @divisor INT

SET @dividend = 1
SET @divisor = 0
 

SELECT @dividend / @divisor
 

/*
Return value:
Error 8134, Level 16, State 1, Line 7
: Division by zero error
.*/
 

This post will discuss various ways to handle this error message in SQL Server when dividing by 0. Often, such errors only occur after a long period of time—that is, when the underlying tables or columns grow larger due to the data. What options are available to avoid this error?

Alternative 1: CASE
 

DECLARE @dividend INT
DECLARE @divisor INT
 

SET @dividend = 1
SET @divisor = 0
 

SELECT CASE
WHEN @divisor = 0 THEN NULL
ELSE @dividend / @divisor
END
 

/*
Return value = NULL */

 


Alternative 2: NULLIF
 

DECLARE @dividend INT
DECLARE @divisor INT
 

SET @dividend = 1
SET @divisor = 0
 

SELECT @dividend / NULLIF(@divisor, 0)

/*
Return value = NULL*/


Alternative 3: NULLIF with an alternative return value
 

DECLARE @dividend INT
DECLARE @divisor INT
 

SET @dividend = 1
SET @divisor = 0
 

SELECT COALESCE(@dividend / NULLIF(@divisor, 0), 0)
 

/*
Return value = 0 */


 

Alternative 4: A simple function

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE NAME = ‘division’) DROP FUNCTION division
go
CREATE FUNCTION dbo.division( @dividend decimal(38, 10), @divisor decimal(38, 10)) returns decimal(38, 10)
BEGIN
DECLARE @result decimal(38, 10);
SELECT @result = NULL;
IF ( @divisor IS NOT NULL
AND @divisor <> 0
AND @dividend IS NOT NULL )
SELECT @result = @dividend / @divisor;
RETURN( @result )
END
 

go


Alternative 5: ARITHABORT

Terminates a query if an overflow error or a division-by-zero (null) error occurs during the query.
 

SET ARITHABORT OFF
SET ANSI_WARNINGS OFF
 

DECLARE @dividend INT
DECLARE @divisor INT
 

SET @dividend = 1
SET @divisor = 0
 

SELECT @dividend / @divisor
 

/*
Return value = NULL */

 

SET ARITHABORT ON
SET ANSI_WARNINGS ON
 

The SET ARITHABORT setting is determined at runtime, not at analysis time. Even if SET ARITHABORT is set to OFF and SET ANSI_WARNINGS is set to ON, SQL Server returns an error message if an error occurs due to division by zero or an overflow error.

To check the current setting for ARITHABORT, you can run the following code:
 

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

Which method is best always depends on the specific situation. Do you have any questions? Feel free to contact our experts via our contact page or by phone at +49 7331 3076 – 0.