Search code examples
sql-servert-sqljoinright-join

Selecting Records From 1 Table That Don't Appear In Another Table


I am hoping someone might be able to help me with this issue I am having. I have a table of customers - let's call it Table C. And I have a second table of customers that are not to be called - let's call it Table D.

I would like to pull all of the needed information (name, address, phone, etc...) from Table C unless the customer appears in Table D.

In the example shown below, I'd like to have data returned for all customers except John Doe (ID: 1) and Fred Savage (ID: 5)

Data Example

I think a RIGHT OUTER JOIN might be applicable here, but I have not used this type of join before.


Solution

  • Use NOT EXISTS to do this:

    SELECT c.*
    FROM tableC c
    WHERE NOT EXISTS (
            SELECT *
            FROM tableD d
            WHERE c.customerID = d.customerid
            );