sql: check if entry in table A exists in table B

codingknob picture codingknob · Apr 11, 2013 · Viewed 235.3k times · Source

I have a definition table that I know is not being maintained very well, lets call this table A. I have another table (call it table B) that is much smaller and ideally should be a subset of table A but I know that table A is somewhat stale and does not contain new entries that are in Table B.

Note, that tables A and B have different columns.

Table A:
ID, Name, blah, blah, blah, blah

Table B:
ID, Name

I want all rows in Table B such that the ID in Table B does NOT exist in Table A. This does not just match rows in Table A; I want only rows in Table B where the ID does NOT exist at all in Table A.

Answer

gdoron is supporting Monica picture gdoron is supporting Monica · Apr 11, 2013
SELECT *
FROM   B
WHERE  NOT EXISTS (SELECT 1 
                   FROM   A 
                   WHERE  A.ID = B.ID)