Why does "WHERE text != "something" also exclude all rows with NULL values? - mysql

Sorry, this is probably a really frequent question, but I really don't know how to phrase a google search that finds it.
SELECT * FROM table where textfield != "Word";
This ignores all rows where the textfield has the string "Word" - but it also ignores all rows where textfield is NULL. Why?
What is the correct way of selecting ALL rows (even NULLS), except rows with a specific string in a text field?

Almost all comparisons with NULL return NULL (the most common excepts are IS NULL and IS NOT NULL). And in WHERE clauses, NULL is treated the same as "false" -- that is, the rows are filtered.
MySQL offers a NULL-safe comparison operator. You can use:
where not textfield <=> 'Word'
<=> returns true or false -- never NULL -- so it does what you expect.
Let me add: The SQL Standard has a NULL-safe operator. So, in Standard SQL, this would be:
where textfield is distinct from 'Word'
However, not many databases support the standard syntax -- yet.

You need to tell the database to include the rows where textfield is NULL:
SELECT *
FROM table
WHERE textfield != 'Word' OR
textfield IS NULL
In a relational database any direct comparison to NULL (using comparison operators such as =, <> or !=, <, >, <=, or >=) will return NULL or UNKNOWN (depending on the database). This is intentional and by design - but it does make it a bit awkward sometimes. If you want NULLs included you need to specify that.
In some databases you can use the NVL or COALESCE functions to provide a "default value" to replace NULLs with, as in:
SELECT *
FROM table
WHERE NVL(textfield, 'X') != 'Word'
or
SELECT *
FROM table
WHERE COALESCE(textfield, 'X') != 'Word'
COALESCE is the ANSI version, allows multiple arguments, and is the preferred solution. For example, if you want to return textfield, but if was NULL you wanted to return text2, and then if text2 was also NULL you wanted to return X you could use
SELECT *
FROM table
WHERE COALESCE(textfield, text2, 'X') != 'Word'

Related

Selecting rows with null in integer columns using mysql query

I have a table named 'datatablecoulmn' with the following columns.
now i want all rows where the column FkID is NULL.FkID is an integer field
i tried the following queries
SELECT * FROM `datatablecoulmn` WHERE `FkID`=NULL
SELECT * FROM `datatablecoulmn` WHERE `FkID`<1
SELECT * FROM `datatablecoulmn` WHERE `FkID`='null'
All of these returns empty rows .Any help?
In MySQL, NULL is considered as a 'missing, unknown value', as opposed to no value. Any arithmetic comparison with NULL does not return true or false, but returns NULL instead., So, NULL != 'C' returns NULL, as opposed to returning true.
Use IS NULL condition in your query and try like this
SELECT * FROM `datatablecoulmn` WHERE `FkID` IS NULL
For handling NULL values MySQL provides three operators
IS NULL: operator returns true if column value is NULL.
IS NOT NULL: operator returns true if column value is not NULL.
<=>: operator compares values, which (unlike the = operator) is true
even for two NULL values.
You can refer to these links for more
Link 1,Link 2,Link 3
You can't compare with NULL. So you gotta check for YourColumn IS NULL (or maybe YourColumn IS NOT NULL.
NULL is a value like infinity is a number. In other words, not at all. NULL is the absence of certain information.
For the same reason that NaN (not a number) in IEEE754 floating point is not equal to other instances (or even the same instance) of NaN, nothing in SQL is equal to NULL, including NULL.
That's something that may sound strange but, when you think of the purpose of NULL, that of specifying unknown or inappropriate values, it makes sense.
In order to see if a value is NULL, you have to therefore use something like:
where COLUMN_NAME is null
More details on working with NULL in MySQL can be found here.
Use something like:
SELECT * FROM `datatablecoulmn` WHERE `FkID` is NULL
NULL is a placeholder to say there is the absence of a value. Which is why you can only use IS NULL/IS NOT NULL as predicates for such situations and not = or != or <> which is used by values.
Here is another way to exclude the records with FkID is NOT NULL:
SELECT D1.*
FROM datatablecoulmn D1
WHERE NOT EXISTS (SELECT D2.*
FROM datatablecoulmn D2
WHERE D2.`FkID` IS NOT NULL)

MySQL: Why can't I "column_name not in (null, 'foo')"?

