Search code examples
sqldatabasepostgresqlnullcomparison-operators

Not equal and null in Postgres


How I can filter SQL results with != in PostgreSQL SQL query? Example

SELECT * FROM "A" WHERE "B" != 'C'

Working. But it's also filtered all record where "B" IS NULL. When I changed query to:

SELECT * FROM "A" WHERE "B" != 'C' OR "B" IS NULL

I'm got right result. O_o. Always, when I need using != I need also check OR "field" IS NULL? Really?

It's uncomfortable in Sequelize: { B: { $or: [null, { $not: 'C' }] } }, instead: { B: { $not: 'C' } } :(


Solution

  • You can use the "null safe" operator is distinct from instead of <>

    SELECT * 
    FROM "A" 
    WHERE "B" is distinct from 'C'
    

    http://www.postgresql.org/docs/current/static/functions-comparison.html


    You should also avoid quoted identifiers. They are much more trouble then they are worth it