Search code examples
sqlsql-server-2000

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


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.


Solution

  • 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?