I just had a trivial but genuine use for NULLIF(), for the first time in my career in SQL. Is this a widely used tool that I just ignored, or an almost forgotten SQL quirk? It is present in all major database implementations.
If someone needs an updater, NULLIF(A, B)returns the first value, if it is not equal to the second, in which case it returns NULL. This is equivalent to this expression CASE:
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 have found is to exclude a specific value from an aggregate function:
SELECT COUNT(NULLIF(Comment, 'Downvoted'))
This has a limitation that allows only to skip one value; a CASE, but more verbose, will allow you to use an expression.
For the record, I found this to suppress the value of the "last change" column if it was equal to the first change:
SELECT Record, FirstChange, NULLIF(LatestChange, FirstChange) AS LatestChange
It was only useful in that it reduced visual clutter for consumers.
user565869
source
share