Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does MySQL ignore null values when looking for not equal?

Tags:

null

mysql

I am noticing something weird in MySQL and I would like to see why it behaves this way and of there a way to change it?

Scenario

I have accounts InnoDB table with the following columns id, name, type where the type is a null-able.

Now, lets say I have 10 records where the type = "TEST" and 100 records with they type IS NULL and 20 records where the type = "STANDARD"

If I run this query

SELECT * FROM accounts WHERE type <> "TEST"

This query will only show me the the 20 records that have type = "STANDARD" only and it ignores the 100 records that have a null value.

To work around this I would have to do something like this

SELECT * FROM accounts WHERE IFNULL(type,"") <> "TEST"

OR

SELECT * FROM accounts WHERE (type <> "TEST" OR type IS NULL)

NULL value means blank "aka no value" and no value means <> "TEST"

It is probably an expected behavior but I am not sure why is it designed like so

like image 601
Jaylen Avatar asked Nov 04 '14 18:11

Jaylen


People also ask

Why do we use not null in MySQL?

The NOT NULL constraint enforces a column to NOT accept NULL values. This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record without adding a value to this field.

What ignores NULL values in SQL?

The first query ignores NULL values in the capacity column when they are the first value in the window frame (defined as 1 preceding and 1 following ). The only time NULL is returned for the FIRST_VALUE function in this case is when the frame consists of three consecutive rows with NULL capacity values.

How do I avoid NULL values in select query?

SELECT column_names FROM table_name WHERE column_name IS NOT NULL; Query: SELECT * FROM Student WHERE Name IS NOT NULL AND Department IS NOT NULL AND Roll_No IS NOT NULL; To exclude the null values from all the columns we used AND operator.


2 Answers

SELECT * FROM accounts WHERE type <> "TEST"

The meaning of this statement would be,

"Select the rows from accounts where the value of column type is not equal to 'TEST' ".

Which means mysql returns the records having a value in type which is not equal to "TEST".
Now here, since NULL means there is no value, it does not return those records which does not have any value for type column.

like image 62
Venkata Krishna Avatar answered Oct 17 '22 19:10

Venkata Krishna


NULL means "the value cannot be known/is not known": which is different to "no value" - a comparison cannot be carried out at all against an unavailable value.

like image 36
davek Avatar answered Oct 17 '22 20:10

davek