MySQL "NOT IN" not working
Asked Answered
H

3

20

Strange thing happening. I am having a problem with my MySQL Community Server 5.1 installed on windows NOT IN query. When I do this query:

select * 
  from table1 
  where date >= "2012-01-01";

returns 582 rows

select * 
  from table1 
  where date >= "2012-01-01" 
    and the_key in (select some_key from table2);

returns 15 rows

so I would expect that the following query would return 582 - 15 = 567 rows

select * 
 from table1 
 where date >= "2012-01-01" 
 and the_key not in (select some_key from table2);

returns 0 rows

Why is this last query not returning any rows?

Handshake answered 6/6, 2012 at 12:45 Comment(5)
key is a keyword in SQL try quoting it with backticksBodi
Try where (date >= "2012-01-01") and (key not in ...); MySQL docs are vague on the not in operator and state that expr NOT IN (value,...) is the same as NOT (expr IN (value,...)), which might result in NOT((date >= "2012-01-01" and key) IN (...)) in your caseWakerife
yes some_key can be null, it is null some timesHandshake
If the subquery returns null (in your case if some_key is null) then the "not in" clause does not work. Filter subquery such that some_key is not nullNagano
"not in" doesn't work . why? Is that a bug?Squarerigger
A
33

Try this.

select * 
 from table1 
 where date >= "2012-01-01" 
 and `key` not in (select some_key from table2 where some_key is not null);

Or using not exists

 select * 
 from table1 
 where date >= "2012-01-01" and not exists ( select some_key from table2 where table2.some_key = table1.key
Ainslie answered 6/6, 2012 at 12:49 Comment(2)
Nice, they both work and seem to take about the same amount of time. Thanks!Handshake
I would have up-voted this answer, but it only gives alternatives to the original approach. It doesn't explain why the original approach doesn't work. The answer from @Kibbee does explain what the problem is.Luetic
S
19

Most likely you have some NULL values in your "key" column. NULL comparisons always return null, which evaluates to false. This can be counter intuitive. For example

SELECT * FROM MyTable WHERE SomeValue <> 0 

Would not return the values with SomeValue = NULL. Even though intuitively, NULL does not equal zero. So to fix the query you have, you should probably do the following.

select * from table1 where date >= "2012-01-01" 
and (key not in (select some_key from table2) OR key IS NULL);
Steno answered 6/6, 2012 at 12:50 Comment(1)
In my case there also where null values in -> not in array query. ThanksIndihar
C
1
select * 
 from table1 
 where date >= "2012-01-01" 
 and `key` not in (select some_key from table2);
Cadelle answered 6/6, 2012 at 12:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.