Nulls can be evil

Nulls can produce weird results when used with comparison operators. Few days back, I was debugging a query like the one below.

Select ....,
  Case When myColumn = 'SomeValue1' Then 'True' Else 'False' End As CaseOutput1,
  Case When myColumn = 'SomeValue2' Then 'True' Else 'False' End As CaseOutput2,
  Case When myColumn != 'SomeValue1' and myColumn != 'SomeValue2' 
    Then 'True' Else 'False' End As CaseOutput3,
...

Looking at the case statements, we can infer that at least one of the case statements will always output a True, but this was not the case. After much effort, I found that myColumn resulted in null due to a left join and so all the case statements evaluated to False. Getting to the cause of problem wasn’t an easy task since the query was quite complex with multiple joins and several case statements.

Advertisements

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: