tags:

views:

838

answers:

6

Hi,

I need to wite a query that will retrieve the records from Table A , provided that the key in Table A does not exist in Table B.

Any help will be appreciated.

Thanks

+1  A: 
SELECT *
FROM A
WHERE ID NOT IN
     (SELECT ID FROM B)
Galwegian
Note that this can be slow on large data volumes and the solution described by kristof below is more efficient.
ConcernedOfTunbridgeWells
A: 

Assuming: TableA's Id = Id TableB's Id = Id

select * from TableA ta where ta.Id not in (select Id from TableB)
CubanX
+8  A: 
select a.* 
from
    tableA a
    left join tableB b
     ON a.id = b.id
where
    b.id is null
kristof
+1 - According to the powers that be from Microsoft, outer joining is faster than in or where not exists, at least on SQL Server 2000. I don't know if this has changed on SQL Server 2005.
ConcernedOfTunbridgeWells
+1 - Although I think that the accepted answer can be easier to think about, from my experience, this SQL has proved much faster for large data volumes.
Russ Cam
+2  A: 

Use a left join. The DB tries to map datasets from TableB to TableA using the id fields. If there is no fitting data set available in TableB, the TableB data gets NULL. Now you just have to check for TableB.id to be NULL.

SELECT TableA.* FROM TableA LEFT JOIN TableB ON TableA.id = TableB.id WHERE TableB.id IS NULL
okoman
A: 
SELECT * FROM TableA
WHERE NOT Exists(SELECT * FROM TableB WHERE id=TableA.id)

also works and it's almost self documenting...

Kaniu
+1  A: 

None of the above solutions would work if the key comprises of multiple columns.

If the tables have compound primary keys, you'll have to use a "NOT EXISTS" clause similar to the one below.

SELECT * 
  FROM TableA AS a 
 WHERE NOT EXISTS (
                   SELECT * 
                     FROM TableB b 
                    WHERE b.id1 = a.id1 
                          AND b.id2 = a.id2 
                          AND b.id3 = a.id3
                  );
Rahul
+1 This constructs best matches the natural language used in the question.
onedaywhen