Why is null<>null=null in mysql

后端 未结 2 525
情深已故
情深已故 2021-01-24 16:40

I am going through a tutorial for MySql, and I came through the following query.

mysql> select null <> null;
+--------------+
| null <> null |
+--         


        
相关标签:
2条回答
  • 2021-01-24 17:04

    Because any comparison operator over NULL appearing in in a sql filter should (and does) make the row not be selected.

    You should use null safe operator <=> to compare to column containing NULL values and other NOT NULL value but <=> will return 1 when both operands are NULL because NULL is never considered equal to NULL.

    This is an example of a situation where null safe operator is useful:

    You have a table:

    Phones
    ----
    Number
    CountryCode (can be NULL) 
    

    And you want to select all phone numbers not being from Spain (country code 34). The first try is usually:

    SELECT Number FROM Phones WHERE CountryCode <> 34;
    

    But you notice that there are phones with no country code (NULL value) not being listed and you want to include them in your result because they are nor from Spain:

    SELECT Number FROM Phones WHERE CountryCode <=> 34;
    
    0 讨论(0)
  • 2021-01-24 17:14
    select null <> null;
    

    Here <> is not null safe operator. It is Not equal operator. Refer official website of mysql.
    Null safe operator is <=>

    0 讨论(0)
提交回复
热议问题