testing inequality with columns that can be null

后端 未结 8 1147
不思量自难忘°
不思量自难忘° 2021-02-05 14:48

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 q

8条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-05 15:43

    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...

提交回复
热议问题