54

Table 1 2 columns: ID, Name

Table 2 2 columns: ID, Name

What is a query to show names from Table 1 that are not in table 2? So filtering out all the names in table 1 that are in table 2 gives the result query. Filtering is on ID not name.

philipxy
  • 14,867
  • 6
  • 39
  • 83
Nick LaMarca
  • 8,076
  • 31
  • 93
  • 152
  • Nick, all of the suggestions below (those using a join and checking for null and those that are suggest using a NOT IN clause) will work. However, if speed is an issue, I believe that NOT IN is slower. If speed isn't an issue, then the NOT IN is probably clearer. – Matt Oct 28 '10 at 16:23
  • The opposite of an INNER JOIN is an OUTER JOIN and it comes in two flavors: LEFT and RIGHT depending on which side of of the JOIN you want to "outer" – Paul Sasik Oct 28 '10 at 16:23
  • 2
    @Matt: your belief is wrong, `NOT IN` is faster. – Quassnoi Oct 28 '10 at 21:51
  • 2
    You are quite right @Quassnoi. It took me a while to get the time and a dataset large enough to measure it, but even the query execution plan shows that NOT IN is about 50% faster. I'm not sure who told me that dirty lie in the first place! :) – Matt Nov 02 '10 at 17:44

5 Answers5

79
Select * from table1
left join table2 on table1.id = table2.id
where table2.id is null
Andrew
  • 26,629
  • 5
  • 63
  • 86
39

This should perform better than the left join...is null version. See here and here for comparisons.

select t1.id, t1.name
    from table1 t1
    where not exists(select null from table2 t2 where t2.id = t1.id)
Joe Stefanelli
  • 132,803
  • 19
  • 237
  • 235
19

Use this query

select
t1.*
from table1 t1
left outer join table2 t2
on t1.id=t2.id
where t2.id is null

this works by joining everything in t1 to whatever exists in t2. the where clause filters out all of the records that don't exist in t2.

DForck42
  • 19,789
  • 13
  • 59
  • 84
3
SELECT Table1.ID, Table1.Name, Table2.ID 
FROM Table1 LEFT OUTER JOIN Table2 ON Table1.ID = Table2.ID 
WHERE Table2.ID IS NULL 

I think that should do it.

i_saw_drones
  • 3,486
  • 1
  • 31
  • 50
Matt
  • 562
  • 1
  • 4
  • 8
1

Try like this:

select t1.*
from table1 as t1
where t1.id not in 
  (select distinct t2.id from table2 as t2);
Dominique
  • 16,450
  • 15
  • 56
  • 112
stanieviv
  • 11
  • 1