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

后端 未结 3 1686
遥遥无期
遥遥无期 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.

提交回复
热议问题