Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL not displaying null values on a not equals query?

Tags:

sql

null

oracle

This is just a question out of curiosity but I am looking at a database and pulling data from a table with a query on one of the columns. The column has four possible values null, 0, 1, 2. When I run the query as:

SELECT * FROM STATUS WHERE STATE != '1' AND STATE != '2'; 

I get the same results as running:

SELECT * FROM STATUS WHERE STATE = '0'; 

I.e. rows with a null value in the top command in the queried column seem to be omitted from the results, does this always happen in SQL?

I'm running my commands through Oracle SQL Developer.

like image 472
Alexei Blue Avatar asked Nov 07 '11 12:11

Alexei Blue


People also ask

IS NOT NULL equal to != In SQL?

In SQL null is not equal ( = ) to anything—not even to another null . According to the three-valued logic of SQL, the result of null = null is not true but unknown. SQL has the is [not] null predicate to test if a particular value is null .

Is != And <> the same in SQL?

Here is the answer – Technically there is no difference between != and <>. Both of them work the same way and there is absolutely no difference in terms of performance or result.

Why NULL does not work in SQL?

NULL can be assigned, but using ' = NULL ', ' <> NULL ', or any other comparison operator, in an expression with NULL as a value, is illegal in SQL and should trigger an error. It can never be correct. The expression will always return NULL .


2 Answers

In several languages NULL is handled differently: Most people know about two-valued logic where true and false are the only comparable values in boolean expressions (even is false is defined as 0 and true as anything else).

In Standard SQL you have to think about three-valued logic. NULL is not treated as a real value, you could rather call it "unknown". So if the value is unknown it is not clear if in your case state is 0, 1, or anything else. So NULL != 1 results to NULL again.

This concludes that whereever you filter something that may be NULL, you have to treat NULL values by yourself. Note that the syntax is different as well: NULL values can only be compare with x IS NULL instead of x = NULL. See Wikipedia for a truth table showing the results of logic operations.

like image 88
Alex Avatar answered Sep 17 '22 13:09

Alex


Yest it's normal, you can maybe put a database settings to fixed that

But you could modify your code and do something like that :

SELECT * FROM STATUS WHERE STATE != '1' OR STATE != '2' or STATE is null; 

Look at this for more info : http://www.w3schools.com/sql/sql_null_values.asp

like image 44
GregM Avatar answered Sep 17 '22 13:09

GregM