I was writing a simple MySQL query along these lines today:
SELECT * FROM table_name WHERE column_name IS NOT NULL and column_name !='foo';
This returned the expected number of results. But I didn't love the syntax, and tried to make it more elegant:
SELECT * FROM table_name WHERE column_name NOT IN (NULL, 'foo');
Of course, that returned 0 results.
My question is this: Can you explain why a null value would not be in (NULL, 'bar')? I think it's because you can't compare NULL with NULL, at least philosophically. But why not?
Consider this:
# ruby
nil == nil
# => true
/* JavaScript */
undefined === undefined
// true
In those languages, and nil or undefined value is equal to any other nil or undefined value. Why not in SQL?
(Bonus points about close-to-the-metal implementation details of SQL, or philosophical differences in languages?)
In SQL, direct comparisons with NULL are neither true nor false, so the IN clause will not work. This is a fundamental feature1 of the ISO SQL standard.
See this Wikipedia entry:
Since Null is not a member of any data domain, it is not considered a "value", but rather a marker (or placeholder) indicating the absence of value. Because of this, comparisons with Null can never result in either True or False, but always in a third logical result, Unknown.
In this way, the concept of NULL in SQL is very different from Ruby's nil, or JavaScript's undefined. Ruby's nil is a 'value', so nil == nil is true. However, SQL's NULL is not a 'value', so NULL = NULL is unknown (but so is NULL <> NULL). For this reason, SQL provides a different operator for comparing NULL's—NULL IS NULL is true.
1: Some may disagree that this is in fact a feature.
The database structural query language SQL implements Three Valued Logic as a means of handling comparisons with NULL field content.
True
False
Unknown
The original intent of NULL in SQL was to represent missing data in a database, i.e. the assumption that an actual value exists, but that the value is not currently recorded in the database.
So comparison with UNKNOWN value gives indeterministic result which is evalauted to FALSE.
Can you explain why a null value would not be in (NULL, 'bar')?
Necause SQL NULLs are not equal to other NULLs. That's the way the SQL NULLs are defined, because the language uses three-value logic (3VL) *. In essence, NULL means "unknown", so all comparisons to it result in the unknown result - i.e. NULL. For example, the result of column_name = NULL is NULL, not false. This is the reason behind the introduction of IS NULL and IS NOT NULL operators into the SQL language.
Your first solution is correct. You could also use a less straightforward solution that converts NULLs to 'foo' before comparison, but the expression that results from this conversion requires more thinking to understand:
WHERE IFNULL(column_name, 'foo') != 'foo'
* The behavior of NULLs in SQL, especially the difference between the way they are treated during aggregation, has been a subject of a controversy. Several suggestions were made at how to "fix" this behavior, but none of them got widespread adoption because of their complexity.
In SQL, NULLs are not equal to other NULLs.
If I don't tell you my age, and you don't tell me your age, do we therefore have the same age?
No, we can't say that's a true predicate. We simply don't have enough information to say one way or the other. It's not exactly FALSE, but it's not definitely TRUE either.
Both column_name = NULL and column_name != NULL are UNKNOWN in SQL, and conditions are satisfied only of they are actually TRUE.
column_name IN (NULL, 'foo') is logically the same as (column_name = NULL) OR (column_name = 'foo').
Likewise, column_name NOT IN (NULL, 'foo') is logically the same as NOT ((column_name = NULL) OR (column_name = 'foo')), or (column_name != NULL) AND (column_name != 'foo').
Either way, the same rules about NULL comparisons apply.
It might be convenient if SQL were to automatically convert that to (column_name IS NULL) OR (column_name = 'foo') but that's not the way the language is standardly defined, for better or for worse.
IN Clause expects a value, a NULL is not a value. So You really have to put the OR with the null to get the desired result.
MySQL manual has a good read with this.
--EDIT--
To answer your comment let's compare NULL and a ZERO.
Zero is a value. It is the unique, known quantity of zero, which is used meaningfully in arithmetic/math. We can do things with zero.
Null on the other hand is a non-value, it's just a placeholder for a data value which is unknown or in other word not specified. Math can't be performed on NULL. Undefined is the other term of NULL. NULL doesn't exist so we can't do anything with it.
Null is not zero, null is not "" (empty string). Null is just a representation of an unknown piece of data.
I hope it's now clear. :)

trying to test that a field <> value with null values in mysql

I have a column that has null values as well as other values such as 'deactivated'. I am trying to build a query that says "WHERE field <> 'deactivated" but it returns an empty result set. From my research it seems to be because it can't compare to the null values. But I haven't been able to figure out how to get around it.
Thanks
As it seems that you want nulls included in the result set, the correct condition would be
WHERE field <> 'deactivated' OR field IS NULL
Try looking for NULL specifically:
WHERE field <> 'deactivated' OR field IS NULL
FYI, you must use IS NOT and not a comparision operator because NULL doesn't equal anything. Even another NULL;
Since you're using MySQL, you can use the "equal to" operator:
WHERE NOT(field <=> 'deactivated')
In other, more SQL-standards compliant databases, you'd write
WHERE field IS DISTINCT FROM 'deactivated'
I have recently written a blog post on the DISTINCT predicate and how it is supported in various databases.
You can use MySQL's "null-safe equal" operator <=>:
WHERE NOT field <=> 'deactivated'

MySQL comparison with null value

