开发者

What applications are there for NULLIF()?

开发者 https://www.devze.com 2023-03-09 22:26 出处:网络
I just had a trivial but genuine use for NULLIF(), for the first time in my career in SQL.I开发者_开发百科s it a widely used tool I\'ve just ignored, or a nearly-forgotten quirk of SQL?It\'s present i

I just had a trivial but genuine use for NULLIF(), for the first time in my career in SQL. I开发者_开发百科s it a widely used tool I've just ignored, or a nearly-forgotten quirk of SQL? It's present in all major database implementations.

If anyone needs a refresher, NULLIF(A, B) returns the first value, unless it's equal to the second in which case it returns NULL. It is equivalent to this CASE statement:

CASE WHEN A <> B OR B IS NULL THEN A END

or, in C-style syntax:

A == B || A == null ? null : A

So far the only non-trivial example I've found is to exclude a specific value from an aggregate function:

SELECT COUNT(NULLIF(Comment, 'Downvoted'))

This has the limitation of only allowing one to skip a single value; a CASE, while more verbose, would let you use an expression.

For the record, the use I found was to suppress the value of a "most recent change" column if it was equal to the first change:

SELECT Record, FirstChange, NULLIF(LatestChange, FirstChange) AS LatestChange

This was useful only in that it reduced visual clutter for human consumers.


I rather think that

NULLIF(A, B)

is syntactic sugar for

CASE WHEN A = B THEN NULL ELSE A END

But you are correct: it is mere syntactic sugar to aid the human reader.


I often use it where I need to avoid the Division by Zero exception:

SELECT
  COALESCE(Expression1 / NULLIF(Expression2, 0), 0) AS Result
FROM …


Three years later, I found a material use for NULLIF: using NULLIF(Field, '') translates empty strings into NULL, for equivalence with Oracle's peculiar idea about what "NULL" represents.


NULLIF is handy when you're working with legacy data that contains a mixture of null values and empty strings.

Example:
SELECT(COALESCE(NULLIF(firstColumn, ''), secondColumn) FROM table WHERE this = that


SUM and COUNT have the behavior of turning nulls into zeros. I could see NULLIF being handy when you want to undo that behavior. If fact this came up in a recent answer I provided. If I had remembered NULLIF I probably would have written the following

SELECT student, 
       NULLIF(coursecount,0) as courseCount 
FROM   (SELECT cs.student, 
               COUNT(os.course) coursecount 
        FROM   @CURRENTSCHOOL cs 
               LEFT JOIN @OTHERSCHOOLS os 
                 ON cs.student = os.student 
                    AND cs.school <> os.school 
        GROUP  BY cs.student) t 
0

精彩评论

暂无评论...
验证码 换一张
取 消