select a value where it doesn't exist in another table

Wai Wong picture Wai Wong · Jun 4, 2010 · Viewed 133.1k times · Source

I have two tables

Table A:

ID
1
2
3
4

Table B:

ID
1
2
3

I have two requests:

  • I want to select all rows in table A that table B doesn't have, which in this case is row 4.
  • I want to delete all rows that table B doesn't have.

I am using SQL Server 2000.

Answer

Tim Schmelter picture Tim Schmelter · Jun 4, 2010

You could use NOT IN:

SELECT A.* FROM A WHERE ID NOT IN(SELECT ID FROM B)

However, meanwhile i prefer NOT EXISTS:

SELECT A.* FROM A WHERE NOT EXISTS(SELECT 1 FROM B WHERE B.ID=A.ID)

There are other options as well, this article explains all advantages and disadvantages very well:

Should I use NOT IN, OUTER APPLY, LEFT OUTER JOIN, EXCEPT, or NOT EXISTS?