Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres not returning rows where value is NULL when !=

Tags:

sql

postgresql

I see a thread here: Why does PostgreSQL not return null values when the condition is <> true with answers explaining why it happens but I'm still not sure how to fix it.

I'm running a query similar to this:

SELECT * FROM beers WHERE name != 'Budlight';

I expect it to return rows where name is not equal to Budlight. The results should include rows where name is NULL. Instead my results shows rows where name is not Budlight or NULL.

How can I form the query where only rows where name is not Budlight are ommitted from results?

SQLFiddle: http://www.sqlfiddle.com/#!15/7b9bd/1

like image 271
Zaki Aziz Avatar asked Oct 25 '25 06:10

Zaki Aziz


2 Answers

Postgres offers the is distinct from operator. You can do:

SELECT *
FROM beers
WHERE name IS DISTINCT FROM 'Budlight';

This does what you expect with NULL values.

This operator is explained in the documentation.

like image 115
Gordon Linoff Avatar answered Oct 26 '25 20:10

Gordon Linoff


The SQL-standard way is just to say OR col IS NULL, e.g.

SELECT * FROM beers WHERE name <> 'Budlight' OR name IS NULL;

Gordon's answer points out IS DISTINCT FROM a non-sql-standard way of saying that. Note that PostgreSQL may not use indexes effectively for IS DISTINCT FROM so I tend to only use it in triggers comparing scalars, and use col <> 'something' OR col IS NULL the rest of the time.

like image 20
Craig Ringer Avatar answered Oct 26 '25 21:10

Craig Ringer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!