Home > SQL Challenge > A handy but little-known SQL function: NULLIF()

A handy but little-known SQL function: NULLIF()

We are all familiar with the ISNULL and COALESCE functions.

Considering this where we want string1 if it’s not null, otherwise we want string2:

COALESCE (string1, string2) as myString

But what if string1 is an empty string, in which case displaying string1 is not what we want. Here is NULLIF function comes into play. NULLIF ensures that empty strings are always returned as NULLS.

So we can modify the above as this without using CASE:

COALESCE (NULLIF(string1, ‘’), string2) as myString

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.

Categories: SQL Challenge
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: