Why does PostgreSQL not return null values when the condition is <> true

后端 未结 3 1680
遥遥无期
遥遥无期 2020-12-16 11:53

I was confused behind the reasoning of the following:

SELECT * FROM table WHERE avalue is null

Returns x number of rows where \'avalue\' is

相关标签:
3条回答
  • 2020-12-16 12:15

    Every halfway decent RDBMS does it the same way, because it's correct.
    I am quoting the Postgres manual here:

    Ordinary comparison operators yield null (signifying "unknown"), not true or false, when either input is null. For example, 7 = NULL yields null, as does 7 <> NULL. When this behavior is not suitable, use the IS [ NOT ] DISTINCT FROM constructs:

    expression IS DISTINCT FROM expression
    expression IS NOT DISTINCT FROM expression
    

    Note that these expressions perform a bit slower than simple expression <> expression comparison.

    For boolean values there is also the simpler IS NOT [TRUE | FALSE].
    To get what you expected in your second query, write:

    SELECT * FROM table WHERE avalue IS NOT TRUE;

    SQL Fiddle.

    0 讨论(0)
  • 2020-12-16 12:19

    It is normal. SQL Server does it in the same way. In SQL Server you can use

    SELECT * FROM table WHERE ISNULL(avalue, 0) <> 1
    

    For postgresql equivalent watch this: What is the PostgreSQL equivalent for ISNULL()

    Consider to use NOT NULL column specification with default value, if it makes sense.

    EDIT:

    I think it is logic. NULL is not a value, so it is excluded from searching - you have to specify it explicitly. If SQL designers decides to go by second way (include nulls automatically), then you would get more troubles if you need to recognize no values

    0 讨论(0)
  • 2020-12-16 12:28

    This link provides a useful insight. Effectively as @Damien_The_Unbeliever points out, it uses Three-valued logic and seems to be (according to the article) the subject of debate.

    A couple of other good links can be found here and here.

    I think it boils down to null not being a value, but a place holder for a value and a decision had to be made and this was it... so NULL is not equal to any value because it isn't a value and won't even not be equal to any value.... if that makes sense.

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