Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not equal and null in Postgres

Tags:

postgresql

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' } } :(

like image 327
faiwer Avatar asked Apr 08 '16 20:04

faiwer


People also ask

What is not equal in Postgres?

Note. <> is the standard SQL notation for “not equal”. !=

What does <> mean in PostgreSQL?

<> is the standard SQL operator meaning "not equal". Many databases, including postgresql, supports != as a synonym for <> . They're exactly the same in postgresql.

How do I check for null in PostgreSQL?

Example - With SELECT StatementSELECT * FROM employees WHERE first_number IS NULL; This PostgreSQL IS NULL example will return all records from the employees table where the first_name contains a NULL value.

Is null or empty Postgres?

Oracle reads empty strings as NULLs, while PostgreSQL treats them as empty. Concatenating NULL values with non-NULL characters results in that character in Oracle, but NULL in PostgreSQL. Oracle and PostgreSQL behave similarly in many cases, but one way they differ is in their treatment of NULLs and empty strings.


1 Answers

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

like image 156
a_horse_with_no_name Avatar answered Oct 11 '22 14:10

a_horse_with_no_name