Using NULLIF() To Prevent Divide-By-Zero Errors In SQL

Posted October 3, 2007 at 8:02 AM by Ben Nadel

Tags: SQL

Boyan Kostadinov just sent me a cool link to an article that is the final part in a four part series that discusses the SQL NULL value. I haven't read the first three parts yet, but there is a really cool tip in the fourth part on using NULLIF() to prevent divide-by-zero errors in a SQL call.

The idea here is that, as with any other form of math that I know of, you cannot divide by zero in a SQL call. Therefore, running this code:

  • <!--- Do SQL division with no error protection. --->
  • <cfquery name="qDivision" datasource="#REQUEST.DSN.Source#">
  • SELECT
  • ( 45 / 0 ) AS value
  • ;
  • </cfquery>

... results in a SQL error being thrown:

Error Executing Database Query. [Macromedia] [SQLServer JDBC Driver] [SQLServer] Divide by zero error encountered.

To prevent this sort of error from being thrown, author Hugo Kornelis suggests using a NULLIF() in the divisor of the equation. NULLIF() takes two arguments and returns NULL if the two values are the same and can be used to turn the divisor from a zero into a NULL which, in turn, will force the entire equation to become NULL. Therefore, running this code:

  • <!--- Do SQL division with divide-by-zero protection. --->
  • <cfquery name="qDivision" datasource="#REQUEST.DSN.Source#">
  • SELECT
  • ( 45 / NULLIF( 0, 0 ) ) AS value
  • ;
  • </cfquery>
  •  
  • <!--- Output resulting value. --->
  • [ #qDivision.value# ]

... we get the following output:

[ ]

Here, the NULLIF( 0, 0 ) returns NULL since zero is equal to zero, which gets the SQL statement to return NULL, which gets ColdFusion to show an empty string. This is a seemingly pointless example since both zero values are hard coded, but imagine if this were a user-entered value, or even better yet, a SQL aggregate or other calculated value (such as might be used in a report or data mining exercise).

Now, let's say you want to take this one step further and provide a default value for the equation if NULL is encountered (A default value, though not entirely accurate might make your consuming code more compact as it won't have to deal with exception cases). To set a default value, we could use the ISNULL() or COALESCE() functions:

  • <!---
  • Do SQL division with divide-by-zero protection. But this,
  • time, let's provide a default value if the division is
  • not valid.
  • --->
  • <cfquery name="qDivision" datasource="#REQUEST.DSN.Source#">
  • SELECT
  • (
  • ISNULL(
  • (45 / NULLIF( 0, 0 )),
  • 0
  • )
  • ) AS value
  • ;
  • </cfquery>
  •  
  • <!--- Output resulting value. --->
  • [ #qDivision.value# ]

Here, we are performing the division as we were above, but then, if that equation returns NULL, our ISNULL() function is going to catch that and return zero as its default value. Therefore, running the above code, we get the following output:

[ 0 ]

As someone who runs a ton of reports on database table (albeit, not in any educated way), this is going to come in very handy. I find that in most cases, having a zero is graphically equivalent to NULL and a whole lot easier to deal with.



Reader Comments

Oct 3, 2007 at 9:52 AM // reply »
54 Comments

Niiiiiiiiiiiice!

I've had this problem in strange statistics data for a long time and its always been a little bit tricky to over come, this is a nice solution, and its all done in SQL too.

In the past I've pulled the math out of SQL and had CF do it as I had more control over the devision by zero, this makes a hell of a lot more sense.

Nice, Ben!

Thanks,

Rob


Oct 3, 2007 at 10:06 AM // reply »
11,238 Comments

@Rob,

Yeah, I feel your pain. I used to use CASE statements in the divisor. It worked, but it was just wordy and distracting. I find this to be much more straight forward and readable.


Oct 3, 2007 at 3:14 PM // reply »
2 Comments

Is this function specific to SQL Server or will it work on other databases as well? (Oracle, MySQL, etc.)


Oct 3, 2007 at 3:29 PM // reply »
11,238 Comments

@Chad,

I think NULLIF() is standard. Not sure about ISNULL(). I think COALESCE() is more standard than ISNULL().


Oct 3, 2007 at 10:45 PM // reply »
48 Comments

Excellent find! Wish I would have known about this a long time ago - I've always just used a case statement:

case
when isNull(divisor, 0) = 0
then 0
else numerator/divisor end as value

But this seems much nicer!


Mar 25, 2009 at 7:30 AM // reply »
1 Comments

How about speed between case n nullif


Mar 25, 2009 at 4:43 PM // reply »
11,238 Comments

@Ivan,

I would guess that CASE would be faster only because it is inline rather than a method call. But, just a guess.


May 13, 2009 at 11:38 AM // reply »
1 Comments

Could not be easier. Thanks a lot !!


Oct 8, 2009 at 3:28 PM // reply »
10 Comments

For Oracle, you might try something like this: columnname1/decode(columnname2,0,null)


Jan 22, 2010 at 10:54 AM // reply »
1 Comments

Thanks!!! This helped with a very tough calculation. Wasn't even aware this function was out there.


May 2, 2010 at 1:36 AM // reply »
1 Comments

Hi,

Excellent find!

Using this I soved my problem. For e.g
sum(objid)/nullif(count(units_purch),0)

where count(units_purch) return 0 value.

However I've one question can I solve this problem using CASE statement. If yes, then how?

Thanks in advance!

Regards,
Aakansha


May 3, 2010 at 9:08 AM // reply »
11,238 Comments

@Aakansha,

Yeah, the nullif() is really just a short hand for the CASE statement. CASE statements are powerful and can be used just about anywhere:

SUM( objid ) / (
CASE
WHEN COUNT( units_purch ) = 0
THEN NULL
ELSE COUNT( units_purch )
END
)

As you can see, NULLIF() is a lot easier (and prevents you from having to calculate count() twice.


May 5, 2010 at 2:02 PM // reply »
1 Comments

I just updated my script with this code and it worked like a clock. This will save me gobs of time plus keep my code less complicated. Thanks a million! Rock On!


May 7, 2010 at 1:14 PM // reply »
18 Comments

VERY late to the party here, but I had occasion to work on a Divide By Zero error today, and came across your post.

With MSSQL (2005 anyway) you can add these two lines ahead of the query that could potentially fail with a DBZ error:

SET ARITHABORT OFF
SET ANSI_WARNINGS OFF

With both ARITHABORT and ANSI_WARNINGS set to OFF, SQL Server will return a NULL value in a calculation involving a divide-by-zero error. To return a 0 value instead of a NULL value, you could still put the division operation inside the ISNULL function:

SET ARITHABORT OFF
SET ANSI_WARNINGS OFF

SELECT ISNULL([Numerator] / [Denominator], 0)

Just one more way to skin the cat. I would assume one would want to use this solution with care, especially when dealing with multiple queries in one request... experimentation is certainly in order.

HTH

Marc


May 7, 2010 at 9:15 PM // reply »
11,238 Comments

@Marc,

Oh cool. I feel like with every SQL server release, they're just adding more cool stuff. I've been using MySQL a lot lately and there's even more stuff in there than I realize. I keep meaning to just read through the docs.


Jun 28, 2010 at 8:19 PM // reply »
1 Comments

excellent tip!

thanks


Jan 27, 2011 at 9:36 AM // reply »
1 Comments

you're my hero! goodbye forever, stupid ugly CASE method


Mar 15, 2011 at 6:53 AM // reply »
1 Comments

thanks a ton


Mar 25, 2011 at 9:35 AM // reply »
1 Comments

Watch it. NULLIF in SQL SERVER 2000 is buggy!

SELECT ISNULL(NULLIF('', ''), 6)
gives: *

SELECT ISNULL(NULLIF('', ''), 'abc')
gives: empty string


May 2, 2011 at 2:26 AM // reply »
1 Comments

thanks for all good notes


JT
Oct 4, 2011 at 5:09 AM // reply »
1 Comments

Thanks for this, over the last couple of years I find myself coming back to this page to look at how to avoid this problem.


Dec 27, 2011 at 3:18 PM // reply »
1 Comments

I'm attempting to use this feature when calculating the average for a value, but I'm not certain if my syntax is correct as CF throws an error:

avg (isNull((((docunitprice * orderqty)-((c.avglaborcost + c.avgburdencost + c.avgmaterialcost + c.avgsubcontcost + c.avgmtlburcost)*d.orderqty))/ nullif(docunitprice * orderqty),0))) as PercValueAdd

Does this work within a function?


Apr 14, 2012 at 2:22 PM // reply »
1 Comments

hi.. I am facing a problem. I have a online form. when I fill this form and submit. my form submited well without any error. but when I went to the C-Panel for to check and Grab out this form data. I am finding values 0,0,0,0 in all fields.for example.
I have 6 fields created in my form.
1 NAME 2.CITY NAME 3.E-mail id 4.Contact No 5.Pass and 6.Comments Area in my form. but when I go the C-panel for to get out the data from above field after completing form. I received values 0,0,0,0,0, in all fields. please help me out.


Apr 19, 2012 at 12:31 PM // reply »
1 Comments

You, sir, RULE!

This has been bugging me for soo long! A full hour of crunching stopped becuase of a 0 on a single row..

Excellent solution!


Jul 30, 2012 at 7:38 AM // reply »
1 Comments

Nice! I was looking for a solution solving divide by zero problem without using case (the query was already too complex) and this is THE solution!


AKE
Sep 25, 2012 at 2:38 PM // reply »
1 Comments

Nice article and useful tip.

However, slightly concerned about your concluding remark: ...in most cases, having a zero is graphically equivalent to NULL and a whole lot easier to deal with.

In general, it is statistical best practice to distinguish between zeros and nulls because very often they mean two very different things. Consider a situation in which 0 is bad and non-zero is good. Management is interested in the percentage of zeros out of the total number of cases. Typically, no one thinks to specify that nulls should be excluded. But encountering the nulls prompts the question. By automatically letting 0 be the default for nulls you are introducing potentially quite significant bias into your data sets.

So, without labouring the point, I recommend that you reconsider this last line, if only to remove it from an article that others might model their own data processing behaviour on.

Best Regards,
AKE


Sep 27, 2012 at 5:41 AM // reply »
1 Comments

Hi, I have a problem, the query below gives me zero value. please help.

ISNULL(table/NULLIF((table),0),0)*100


Oct 21, 2012 at 3:29 AM // reply »
1 Comments

Addendum:

In case when divisor could be NULL it's important to NVL it to ZERO. At least Oracle's implementation of NULLIF doesn't accept NULL value as valid parameter and returns error message about it.

So, in complete form it looks like:

nullif(nvl(divisor,0),0)

NVL will change NULL on 0 and NULLIF will change all zeroes to NULL without failures.


Apr 30, 2013 at 4:37 PM // reply »
1 Comments

bennadel.com saves me again!


May 1, 2013 at 11:52 AM // reply »
1 Comments

Well done. Thank you.



Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
May 22, 2013 at 12:44 PM
Ask Ben: Query Loop Inside CFScript Tags
In cf10, if you call a function that has: local.result = {}; local.result.msg = ""; local.svc = new query(); local.svc.setSQL("SELECT * FROM..."); local.obj = local.svc.exe ... read »
May 22, 2013 at 12:29 PM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@Ben: What version of Java are you using? Also, did you test users.id to see what Java reports as the data type? I wonder if it's not a Java primitive data type, but getting returned as something ... read »
May 22, 2013 at 11:47 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@Dana, Awesome - so it looks like this bug was fixed in ColdFusion 10. Thanks so much for double-checking that. ... read »
May 22, 2013 at 11:37 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
When I c&p and run on cf10, I get: Selected User IDs: 1,4 User 1 selected: YES - YES User 2 selected: NO - NO User 3 selected: NO - NO User 4 selected: YES - YES User 5 selected: NO - ... read »
May 22, 2013 at 11:27 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@Tom, Good thought, but no dice. Both of these still exhibit the same behavior: users.id[ users.currentRow ] users[ "id" ][ users.currentRow ] It's just something whacky happening with ... read »
May 22, 2013 at 11:07 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
Could your problem be that "users.id" is actually an ARRAY, not a single value? Perhaps try it again with "users.id[1]" (I only have CF8 here at work). ... read »
May 22, 2013 at 7:52 AM
Nested Views, Routing, And Deep Linking With AngularJS
Hi, Just a quick thank you. As it happens, for my own purposes, the pending ui-router work being done in native angular is likely the one I'll adopt, but your exploration, code and documentation of ... read »
May 22, 2013 at 4:43 AM
How Do You Use The ColdFusion CFParam Tag?
'<cfparam>' or 'isDefined()and <cfset>' performs the same task.Is there any difference? ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools