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 »
10,640 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 »
10,640 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 »
10,640 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 »
9 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 »
10,640 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 »
10,640 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?



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
InVision App - Prototyping Made Beautiful With Prototyping Tools Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
Feb 12, 2012 at 3:37 AM
Learning ColdFusion 8: CFImage Part III - Watermarks And Transparency
Hi Ben, Just to ask currently it is placed bottom right corner, if i need to replace the same rendered image on the bottom left side or in the bottom center, how that can be calculated. bottom ce ... read »
Feb 11, 2012 at 9:29 PM
Use jQuery's SlideDown() With Fixed-Width Elements To Prevent Jumping
I can't say how glad I am that I found your post. Thank you very much. ... read »
Feb 10, 2012 at 7:21 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
Update! Instead of $(eval(options.insertAfter)).after(data['insertData']); I now use: var ajaxNode = document.createElement('span'); var parent = $(eval(options.insertAfter))[0].parentNode; ... read »
Feb 10, 2012 at 6:18 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
encountered this same, what I consider, jQuery bug last week. I'm building a site in which I load some content via AJAX. This content contains Linkedin share button placeholders which Linkedin API ne ... read »
Feb 10, 2012 at 11:30 AM
Cross-Origin Resource Sharing (CORS) AJAX Requests Between jQuery And Node.js
After you understand the concepts here, this is an awesome cheatsheet for enabling CORS in just about anything http://enable-cors.org/ ... read »
JM
Feb 10, 2012 at 9:10 AM
My Safari Browser SQLite Database Hello World Example
@Amy, Here is a very good tutorial on how to use JOIN: http://www.sqltutorial.org/sqljoin-innerjoin.aspx ... read »
Feb 10, 2012 at 4:42 AM
Building A Twitter-Inspired RESTful API Architecture In ColdFusion
This is great, very useful Ben. I spotted a small typo in the api.cgm listing: <cfthrow type="Unauthroized" /> Cheers Stefan ... read »
Feb 9, 2012 at 10:35 PM
CFDirectory Filtering Uses Pipe Character For Multiple Filters (Thanks Steve Withington)
I was wondering if there would be a filter you could apply so that you got everything but what you included in the filter. As in show me all docs that are not a .pdf. ... read »