Search code examples
postgresqlsql-null

In Postgres, field != 'N' fails to include NULL value


We have a case in Postgres where

where p.is_ready_for_submission != 'N'

is failing to include NULL as a satisfying value for this condition. The column is_ready_for_submission can be NULL, Y, N. The purpose of the statement above is to include NULL and Y. But the NULLs are not included (they were in Oracle).

The only way to achieve this was to re-write as

(p.is_ready_for_submission is null or p.is_ready_for_submission = 'Y')

Is this special to Postgres? Note: this happens with both != and <>.


Solution

  • No, this isn't specific to Postgres, it's the same in Oracle (online example a, online example b). A != or <> expression where one of the operands is NULL will evaluate to NULL, and this will be considered falsy in the WHERE clause.

    To include NULL values in your results, you can use the SQL-1999 standard

    p.is_ready_for_submission IS DISTINCT FROM 'n'
    

    which will not propagate NULL values but consider them as distinct values.

    Unfortunately, it's not supported in Oracle, various alternatives exist (like the one in your question).