I have a column called CODE in a MySQL table which can be NULL. Say I have some rows with CODE='C' which I want to ignore in my select result set. I can have either CODE=NULL or CODE!='C' in my result set.
The following query does not return a row with CODE as NULL:
SELECT * from TABLE where CODE!='C'
But this query works as expected and I know it is the right way to do it.
SELECT * from TABLE where CODE IS NULL OR CODE!='C'
My question is why does having only CODE!='C' does not return rows where CODE=NULL? Definitely 'C' is not NULL. We are comparing no value to a character here. Can someone throw some light as why it doesn't work that way?
In MySQL, NULL is considered as a 'missing, unknown value', as opposed to no value. Take a look at this MySQL Reference on NULL.
Any arithmetic comparison with NULL does not return true or false, but returns NULL instead., So, NULL != 'C' returns NULL, as opposed to returning true.
Any arithmetic comparison with 'NULL' will return false. To check this in SQL:
SELECT IF(NULL=123,'true','false')
To check NULL values we need to use IS NULL & IS NOT NULL operator.
Based on my tests and the documentation here: http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html
You can compare null and get a boolean result using <=>
NOTE: it looks like NOT EQ operator, but it's EQ operator
For example:
select x <=> y;
or
select #x <=> #y;
This also compares string vs null, string vs string, etc.
In SQL, the NULL value is a special value, not comparable with any other one.
The result of a direct comparison with a NULL is always NULL, although (unfortunately) you may find FALSE in some implementation.
To test a null value you should use IS NULL and IS NOT NULL.
SELECT *
FROM `table_name`
WHERE IFNULL(`column_name` != 'C', TRUE)
The specified problem can also appear in joins and the above answers aren't particularly helpful. The way I prefer to do it is by coalescing to otherwise impossible value. For example, this
select foo from bar
inner join baz on bar.x = baz.y
won't work if bar.x and baz.y are both nulls (join won't bring results). The workaround is to use e.g.
select foo from bar
inner join baz on coalesce(bar.x, -1) = coalesce(baz.y, -1)
where -1 is "impossible" value meaning it can never appear in the data set.
select * from user where application_id='1223333344' and name is null;
I use:
SELECT * from TABLE where NOT(CODE <=> 'C')

MySQL: selecting rows where a column is null

I'm having a problem where when I try to select the rows that have a NULL for a certain column, it returns an empty set. However, when I look at the table in phpMyAdmin, it says null for most of the rows.
My query looks something like this:
SELECT pid FROM planets WHERE userid = NULL
Empty set every time.
A lot of places said to make sure it's not stored as "NULL" or "null" instead of an actual value, and one said to try looking for just a space (userid = ' ') but none of these have worked. There was a suggestion to not use MyISAM and use innoDB because MyISAM has trouble storing null. I switched the table to innoDB but now I feel like the problem may be that it still isn't actually null because of the way it might convert it. I'd like to do this without having to recreate the table as innoDB or anything else, but if I have to, I can certainly try that.
SQL NULL's special, and you have to do WHERE field IS NULL, as NULL cannot be equal to anything,
including itself (ie: NULL = NULL is always false).
See Rule 3 https://en.wikipedia.org/wiki/Codd%27s_12_rules
SELECT pid FROM planets WHERE userid IS NULL
As all are given answers I want to add little more. I had also faced the same issue.
Why did your query fail? You have,
SELECT pid FROM planets WHERE userid = NULL;
This will not give you the expected result, because from mysql doc
In SQL, the NULL value is never true in comparison to any other value, even NULL. An expression that contains NULL always produces a NULL value unless otherwise indicated in the documentation for the operators and functions involved in the expression.
Emphasis mine.
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
Solution
SELECT pid FROM planets WHERE userid IS NULL;
To test for NULL, use the IS NULL and IS NOT NULL operators.
operator IS NULL tests whether a value is NULL.
operator IS NOT NULL tests whether a value is not NULL.
MySQL comparison operators
There's also a <=> operator:
SELECT pid FROM planets WHERE userid <=> NULL
Would work. The nice thing is that <=> can also be used with non-NULL values:
SELECT NULL <=> NULL yields 1.
SELECT 42 <=> 42 yields 1 as well.
See here: https://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html#operator_equal-to
Info from http://w3schools.com/sql/sql_null_values.asp:
1) NULL values represent missing unknown data.
2) By default, a table column can hold NULL values.
3) NULL values are treated differently from other values
4) It is not possible to compare NULL and 0; they are not equivalent.
5) It is not possible to test for NULL values with comparison
operators, such as =, <, or <>.
6) We will have to use the IS NULL and IS NOT NULL operators instead
So in case of your problem:
SELECT pid FROM planets WHERE userid IS NULL
Had the same issue where query:
SELECT * FROM 'column' WHERE 'column' IS NULL;
returned no values.
Seems to be an issue with MyISAM and the same query on the data in InnoDB returned expected results.
Went with:
SELECT * FROM 'column' WHERE 'column' = ' ';
Returned all expected results.
SELECT pid FROM planets WHERE userid is null;
I had the same issue when converting databases from Access to MySQL (using vb.net to communicate with the database).
I needed to assess if a field (field type varchar(1)) was null.
This statement worked for my scenario:
SELECT * FROM [table name] WHERE [field name] = ''