Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Microsoft SQL: CASE WHEN vs ISNULL/NULLIF

Besides readability is there any significant benifit to using a CASE WHEN statement vs ISNULL/NULLIF when guarding against a divide by 0 error in SQL?

CASE WHEN (BeginningQuantity + BAdjustedQuantity)=0 THEN 0 
ELSE EndingQuantity/(BeginningQuantity + BAdjustedQuantity) END

vs

ISNULL((EndingQuantity)/NULLIF(BeginningQuantity + BAdjustedQuantity,0),0)
like image 829
Christopher Klein Avatar asked May 13 '09 13:05

Christopher Klein


People also ask

What is the difference between Isnull () and Nullif () function?

ISNULL( ) function replaces the Null value with placed value. The use of ISNULL ( ) function is very common in different situations such as changing the Null value to some value in Joins, in Select statement etc. NULLIF ( ) function returns us Null if two arguments passed to functions are equal.

Can you use Isnull with a case statement?

ISNULL() Function, COALESCE() Function And CASE Statement In our Table data, some columns contain null values. We can replace it using ISNULL() function , COALESCE() function, and CASE Statement.

Which is better coalesce or Isnull?

advantage that COALESCE has over ISNULL is that it supports more than two inputs, whereas ISNULL supports only two. Another advantage of COALESCE is that it's a standard function (namely, defined by the ISO/ANSI SQL standards), whereas ISNULL is T-SQL–specific.

Why Nullif is used in SQL?

NULLIF returns the first expression if the two expressions are not equal. If the expressions are equal, NULLIF returns a null value of the type of the first expression.


1 Answers

Remember that NULL is different from 0. So the two code snippets in the question can return different results for the same input.

For example, if BeginningQuantity is NULL, the first expression evaluates to NULL:

CASE WHEN (NULL + ?)=0 THEN 0 ELSE ?/(NULL + ?) END

Now (NULL + ?) equals NULL, and NULL=0 is false, so the ELSE clause is evaluated, giving ?/(NULL+?), which results in NULL. However, the second expression becomes:

ISNULL((?)/NULLIF(NULL + ?,0),0)

Here NULL+? becomes NULL, and because NULL is not equal to 0, the NULLIF returns the first expression, which is NULL. The outer ISNULL catches this and returns 0.

So, make up your mind: are you guarding against divison by zero, or divison by NULL? ;-)

like image 142
Andomar Avatar answered Nov 09 '22 15:11

Andomar