Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL "NOT IN" not working

Tags:

mysql

notin

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?

like image 403
jeffery_the_wind Avatar asked Jun 06 '12 12:06

jeffery_the_wind


People also ask

How do I SELECT not in MySQL?

The MySQL NOT condition can be combined with the IN Condition. For example: SELECT * FROM contacts WHERE first_name NOT IN ('Joseph','Andrew','Brad'); This MySQL NOT example would return all rows from the contacts table where the first_name is not Joseph, Andrew, or Brad.

What is the use of NOT IN operator in MySQL?

The NOT operator displays a record if the condition(s) is NOT TRUE.

Is not in function SQL?

The SQL Server NOT IN operator is used to replace a group of arguments using the <> (or !=) operator that are combined with an AND. It can make code easier to read and understand for SELECT, UPDATE or DELETE SQL commands. Generally, it will not change performance characteristics.

Which is faster in SQL in or not in?

Your answer So IN is faster in some circumstances. The best way to know is to profile both on your database with your specific data to see which is faster. So, in this case, the method using OR is about 30% slower. Adding more terms makes the difference larger.


2 Answers

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
like image 189
Vishwanath Dalvi Avatar answered Sep 28 '22 10:09

Vishwanath Dalvi


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);
like image 44
Kibbee Avatar answered Sep 28 '22 09:09

Kibbee