tags:

views:

65

answers:

3
**Table A**
1
2
3
4
5
6


**Table B**
2
3
5

How can I select for entry IDs that only exist in Table B? In this example, I'm looking for a query that returns 1, 4, and 6.

+2  A: 

Try

select value from B where value not in (select value from A)

to get values in B that are not in A.

To get the opposite (values in A not in B) use

select value from A where value not in (select value from B)
Jonathan Fingland
I'd be very curious to see how this performs against the answer cletus provided. My initial thought was to answer with what he wrote but would't this be faster? Mmm.
Paolo Bergantino
If table B can contain NULL values, NOT IN is a dangerous tool, see http://stackoverflow.com/questions/129077/sql-not-in-constraint-and-null-values Consider using NOT EXISTS.
Andomar
+2  A: 

Assuming the column is named 'id', either:

SELECT *
FROM tableA a
WHERE NOT EXISTS (SELECT 1 FROM tableB WHERE id = a.id)

or

SELECT *
FROM TableA
WHERE id NOT IN (SELECT id FROM tableB)

You will probably need to test to see which performs best. MySQL can be a bit unpredictable.

cletus
Ah, that's perfect! Thanks! Performance isn't an issue here as this this is a one-time query.
Eileen
A: 

This avoids IN + subquery:

SELECT A.value FROM A
LEFT OUTER JOIN B ON (A.value = B.value)
WHERE B.value IS NULL

Because IN (subquery) isn't optimized as it is executed for each found row in table A

streetpc
That's up to the query optimizer. For example, Sql Server will execute both queries in the same way.
Andomar
Yes, but the question being for mysql, it is said in the doc that this query is (still in 6.0 apparently) messed up by the optimizer.
streetpc