Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result

Tags:

sql

mysql

I expect the result of the third query below to contain id=732. It doesn't. Why is that?

mysql> SELECT id FROM match ORDER BY id DESC LIMIT 5 ;
+------------+
|         id |
+------------+
|        732 | 
|        730 | 
|        655 | 
|        458 | 
|        456 | 
+------------+
5 rows in set (0.00 sec)

mysql> SELECT id FROM email ORDER BY id DESC LIMIT 5 ;
+------------+
|         id |
+------------+
|        731 | 
|        727 | 
|        725 | 
|        724 | 
|        723 | 
+------------+
5 rows in set (0.00 sec)

mysql> SELECT * FROM match WHERE id NOT IN ( SELECT id FROM email ) ;
Empty set (0.00 sec)

There are three NULL entries in table email.id, and no NULL entries in match.id.

The full table / queries can be seen at http://pastebin.ca/1462094

like image 943
Chris Burgess Avatar asked Jun 16 '09 12:06

Chris Burgess


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 SELECT * from in MySQL?

The SELECT statement is used to select data from a database. The data returned is stored in a result table, called the result-set.

What happens if you run a SELECT statement without a WHERE clause?

Using SELECT without a WHERE clause is useful for browsing data from tables. In a WHERE clause, you can specify a search condition (logical expression) that has one or more conditions. When the condition (logical expression) evaluates to true the WHERE clause filter unwanted rows from the result.

What is X in MySQL?

The optional MySQL Server X Plugin is the latest one. It implements its own client server protocol called the X Protocol. Application clients and their drivers feature the alternative protocol and a new X DevAPI programming API. The X DevAPI is an alternative way of acessing MySQL.


2 Answers

From documentation:

To comply with the SQL standard, IN returns NULL not only if the expression on the left hand side is NULL, but also if no match is found in the list and one of the expressions in the list is NULL.

This is exactly your case.

Both IN and NOT IN return NULL which is not an acceptable condition for WHERE clause.

Rewrite your query as follows:

SELECT  *
FROM    match m
WHERE   NOT EXISTS
        (
        SELECT  1
        FROM    email e
        WHERE   e.id = m.id
        )
like image 164
Quassnoi Avatar answered Oct 19 '22 11:10

Quassnoi


... or if you really want to use NOT IN you can use

SELECT * FROM match WHERE id NOT IN ( SELECT id FROM email WHERE id IS NOT NULL)
like image 49
auris Avatar answered Oct 19 '22 10:10

auris