T-SQL: How to Select Values in Value List that are NOT IN the Table?
You should have a table with the list of emails to check. Then do this query:
SELECT E.Email, CASE WHEN U.Email IS NULL THEN 'Not Exists' ELSE 'Exists' END Status
FROM EmailsToCheck E
LEFT JOIN (SELECT DISTINCT Email FROM Users) U
ON E.Email = U.Email
You need to somehow create a table with these values and then use NOT IN
. This can be done with a temporary table, a CTE (Common Table Expression) or a Table Values Constructor (available in SQL-Server 2008):
SELECT email
FROM
( VALUES
('email1')
, ('email2')
, ('email3')
) AS Checking (email)
WHERE email NOT IN
( SELECT email
FROM Users
)
The second result can be found with a LEFT JOIN
or an EXISTS
subquery:
SELECT email
, CASE WHEN EXISTS ( SELECT *
FROM Users u
WHERE u.email = Checking.email
)
THEN 'Exists'
ELSE 'Not exists'
END AS status
FROM
( VALUES
('email1')
, ('email2')
, ('email3')
) AS Checking (email)
For SQL Server 2008
SELECT email,
CASE
WHEN EXISTS(SELECT *
FROM Users U
WHERE E.email = U.email) THEN 'Exist'
ELSE 'Not Exist'
END AS [Status]
FROM (VALUES('email1'),
('email2'),
('email3'),
('email4')) E(email)
For previous versions you can do something similar with a derived table UNION ALL
-ing the constants.
/*The SELECT list is the same as previously*/
FROM (
SELECT 'email1' UNION ALL
SELECT 'email2' UNION ALL
SELECT 'email3' UNION ALL
SELECT 'email4'
) E(email)
Or if you want just the non-existing ones (as implied by the title) rather than the exact resultset given in the question, you can simply do this
SELECT email
FROM (VALUES('email1'),
('email2'),
('email3'),
('email4')) E(email)
EXCEPT
SELECT email
FROM Users