Click here to Skip to main content
15,891,204 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have three tables namely contact, schoolcontact and userdetails where all the three tables are linked by the column ContactID. Now I want to find the record that are present only in the table Contact and not in userdetails and schoolcontact. Can you please help me to query this problem. I tried the follwing query

SQL
select * from [TflStars].[dbo].[Contact] 
where [ContactID] NOT IN ( select [ContactID] from [TflStars].[dbo].[UserDetail] AND select [ContactID] from [TflStars].[dbo].[SchoolContact]) 


It shows an syntax error near the keyword 'AND'
Posted
Updated 19-May-15 5:24am
v2

There are several ways to do it. You are on the right track but just need to break up your SELECT statements in the WHERE clause.

For example:
SQL
SELECT *
FROM Contact
WHERE ContactID NOT IN (SELECT ContactID FROM UserDetail)
AND ContactID NOT IN (SELECT ContactID FROM SchoolContact)


Or another way:
SQL
SELECT *
FROM Contact c 
LEFT JOIN UserDetail d ON c.ConactID = d.ContactID  
LEFT JOIN SchoolContact s ON c.ContactID = s.ContactID
WHERE d.ContactID IS NULL AND s.ContactID IS NULL -- since they are left joined they will be null if no match


Or even:
SQL
SELECT *
FROM Contact
WHERE ContactID NOT IN (
  SELECT ContactID FROM UserDetail
  UNION 
  SELECT ContactID FROM SchoolContact )


I would test each case to make sure none of them are too slow in your database.
 
Share this answer
 
Hi,

There is a small correction of bracket. That will get rid of the error and show you the correct result.

SQL
select * from [TflStars].[dbo].[Contact]
where [ContactID] NOT IN ( select [ContactID] from [TflStars].[dbo].[UserDetail]) AND [ContactID] NOT IN (select [ContactID] from [TflStars].[dbo].[SchoolContact])


But inner query may slow down the execution of query. So you have another option of combination of "except" and "union". Please try below query.

SQL
select ContactID  from [TflStars]
 EXCEPT
(SELECT ContactID FROM UserDetail
  UNION
 SELECT ContactID FROM SchoolContact
)



Please let me know if you have any concern or query or if you are still facing issue.

Thanks
Advay Pandya
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900