0

I have two tables Invitations and Users, both table contain some emails.

I want to count those emails which are present in the Invitation table but not present in the Users table

Invitation

InvitationID    Email
-------------------------------------
    1           [email protected]
    2           [email protected]
    3           [email protected]

Users

UserName                  IsActive
-------------------------------------
[email protected]             InActive
[email protected]       Active
[email protected]           InActive

I tried it like this

SELECT  COUNT(*) FROM Invitations, Users                                     
where Invitations.Email <> Users.UserName

I want like this

Count=1
2
  • So what is the specific issue here? Commented Nov 30, 2012 at 10:34
  • 2
    Bad habits to kick : using old-style JOINs - that old-style comma-separated list of tables style was discontinued with the ANSI-92 SQL Standard - stop using it Commented Nov 30, 2012 at 10:35

3 Answers 3

8

You're getting the wrong answer because you're counting the wrong thing.

Imagine two records, a and b in each table. a<>b and b<>a so you'll get 2, not the 0 you're expecting.

Try this instead

Select count(*) 
from Invitations
     left join Users                                     
     on Invitations.Email = Users.UserName
where Users.UserName is null
Sign up to request clarification or add additional context in comments.

Comments

3

You can try this one:

SELECT COUNT(*)
FROM Invitation
WHERE Email not in (
    SELECT u.username
    FROM Users
)

Comments

3
select count(*)
from Invitation i
where not exists (select 1 from Users u where i.email = u.userName)

This is simplest way in my opinion, you can event read it: count all rows in Invitation table where not exists a row in table Users where userName is equal email.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.