SQL Select where doesnt (not) exist in another table?

Posted on 2009-04-25
Last Modified: 2012-05-06
Another SQL question for you experts.

I have 2 tables:
tblContacts (ID, Name, etc)
tblContactGroupMapping(contactID, groupID)

I want to write a query that will select all the Contacts who are not assigned to at least 1 group in the tblContactGroupMapping table.

It seems like it should be easy with set operations, but i've never used those in SQL... or is there a better way?
Question by:BobBarker_99
    LVL 25

    Accepted Solution

    Try -
    Select c.*
    from tblContacts c
    where not exists (select null from tblcontactgroupmapping where contactid =

    Open in new window

    LVL 41

    Assisted Solution

    Another alternative is using left join. Please check this out.

    select a.* from tblContacts a
    left join tblContactGroupMapping b on a.ID = b.contactID
    where b.groupID is null

    Open in new window


    Assisted Solution


    select * 
    from tblContacts
    where not exists (select * 
    					from tblContactGroupMapping
    					where tblContactGroupMapping.ContactID = tblContacts.ID)

    Open in new window


    Author Closing Comment

    THanks.  THey all work great, and taught me a little more about sql.  

    Featured Post

    Find Ransomware Secrets With All-Source Analysis

    Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

    Join & Write a Comment

    Suggested Solutions

    Having an SQL database can be a big investment for a small company. Hardware, setup and of course, the price of software all add up to a big bill that some companies may not be able to absorb.  Luckily, there is a free version SQL Express, but does …
    JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
    Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
    Via a live example, show how to shrink a transaction log file down to a reasonable size.

    728 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now