Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

testing inequality with columns that can be null

So, I asked a question this morning, which I did not phrase correctly, so I got a lot of responses as to why NULL compared to anything will give NULL/FALSE.

My actual question was, what is the time honored fashion in which db guys test inequalities for two columns that can both be NULL. My question is the exact opposite of this question.

The requirements are as follows, A and B are two columns:
a) if A and B are both NULL, they are equal, return FALSE
b) if A and B are both not NULL, then return A<>B
c) if either A or B are NULL, they are not equal, return TRUE

like image 660
rouble Avatar asked Dec 02 '09 20:12

rouble


1 Answers

Depending on the data type and possible values for the columns:

COALESCE(A, -1) <> COALESCE(B, -1)

The trick is finding a value (here I used -1) that will NEVER appear in your data.

The other way would be:

(A <> B) OR (A IS NOT NULL AND B IS NULL) OR (A IS NULL AND B IS NOT NULL)

This can be a problem depending on how your particular RDBMS handles NULLs. By the ANSI standard, this should give you what you want, but who follows standards anyway. :)

P.S. - I should also point out that using the COALESCE function may invalidate the use of indexes in comparing the columns. Check your query plan and performance of the query to see if that's a problem.

P.P.S. - I just noticed that OMG Ponies mentioned that Informix doesn't support COALESCE. It's an ANSI standard function I believe, but see what I said above about standards...

like image 137
Tom H Avatar answered Oct 22 '22 17:10

Tom H