NULL values in where clause

后端 未结 6 673
花落未央
花落未央 2020-12-11 02:17

i\'ve got a table \"bla\" like this:

[id]    [name]    [fk]
1       test      4
2       foo       5
3       bar       NULL

if i do the sql

相关标签:
6条回答
  • 2020-12-11 02:52

    NULL doesn't compare equal to anything. You'll need to accept nulls explicitly:

    where fk <> 4 or fk is null;
    

    See Working with NULL for more information about NULL handling.

    0 讨论(0)
  • 2020-12-11 02:53

    NULL is special in that it represents an "unknown" value. This can't be compared to numbers (or any other value for that matter), hence the result -

    Is NULL <> 4? The answer is - don't know. Is 4 different from an unknown value?

    Try this instead:

    SELECT * FROM bla WHERE fk <> 4 OR FK IS NULL
    
    0 讨论(0)
  • 2020-12-11 03:01

    How about

    SELECT * FROM bla WHERE NOT (fk = 4)
    

    Logic:

    NULL = 4 --false
    5 = 4    --false
    4 = 4    --true
    
    NOT (NULL = 4) --true
    NOT (5 = 4)    --true
    NOT (4 = 4)    --false
    
    0 讨论(0)
  • 2020-12-11 03:04

    Because NULL stands for UNKNOWN, and when you compare a value with UNKNOWN, the result will always be false.

    Take a look at this comparisons -

    NULL = NULL    -- false, since both are unknown, so the truth value of this expression can't be determined.
    NULL = 4       -- false
    4 = 4          -- true, since both values are known.
    

    If you want to fetch the records containing NULL, you need to re-write your query this way -

    where fk <> 4
    OR fk is null;
    

    For more information, see Wikipedia.

    0 讨论(0)
  • 2020-12-11 03:05

    Following statement should help:

    SELECT * FROM bla WHERE COALESCE(fk,0) <> 4

    0 讨论(0)
  • 2020-12-11 03:08

    NULL is not a value, but rather the unknown absence of a value. If you'd like to test for NULL, you have to do so explicitly by using IS NULL and IS NOT NULL. For example, NULL will test FALSE even against NULL itself. So, working with NULL is only done with the aforementioned functions (and ISNULL()). Your query could be rewritten as

    SELECT * FROM bla WHERE fk <> 4 OR fk IS NULL
    
    0 讨论(0)
提交回复
热议问题