18

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?

jeffery_the_wind
  • 17,048
  • 34
  • 98
  • 160

3 Answers3

32

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
Vishwanath Dalvi
  • 35,388
  • 41
  • 123
  • 155
  • Nice, they both work and seem to take about the same amount of time. Thanks! – jeffery_the_wind Jun 06 '12 at 13:09
  • 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. – Syntax Junkie Feb 14 '23 at 17:23
18

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);
Kibbee
  • 65,369
  • 27
  • 142
  • 182
1
select * 
 from table1 
 where date >= "2012-01-01" 
 and `key` not in (select some_key from table2);
Sarfraz
  • 377,238
  • 77
  • 533
  • 578