Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why will mySQL not return a row with a null value when selecting != to a string

Tags:

mysql

I have a table with a nullable varchar column. When selecting rows and specifying that I want rows with a value not equal to a given string, it does NOT return the rows where the value is null.

For example:

## if `value` is null, that row is ignored
SELECT * FROM test_table WHERE value != 'some string'

I'd like to understand why that's happening.

Example: http://sqlfiddle.com/#!2/83f0d/1

like image 597
just.another.newbie Avatar asked Jan 14 '14 23:01

just.another.newbie


People also ask

How do I select NULL rows in MySQL?

To search for column values that are NULL , you cannot use an expr = NULL test. The following statement returns no rows, because expr = NULL is never true for any expression: mysql> SELECT * FROM my_table WHERE phone = NULL; To look for NULL values, you must use the IS NULL test.

Does MySQL return NULL?

If your select statement returns one column, but no rows, NULL will be returned.

What is the MySQL operator for returning true if a value is NULL?

ISNULL() function returns true if argument is a NULL value, while IFNULL() returns the first argument if it is non-null.


1 Answers

In ANSI SQL, NULL is neither equal to nor unequal to any value, including itself.

NULL = 'foo'
NULL != 'foo'
NULL = NULL
NULL != NULL

all evaluate to NULL. To test for nullness you must use is null or is not null in your query.

like image 68
dg99 Avatar answered Oct 06 '22 09:10

dg99