-1

Let's say I have these two tables:

    Table 1                        Table 2
  PName  |   FID                 PName   |  FID
  ----------------               ---------------
  Dog    |   1                   Dog     |  1
  Dog    |   2                   Cat     |  2
  Cat    |   2                   Cat     |  4
  Cat    |   3

What is the right query to select the two fields combinations of the first table that are not present in the second?

What I want to get is

    Table 1                      
  PName  |   FID                 
  ----------------               
  Dog    |   2                   
  Cat    |   3

Would that be?

SELECT * FROM [Table 1] WHERE ([Table 1].[PName] NOT IN (SELECT [Table 2].[PName] FROM [Table 2]) AND ([Table 1].[FID] NOT IN (SELECT [Table 2].[FID] FROM [Table 2]))

3 Answers3

3

I'd use except.

select * from table1
except
select * from table2

It's worth mentioning this great answer discussing except vs not in especially in regards to NULL

S3S
  • 24,809
  • 5
  • 26
  • 45
2

I might suggest something like the following:

select t1.* 
from table1 t1 
where not exists (select 1  
                  from table2 t2 
                  where t2.pname = t1.pname and t2.fid = t1.fid
                 );
Yogesh Sharma
  • 49,870
  • 5
  • 26
  • 52
Lee Mac
  • 15,615
  • 6
  • 32
  • 80
1

You need a left join and take only the rows where there is no match:

select t1.*
from t1 left join t2
on t1.pname = t2.pname and t1.fid = t2.fid
where t2.pname is null and t2.fid is null

See the demo

forpas
  • 160,666
  • 10
  • 38
  • 76