September 26, 2011

SQL Server: Handling Divide By Zero Error

Often SQL developers encounter "Divide by zero" error. This is because in an arithmetic
expression, when the divisor is zero (0), the expression throws an error. If you want to simply return NULL instead of an error, you can use one of the following methods

Method 1 : Use CASE expression

declare @var1 int ,@var2 int
select @var1=763, @var2=0

select @var1/case when @var2 =0 then null else @var2 end



Method 2 : Use NULLIF function

declare @var1 int ,@var2 int
select @var1=763, @var2=0

select @var1/nullif(@var2,0)

The NULLIF function compares the first parameter (var2) with second parameter (0). If they are same, it returns a NULL

Did you like this post?
kick it on
subscribe via rss subscribe via e-mail
print this post follow me on twitter

About The Author

Madhivanan,an MSc computer Science graduate from Chennai-India, works as a works as a Lead Subject Matter Expert at a company that simplifies BIG data. He started his career as a developer working with Visual Basic 6.0, SQL Server 2000 and Crystal Report 8. As years went by, he started working more on writing queries in SQL Server. He now has good level of knowledge in SQLServer, Oracle, MySQL and PostgreSQL as well. He is also one of the leading posters at and a moderator at His T-sql blog is at



0 Responses to "SQL Server: Handling Divide By Zero Error"

Copyright © 2009-2014 All Rights Reserved for by Suprotim Agarwal | Terms and Conditions