tags:

views:

62

answers:

3

Hello, I am trying to join 2 tables and trying to fetch the records, which do not have values in the join column of the 2nd table. For example: Table 1 Id column values: 1, 2, 3, 4,

Table 2 Id column values: 1, 3,

Given the above example of the values in the join columns of the 2 tables, I want to fetch records from table1 with ids 2 and 4, because they are not present in table2.

Any help would be much appreciated.

My SQL has gotten rusty to the introduction of JPA frameworks, but today I cannot run away from not knowing it, it seems :(

Thanks!

+3  A: 
select t1.id
from Table1 t1
left outer join Table2 t2 on t1.id = t2.id
where t2.id is null
RedFilter
Hey thanks for that suggestion. Will try it. Cheers!
PaiS
+2  A: 
SELECT * FROM table1 WHERE table1.id NOT IN (SELECT id from table2)
Dan Williams
Hey, thanks that was fairly simple :), I really need to brush up my query language.
PaiS
Beware of NULLs in the ID column in table2, when using a `NOT IN` clause.
Mark Bannister
This is likely to be the wrost performing of the possibilities, As always test all fothem to see.
HLGEM
meh, http://blog.sqlauthority.com/2008/04/22/sql-server-better-performance-left-join-or-not-in/Always test your query performance on your data and your server.
Dan Williams
+1  A: 

NOT EXISTS variant:

SELECT * FROM table1 WHERE NOT EXISTS 
(SELECT NULL from table2 WHERE table2.id = table1.id)
Mark Bannister