Postgresql – How to get users how do not have a group (through join table)

postgresql

I want to get users how are not present in a group. The group name is "everybody".

I have a join table called groups_users with user_id and group_id.

I did this

SELECT users.email
FROM users
  WHERE NOT EXISTS (
    SELECT groups_users.user_id 
    FROM groups_users
    INNER JOIN groups ON groups_users.group_id = groups.id 
    WHERE groups.name = 'everybody'
);

But it doesn't return any result. I have a user without any group and it doesn't appear. Did I miss something?

Best Answer

Right now your (uncorrelated) subquery returns all user IDs, which is obviously a non-empty set. You need to correlate the subquery to the particular user from the outer query:

SELECT users.email
FROM users
  WHERE NOT EXISTS (
    SELECT groups_users.user_id 
    FROM groups_users
    INNER JOIN groups ON groups_users.group_id = groups.id 
    WHERE groups.name = 'everybody'
    AND groups_users.user_id = users.id
);