gymcode
gymcode

Reputation: 4623

SQL Check If Data in Column A Exists in Column B

I have an Employee Table

EmployeeID | Name | EmployeeEmail | ManagerEmail


Every ManagerEmail should belong to a Manager-Level Employee, being their primary email as EmployeeEmail.

I would like to check if there are any ManagerEmail that does not belong to any Employee.


The DBMS that I am using is Microsoft SQL Server Management Studio 2014.

May I know how can I accomplish that?

Thank you.

Upvotes: 0

Views: 1188

Answers (3)

Yogesh Sharma
Yogesh Sharma

Reputation: 50163

You seems want :

select e.*
from Employee e
where e.ManagerEmail is not null and
      not exists (select 1 
                  from Employee e1 
                  where e1.EmployeeEmail = e.ManagerEmail
                 );

EDIT: Added the additional WHERE clause based on the OP's comment.

Upvotes: 4

IShubh
IShubh

Reputation: 364

Try the following query-:

select ManagerEmail from YourTableName 
where ManagerEmail not in (select EmployeeEmail from YourTableName)

SQL Server

Upvotes: 0

Thorsten Kettner
Thorsten Kettner

Reputation: 94859

As this is a very general question, the answer is equally general. Use one of these methods:

  • NOT IN
  • NOT EXISTS
  • EXCEPT
  • an anti join

As it seems that none of these came to mind, you may want to study all of them. You should at least learn how to apply the first three, in my opinion.

Upvotes: 0

Related Questions